gpgv.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 GNUPGKEYEXPIRED "[GNUPG:] KEYEXPIRED"
  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. string GPGVMethod::VerifyGetSigners(const char *file, const char *outfile,
  102. std::string const &key,
  103. vector<string> &GoodSigners,
  104. vector<string> &BadSigners,
  105. vector<string> &WorthlessSigners,
  106. vector<Signer> &SoonWorthlessSigners,
  107. vector<string> &NoPubKeySigners)
  108. {
  109. bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
  110. if (Debug == true)
  111. std::clog << "inside VerifyGetSigners" << std::endl;
  112. int fd[2];
  113. bool const keyIsID = (key.empty() == false && key[0] != '/');
  114. if (pipe(fd) < 0)
  115. return "Couldn't create pipe";
  116. pid_t pid = fork();
  117. if (pid < 0)
  118. return string("Couldn't spawn new process") + strerror(errno);
  119. else if (pid == 0)
  120. ExecGPGV(outfile, file, 3, fd, (keyIsID ? "" : key));
  121. close(fd[1]);
  122. FILE *pipein = fdopen(fd[0], "r");
  123. // Loop over the output of apt-key (which really is gnupg), and check the signatures.
  124. std::vector<std::string> ValidSigners;
  125. std::vector<std::string> ErrSigners;
  126. size_t buffersize = 0;
  127. char *buffer = NULL;
  128. while (1)
  129. {
  130. if (getline(&buffer, &buffersize, pipein) == -1)
  131. break;
  132. if (Debug == true)
  133. std::clog << "Read: " << buffer << std::endl;
  134. // Push the data into three separate vectors, which
  135. // we later concatenate. They're kept separate so
  136. // if we improve the apt method communication stuff later
  137. // it will be better.
  138. if (strncmp(buffer, GNUPGBADSIG, sizeof(GNUPGBADSIG)-1) == 0)
  139. {
  140. if (Debug == true)
  141. std::clog << "Got BADSIG! " << std::endl;
  142. BadSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  143. }
  144. else if (strncmp(buffer, GNUPGERRSIG, sizeof(GNUPGERRSIG)-1) == 0)
  145. {
  146. if (Debug == true)
  147. std::clog << "Got ERRSIG " << std::endl;
  148. ErrSigners.push_back(string(buffer, strlen(GNUPGPREFIX), strlen("ERRSIG ") + 16));
  149. }
  150. else if (strncmp(buffer, GNUPGNOPUBKEY, sizeof(GNUPGNOPUBKEY)-1) == 0)
  151. {
  152. if (Debug == true)
  153. std::clog << "Got NO_PUBKEY " << std::endl;
  154. NoPubKeySigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  155. ErrSigners.erase(std::remove_if(ErrSigners.begin(), ErrSigners.end(), [&](std::string const &errsig) {
  156. return errsig.compare(strlen("ERRSIG "), 16, buffer, strlen(GNUPGNOPUBKEY), 16) == 0; }), ErrSigners.end());
  157. }
  158. else if (strncmp(buffer, GNUPGNODATA, sizeof(GNUPGBADSIG)-1) == 0)
  159. {
  160. if (Debug == true)
  161. std::clog << "Got NODATA! " << std::endl;
  162. BadSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  163. }
  164. else if (strncmp(buffer, GNUPGKEYEXPIRED, sizeof(GNUPGKEYEXPIRED)-1) == 0)
  165. {
  166. if (Debug == true)
  167. std::clog << "Got KEYEXPIRED! " << std::endl;
  168. WorthlessSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  169. }
  170. else if (strncmp(buffer, GNUPGREVKEYSIG, sizeof(GNUPGREVKEYSIG)-1) == 0)
  171. {
  172. if (Debug == true)
  173. std::clog << "Got REVKEYSIG! " << std::endl;
  174. WorthlessSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  175. }
  176. else if (strncmp(buffer, GNUPGGOODSIG, sizeof(GNUPGGOODSIG)-1) == 0)
  177. {
  178. char *sig = buffer + sizeof(GNUPGPREFIX);
  179. char *p = sig + sizeof("GOODSIG");
  180. while (*p && isxdigit(*p))
  181. p++;
  182. *p = 0;
  183. if (Debug == true)
  184. std::clog << "Got GOODSIG, key ID:" << sig << std::endl;
  185. GoodSigners.push_back(string(sig));
  186. }
  187. else if (strncmp(buffer, GNUPGVALIDSIG, sizeof(GNUPGVALIDSIG)-1) == 0)
  188. {
  189. char *sig = buffer + sizeof(GNUPGVALIDSIG);
  190. std::istringstream iss((string(sig)));
  191. vector<string> tokens{std::istream_iterator<string>{iss},
  192. std::istream_iterator<string>{}};
  193. char *p = sig;
  194. while (*p && isxdigit(*p))
  195. p++;
  196. *p = 0;
  197. // Reject weak digest algorithms
  198. Digest digest = FindDigest(tokens[7]);
  199. switch (digest.getState()) {
  200. case Digest::State::Weak:
  201. // Treat them like an expired key: For that a message about expiry
  202. // is emitted, a VALIDSIG, but no GOODSIG.
  203. SoonWorthlessSigners.push_back({string(sig), digest.name});
  204. if (Debug == true)
  205. std::clog << "Got weak VALIDSIG, key ID: " << sig << std::endl;
  206. break;
  207. case Digest::State::Untrusted:
  208. // Treat them like an expired key: For that a message about expiry
  209. // is emitted, a VALIDSIG, but no GOODSIG.
  210. WorthlessSigners.push_back(string(sig));
  211. GoodSigners.erase(std::remove_if(GoodSigners.begin(), GoodSigners.end(), [&](std::string const &goodsig) {
  212. return IsTheSameKey(string(sig), goodsig); }), GoodSigners.end());
  213. if (Debug == true)
  214. std::clog << "Got untrusted VALIDSIG, key ID: " << sig << std::endl;
  215. break;
  216. case Digest::State::Trusted:
  217. if (Debug == true)
  218. std::clog << "Got trusted VALIDSIG, key ID: " << sig << std::endl;
  219. break;
  220. }
  221. ValidSigners.push_back(string(sig));
  222. }
  223. }
  224. fclose(pipein);
  225. free(buffer);
  226. std::move(ErrSigners.begin(), ErrSigners.end(), std::back_inserter(WorthlessSigners));
  227. // apt-key has a --keyid parameter, but this requires gpg, so we call it without it
  228. // and instead check after the fact which keyids where used for verification
  229. if (keyIsID == true)
  230. {
  231. if (Debug == true)
  232. std::clog << "GoodSigs needs to be limited to keyid " << key << std::endl;
  233. std::vector<std::string>::iterator const foundItr = std::find(ValidSigners.begin(), ValidSigners.end(), key);
  234. bool const found = (foundItr != ValidSigners.end());
  235. std::copy(GoodSigners.begin(), GoodSigners.end(), std::back_insert_iterator<std::vector<std::string> >(NoPubKeySigners));
  236. if (found)
  237. {
  238. // we look for GOODSIG here as well as an expired sig is a valid sig as well (but not a good one)
  239. std::string const goodlongkeyid = "GOODSIG " + key.substr(24, 16);
  240. bool const foundGood = std::find(GoodSigners.begin(), GoodSigners.end(), goodlongkeyid) != GoodSigners.end();
  241. if (Debug == true)
  242. std::clog << "Key " << key << " is valid sig, is " << goodlongkeyid << " also a good one? " << (foundGood ? "yes" : "no") << std::endl;
  243. GoodSigners.clear();
  244. if (foundGood)
  245. {
  246. GoodSigners.push_back(goodlongkeyid);
  247. NoPubKeySigners.erase(std::remove(NoPubKeySigners.begin(), NoPubKeySigners.end(), goodlongkeyid), NoPubKeySigners.end());
  248. }
  249. }
  250. else
  251. GoodSigners.clear();
  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;
  272. }
  273. if (WEXITSTATUS(status) == 0)
  274. {
  275. if (keyIsID)
  276. {
  277. // gpgv will report success, but we want to enforce a certain keyring
  278. // so if we haven't found the key the valid we found is in fact invalid
  279. if (GoodSigners.empty())
  280. return _("At least one invalid signature was encountered.");
  281. }
  282. else
  283. {
  284. if (GoodSigners.empty())
  285. return _("Internal error: Good signature, but could not determine key fingerprint?!");
  286. }
  287. return "";
  288. }
  289. else if (WEXITSTATUS(status) == 1)
  290. return _("At least one invalid signature was encountered.");
  291. else if (WEXITSTATUS(status) == 111)
  292. return _("Could not execute 'apt-key' to verify signature (is gnupg installed?)");
  293. else if (WEXITSTATUS(status) == 112)
  294. {
  295. // acquire system checks for "NODATA" to generate GPG errors (the others are only warnings)
  296. std::string errmsg;
  297. //TRANSLATORS: %s is a single techy word like 'NODATA'
  298. strprintf(errmsg, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NODATA");
  299. return errmsg;
  300. }
  301. else
  302. return _("Unknown error executing apt-key");
  303. }
  304. bool GPGVMethod::URIAcquire(std::string const &Message, FetchItem *Itm)
  305. {
  306. URI const Get = Itm->Uri;
  307. string const Path = Get.Host + Get.Path; // To account for relative paths
  308. std::string const key = LookupTag(Message, "Signed-By");
  309. vector<string> GoodSigners;
  310. vector<string> BadSigners;
  311. // a worthless signature is a expired or revoked one
  312. vector<string> WorthlessSigners;
  313. vector<Signer> SoonWorthlessSigners;
  314. vector<string> NoPubKeySigners;
  315. FetchResult Res;
  316. Res.Filename = Itm->DestFile;
  317. URIStart(Res);
  318. // Run apt-key on file, extract contents and get the key ID of the signer
  319. string msg = VerifyGetSigners(Path.c_str(), Itm->DestFile.c_str(), key,
  320. GoodSigners, BadSigners, WorthlessSigners,
  321. SoonWorthlessSigners, NoPubKeySigners);
  322. // Check if all good signers are soon worthless and warn in that case
  323. if (std::all_of(GoodSigners.begin(), GoodSigners.end(), [&](std::string const &good) {
  324. return std::any_of(SoonWorthlessSigners.begin(), SoonWorthlessSigners.end(), [&](Signer const &weak) {
  325. return IsTheSameKey(weak.key, good);
  326. });
  327. }))
  328. {
  329. for (auto const & Signer : SoonWorthlessSigners)
  330. // TRANSLATORS: The second %s is the reason and is untranslated for repository owners.
  331. Warning(_("Signature by key %s uses weak digest algorithm (%s)"), Signer.key.c_str(), Signer.note.c_str());
  332. }
  333. if (GoodSigners.empty() || !BadSigners.empty() || !NoPubKeySigners.empty())
  334. {
  335. string errmsg;
  336. // In this case, something bad probably happened, so we just go
  337. // with what the other method gave us for an error message.
  338. if (BadSigners.empty() && WorthlessSigners.empty() && NoPubKeySigners.empty())
  339. errmsg = msg;
  340. else
  341. {
  342. if (!BadSigners.empty())
  343. {
  344. errmsg += _("The following signatures were invalid:\n");
  345. for (vector<string>::iterator I = BadSigners.begin();
  346. I != BadSigners.end(); ++I)
  347. errmsg += (*I + "\n");
  348. }
  349. if (!WorthlessSigners.empty())
  350. {
  351. errmsg += _("The following signatures were invalid:\n");
  352. for (vector<string>::iterator I = WorthlessSigners.begin();
  353. I != WorthlessSigners.end(); ++I)
  354. errmsg += (*I + "\n");
  355. }
  356. if (!NoPubKeySigners.empty())
  357. {
  358. errmsg += _("The following signatures couldn't be verified because the public key is not available:\n");
  359. for (vector<string>::iterator I = NoPubKeySigners.begin();
  360. I != NoPubKeySigners.end(); ++I)
  361. errmsg += (*I + "\n");
  362. }
  363. }
  364. // this is only fatal if we have no good sigs or if we have at
  365. // least one bad signature. good signatures and NoPubKey signatures
  366. // happen easily when a file is signed with multiple signatures
  367. if(GoodSigners.empty() or !BadSigners.empty())
  368. return _error->Error("%s", errmsg.c_str());
  369. }
  370. // Just pass the raw output up, because passing it as a real data
  371. // structure is too difficult with the method stuff. We keep it
  372. // as three separate vectors for future extensibility.
  373. Res.GPGVOutput = GoodSigners;
  374. Res.GPGVOutput.insert(Res.GPGVOutput.end(),BadSigners.begin(),BadSigners.end());
  375. Res.GPGVOutput.insert(Res.GPGVOutput.end(),NoPubKeySigners.begin(),NoPubKeySigners.end());
  376. URIDone(Res);
  377. if (_config->FindB("Debug::Acquire::gpgv", false))
  378. {
  379. std::clog << "apt-key succeeded\n";
  380. }
  381. return true;
  382. }
  383. int main()
  384. {
  385. setlocale(LC_ALL, "");
  386. GPGVMethod Mth;
  387. return Mth.Run();
  388. }