gpgv.cc 16 KB

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