gpgv.cc 16 KB

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