]> git.saurik.com Git - apt.git/blob - methods/gpgv.cc
add apt-key support for armored GPG key files (*.asc)
[apt.git] / methods / gpgv.cc
1 #include <config.h>
2
3 #include <apt-pkg/configuration.h>
4 #include <apt-pkg/error.h>
5 #include <apt-pkg/gpgv.h>
6 #include <apt-pkg/strutl.h>
7 #include <apt-pkg/fileutl.h>
8 #include "aptmethod.h"
9
10 #include <ctype.h>
11 #include <errno.h>
12 #include <stddef.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/wait.h>
17 #include <unistd.h>
18
19 #include <array>
20 #include <algorithm>
21 #include <sstream>
22 #include <iterator>
23 #include <iostream>
24 #include <string>
25 #include <vector>
26
27 #include <apti18n.h>
28
29 using std::string;
30 using std::vector;
31
32 #define GNUPGPREFIX "[GNUPG:]"
33 #define GNUPGBADSIG "[GNUPG:] BADSIG"
34 #define GNUPGERRSIG "[GNUPG:] ERRSIG"
35 #define GNUPGNOPUBKEY "[GNUPG:] NO_PUBKEY"
36 #define GNUPGVALIDSIG "[GNUPG:] VALIDSIG"
37 #define GNUPGGOODSIG "[GNUPG:] GOODSIG"
38 #define GNUPGEXPKEYSIG "[GNUPG:] EXPKEYSIG"
39 #define GNUPGEXPSIG "[GNUPG:] EXPSIG"
40 #define GNUPGREVKEYSIG "[GNUPG:] REVKEYSIG"
41 #define GNUPGNODATA "[GNUPG:] NODATA"
42 #define APTKEYWARNING "[APTKEY:] WARNING"
43 #define APTKEYERROR "[APTKEY:] ERROR"
44
45 struct Digest {
46 enum class State {
47 Untrusted,
48 Weak,
49 Trusted,
50 } state;
51 char name[32];
52
53 State getState() const {
54 std::string optionUntrusted;
55 std::string optionWeak;
56 strprintf(optionUntrusted, "APT::Hashes::%s::Untrusted", name);
57 strprintf(optionWeak, "APT::Hashes::%s::Weak", name);
58 if (_config->FindB(optionUntrusted, state == State::Untrusted) == true)
59 return State::Untrusted;
60 if (_config->FindB(optionWeak, state == State::Weak) == true)
61 return State::Weak;
62
63 return state;
64 }
65 };
66
67 static constexpr Digest Digests[] = {
68 {Digest::State::Untrusted, "Invalid digest"},
69 {Digest::State::Untrusted, "MD5"},
70 {Digest::State::Weak, "SHA1"},
71 {Digest::State::Weak, "RIPE-MD/160"},
72 {Digest::State::Trusted, "Reserved digest"},
73 {Digest::State::Trusted, "Reserved digest"},
74 {Digest::State::Trusted, "Reserved digest"},
75 {Digest::State::Trusted, "Reserved digest"},
76 {Digest::State::Trusted, "SHA256"},
77 {Digest::State::Trusted, "SHA384"},
78 {Digest::State::Trusted, "SHA512"},
79 {Digest::State::Trusted, "SHA224"},
80 };
81
82 static Digest FindDigest(std::string const & Digest)
83 {
84 int id = atoi(Digest.c_str());
85 if (id >= 0 && static_cast<unsigned>(id) < _count(Digests)) {
86 return Digests[id];
87 } else {
88 return Digests[0];
89 }
90 }
91
92 struct Signer {
93 std::string key;
94 std::string note;
95 };
96 static bool IsTheSameKey(std::string const &validsig, std::string const &goodsig) {
97 // VALIDSIG reports a keyid (40 = 24 + 16), GOODSIG is a longid (16) only
98 return validsig.compare(24, 16, goodsig, strlen("GOODSIG "), 16) == 0;
99 }
100
101 class GPGVMethod : public aptMethod
102 {
103 private:
104 string VerifyGetSigners(const char *file, const char *outfile,
105 std::string const &key,
106 vector<string> &GoodSigners,
107 vector<string> &BadSigners,
108 vector<string> &WorthlessSigners,
109 vector<Signer> &SoonWorthlessSigners,
110 vector<string> &NoPubKeySigners);
111 protected:
112 virtual bool URIAcquire(std::string const &Message, FetchItem *Itm) APT_OVERRIDE;
113 public:
114 GPGVMethod() : aptMethod("gpgv","1.0",SingleInstance | SendConfig) {};
115 };
116 static void PushEntryWithKeyID(std::vector<std::string> &Signers, char * const buffer, bool const Debug)
117 {
118 char * const msg = buffer + sizeof(GNUPGPREFIX);
119 char *p = msg;
120 // skip the message
121 while (*p && !isspace(*p))
122 ++p;
123 // skip the seperator whitespace
124 ++p;
125 // skip the hexdigit fingerprint
126 while (*p && isxdigit(*p))
127 ++p;
128 // cut the rest from the message
129 *p = '\0';
130 if (Debug == true)
131 std::clog << "Got " << msg << " !" << std::endl;
132 Signers.push_back(msg);
133 }
134 static void PushEntryWithUID(std::vector<std::string> &Signers, char * const buffer, bool const Debug)
135 {
136 std::string msg = buffer + sizeof(GNUPGPREFIX);
137 auto const nuke = msg.find_last_not_of("\n\t\r");
138 if (nuke != std::string::npos)
139 msg.erase(nuke + 1);
140 if (Debug == true)
141 std::clog << "Got " << msg << " !" << std::endl;
142 Signers.push_back(msg);
143 }
144 string GPGVMethod::VerifyGetSigners(const char *file, const char *outfile,
145 std::string const &key,
146 vector<string> &GoodSigners,
147 vector<string> &BadSigners,
148 vector<string> &WorthlessSigners,
149 vector<Signer> &SoonWorthlessSigners,
150 vector<string> &NoPubKeySigners)
151 {
152 bool const Debug = DebugEnabled();
153
154 if (Debug == true)
155 std::clog << "inside VerifyGetSigners" << std::endl;
156
157 int fd[2];
158 bool const keyIsID = (key.empty() == false && key[0] != '/');
159
160 if (pipe(fd) < 0)
161 return "Couldn't create pipe";
162
163 pid_t pid = fork();
164 if (pid < 0)
165 return string("Couldn't spawn new process") + strerror(errno);
166 else if (pid == 0)
167 ExecGPGV(outfile, file, 3, fd, (keyIsID ? "" : key));
168 close(fd[1]);
169
170 FILE *pipein = fdopen(fd[0], "r");
171
172 // Loop over the output of apt-key (which really is gnupg), and check the signatures.
173 std::vector<std::string> ValidSigners;
174 std::vector<std::string> ErrSigners;
175 size_t buffersize = 0;
176 char *buffer = NULL;
177 bool gotNODATA = false;
178 while (1)
179 {
180 if (getline(&buffer, &buffersize, pipein) == -1)
181 break;
182 if (Debug == true)
183 std::clog << "Read: " << buffer << std::endl;
184
185 // Push the data into three separate vectors, which
186 // we later concatenate. They're kept separate so
187 // if we improve the apt method communication stuff later
188 // it will be better.
189 if (strncmp(buffer, GNUPGBADSIG, sizeof(GNUPGBADSIG)-1) == 0)
190 PushEntryWithUID(BadSigners, buffer, Debug);
191 else if (strncmp(buffer, GNUPGERRSIG, sizeof(GNUPGERRSIG)-1) == 0)
192 PushEntryWithKeyID(ErrSigners, buffer, Debug);
193 else if (strncmp(buffer, GNUPGNOPUBKEY, sizeof(GNUPGNOPUBKEY)-1) == 0)
194 {
195 PushEntryWithKeyID(NoPubKeySigners, buffer, Debug);
196 ErrSigners.erase(std::remove_if(ErrSigners.begin(), ErrSigners.end(), [&](std::string const &errsig) {
197 return errsig.compare(strlen("ERRSIG "), 16, buffer, sizeof(GNUPGNOPUBKEY), 16) == 0; }), ErrSigners.end());
198 }
199 else if (strncmp(buffer, GNUPGNODATA, sizeof(GNUPGNODATA)-1) == 0)
200 gotNODATA = true;
201 else if (strncmp(buffer, GNUPGEXPKEYSIG, sizeof(GNUPGEXPKEYSIG)-1) == 0)
202 PushEntryWithUID(WorthlessSigners, buffer, Debug);
203 else if (strncmp(buffer, GNUPGEXPSIG, sizeof(GNUPGEXPSIG)-1) == 0)
204 PushEntryWithUID(WorthlessSigners, buffer, Debug);
205 else if (strncmp(buffer, GNUPGREVKEYSIG, sizeof(GNUPGREVKEYSIG)-1) == 0)
206 PushEntryWithUID(WorthlessSigners, buffer, Debug);
207 else if (strncmp(buffer, GNUPGGOODSIG, sizeof(GNUPGGOODSIG)-1) == 0)
208 PushEntryWithKeyID(GoodSigners, buffer, Debug);
209 else if (strncmp(buffer, GNUPGVALIDSIG, sizeof(GNUPGVALIDSIG)-1) == 0)
210 {
211 std::istringstream iss(buffer + sizeof(GNUPGVALIDSIG));
212 vector<string> tokens{std::istream_iterator<string>{iss},
213 std::istream_iterator<string>{}};
214 auto const sig = tokens[0];
215 // Reject weak digest algorithms
216 Digest digest = FindDigest(tokens[7]);
217 switch (digest.getState()) {
218 case Digest::State::Weak:
219 // Treat them like an expired key: For that a message about expiry
220 // is emitted, a VALIDSIG, but no GOODSIG.
221 SoonWorthlessSigners.push_back({sig, digest.name});
222 if (Debug == true)
223 std::clog << "Got weak VALIDSIG, key ID: " << sig << std::endl;
224 break;
225 case Digest::State::Untrusted:
226 // Treat them like an expired key: For that a message about expiry
227 // is emitted, a VALIDSIG, but no GOODSIG.
228 WorthlessSigners.push_back(sig);
229 GoodSigners.erase(std::remove_if(GoodSigners.begin(), GoodSigners.end(), [&](std::string const &goodsig) {
230 return IsTheSameKey(sig, goodsig); }), GoodSigners.end());
231 if (Debug == true)
232 std::clog << "Got untrusted VALIDSIG, key ID: " << sig << std::endl;
233 break;
234
235 case Digest::State::Trusted:
236 if (Debug == true)
237 std::clog << "Got trusted VALIDSIG, key ID: " << sig << std::endl;
238 break;
239 }
240
241 ValidSigners.push_back(sig);
242 }
243 else if (strncmp(buffer, APTKEYWARNING, sizeof(APTKEYWARNING)-1) == 0)
244 Warning("%s", buffer + sizeof(APTKEYWARNING));
245 else if (strncmp(buffer, APTKEYERROR, sizeof(APTKEYERROR)-1) == 0)
246 _error->Error("%s", buffer + sizeof(APTKEYERROR));
247 }
248 fclose(pipein);
249 free(buffer);
250 std::move(ErrSigners.begin(), ErrSigners.end(), std::back_inserter(WorthlessSigners));
251
252 // apt-key has a --keyid parameter, but this requires gpg, so we call it without it
253 // and instead check after the fact which keyids where used for verification
254 if (keyIsID == true)
255 {
256 if (Debug == true)
257 std::clog << "GoodSigs needs to be limited to keyid " << key << std::endl;
258 bool foundGood = false;
259 for (auto const &k: VectorizeString(key, ','))
260 {
261 if (std::find(ValidSigners.begin(), ValidSigners.end(), k) == ValidSigners.end())
262 continue;
263 // we look for GOODSIG here as well as an expired sig is a valid sig as well (but not a good one)
264 std::string const goodfingerprint = "GOODSIG " + k;
265 std::string const goodlongkeyid = "GOODSIG " + k.substr(24, 16);
266 foundGood = std::find(GoodSigners.begin(), GoodSigners.end(), goodfingerprint) != GoodSigners.end();
267 if (Debug == true)
268 std::clog << "Key " << k << " is valid sig, is " << goodfingerprint << " also a good one? " << (foundGood ? "yes" : "no") << std::endl;
269 std::string goodsig;
270 if (foundGood == false)
271 {
272 foundGood = std::find(GoodSigners.begin(), GoodSigners.end(), goodlongkeyid) != GoodSigners.end();
273 if (Debug == true)
274 std::clog << "Key " << k << " is valid sig, is " << goodlongkeyid << " also a good one? " << (foundGood ? "yes" : "no") << std::endl;
275 goodsig = goodlongkeyid;
276 }
277 else
278 goodsig = goodfingerprint;
279 if (foundGood == false)
280 continue;
281 std::copy(GoodSigners.begin(), GoodSigners.end(), std::back_insert_iterator<std::vector<std::string> >(NoPubKeySigners));
282 GoodSigners.clear();
283 GoodSigners.push_back(goodsig);
284 NoPubKeySigners.erase(
285 std::remove(NoPubKeySigners.begin(),
286 std::remove(NoPubKeySigners.begin(), NoPubKeySigners.end(), goodfingerprint),
287 goodlongkeyid),
288 NoPubKeySigners.end()
289 );
290 break;
291 }
292 if (foundGood == false)
293 {
294 std::copy(GoodSigners.begin(), GoodSigners.end(), std::back_insert_iterator<std::vector<std::string> >(NoPubKeySigners));
295 GoodSigners.clear();
296 }
297 }
298
299 int status;
300 waitpid(pid, &status, 0);
301 if (Debug == true)
302 {
303 ioprintf(std::clog, "gpgv exited with status %i\n", WEXITSTATUS(status));
304 }
305
306 if (Debug)
307 {
308 std::cerr << "Summary:" << std::endl << " Good: ";
309 std::copy(GoodSigners.begin(), GoodSigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
310 std::cerr << std::endl << " Bad: ";
311 std::copy(BadSigners.begin(), BadSigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
312 std::cerr << std::endl << " Worthless: ";
313 std::copy(WorthlessSigners.begin(), WorthlessSigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
314 std::cerr << std::endl << " SoonWorthless: ";
315 std::for_each(SoonWorthlessSigners.begin(), SoonWorthlessSigners.end(), [](Signer const &sig) { std::cerr << sig.key << ", "; });
316 std::cerr << std::endl << " NoPubKey: ";
317 std::copy(NoPubKeySigners.begin(), NoPubKeySigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
318 std::cerr << std::endl << " NODATA: " << (gotNODATA ? "yes" : "no") << std::endl;
319 }
320
321 if (WEXITSTATUS(status) == 112)
322 {
323 // acquire system checks for "NODATA" to generate GPG errors (the others are only warnings)
324 std::string errmsg;
325 //TRANSLATORS: %s is a single techy word like 'NODATA'
326 strprintf(errmsg, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NODATA");
327 return errmsg;
328 }
329 else if (gotNODATA)
330 {
331 // acquire system checks for "NODATA" to generate GPG errors (the others are only warnings)
332 std::string errmsg;
333 //TRANSLATORS: %s is a single techy word like 'NODATA'
334 strprintf(errmsg, _("Signed file isn't valid, got '%s' (does the network require authentication?)"), "NODATA");
335 return errmsg;
336 }
337 else if (WEXITSTATUS(status) == 0)
338 {
339 if (keyIsID)
340 {
341 // gpgv will report success, but we want to enforce a certain keyring
342 // so if we haven't found the key the valid we found is in fact invalid
343 if (GoodSigners.empty())
344 return _("At least one invalid signature was encountered.");
345 }
346 else
347 {
348 if (GoodSigners.empty())
349 return _("Internal error: Good signature, but could not determine key fingerprint?!");
350 }
351 return "";
352 }
353 else if (WEXITSTATUS(status) == 1)
354 return _("At least one invalid signature was encountered.");
355 else if (WEXITSTATUS(status) == 111)
356 return _("Could not execute 'apt-key' to verify signature (is gnupg installed?)");
357 else
358 return _("Unknown error executing apt-key");
359 }
360
361 bool GPGVMethod::URIAcquire(std::string const &Message, FetchItem *Itm)
362 {
363 URI const Get = Itm->Uri;
364 string const Path = Get.Host + Get.Path; // To account for relative paths
365 std::string const key = LookupTag(Message, "Signed-By");
366 vector<string> GoodSigners;
367 vector<string> BadSigners;
368 // a worthless signature is a expired or revoked one
369 vector<string> WorthlessSigners;
370 vector<Signer> SoonWorthlessSigners;
371 vector<string> NoPubKeySigners;
372
373 FetchResult Res;
374 Res.Filename = Itm->DestFile;
375 URIStart(Res);
376
377 // Run apt-key on file, extract contents and get the key ID of the signer
378 string const msg = VerifyGetSigners(Path.c_str(), Itm->DestFile.c_str(), key,
379 GoodSigners, BadSigners, WorthlessSigners,
380 SoonWorthlessSigners, NoPubKeySigners);
381 if (_error->PendingError())
382 return false;
383
384 // Check if all good signers are soon worthless and warn in that case
385 if (std::all_of(GoodSigners.begin(), GoodSigners.end(), [&](std::string const &good) {
386 return std::any_of(SoonWorthlessSigners.begin(), SoonWorthlessSigners.end(), [&](Signer const &weak) {
387 return IsTheSameKey(weak.key, good);
388 });
389 }))
390 {
391 for (auto const & Signer : SoonWorthlessSigners)
392 // TRANSLATORS: The second %s is the reason and is untranslated for repository owners.
393 Warning(_("Signature by key %s uses weak digest algorithm (%s)"), Signer.key.c_str(), Signer.note.c_str());
394 }
395
396 if (GoodSigners.empty() || !BadSigners.empty() || !NoPubKeySigners.empty())
397 {
398 string errmsg;
399 // In this case, something bad probably happened, so we just go
400 // with what the other method gave us for an error message.
401 if (BadSigners.empty() && WorthlessSigners.empty() && NoPubKeySigners.empty())
402 errmsg = msg;
403 else
404 {
405 if (!BadSigners.empty())
406 {
407 errmsg += _("The following signatures were invalid:\n");
408 for (vector<string>::iterator I = BadSigners.begin();
409 I != BadSigners.end(); ++I)
410 errmsg += (*I + "\n");
411 }
412 if (!WorthlessSigners.empty())
413 {
414 errmsg += _("The following signatures were invalid:\n");
415 for (vector<string>::iterator I = WorthlessSigners.begin();
416 I != WorthlessSigners.end(); ++I)
417 errmsg += (*I + "\n");
418 }
419 if (!NoPubKeySigners.empty())
420 {
421 errmsg += _("The following signatures couldn't be verified because the public key is not available:\n");
422 for (vector<string>::iterator I = NoPubKeySigners.begin();
423 I != NoPubKeySigners.end(); ++I)
424 errmsg += (*I + "\n");
425 }
426 }
427 // this is only fatal if we have no good sigs or if we have at
428 // least one bad signature. good signatures and NoPubKey signatures
429 // happen easily when a file is signed with multiple signatures
430 if(GoodSigners.empty() or !BadSigners.empty())
431 return _error->Error("%s", errmsg.c_str());
432 }
433
434 // Just pass the raw output up, because passing it as a real data
435 // structure is too difficult with the method stuff. We keep it
436 // as three separate vectors for future extensibility.
437 Res.GPGVOutput = GoodSigners;
438 std::move(BadSigners.begin(), BadSigners.end(), std::back_inserter(Res.GPGVOutput));
439 std::move(NoPubKeySigners.begin(), NoPubKeySigners.end(), std::back_inserter(Res.GPGVOutput));
440 URIDone(Res);
441
442 if (DebugEnabled())
443 std::clog << "apt-key succeeded\n";
444
445 return true;
446 }
447
448
449 int main()
450 {
451 return GPGVMethod().Run();
452 }