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. Configureable
  42. } state;
  43. char name[32];
  44. State getState() const {
  45. if (state != Digest::State::Configureable)
  46. return state;
  47. std::string const digestconfig = _config->Find("Debug::Acquire::gpgv::configdigest::truststate", "trusted");
  48. if (digestconfig == "weak")
  49. return State::Weak;
  50. else if (digestconfig == "untrusted")
  51. return State::Untrusted;
  52. return State::Trusted;
  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::Configureable, "SHA224"},
  68. };
  69. static_assert(Digests[_count(Digests) - 1].state == Digest::State::Configureable, "the last digest algo isn't the configurable one which we expect for tests");
  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, GNUPGKEYEXPIRED, sizeof(GNUPGKEYEXPIRED)-1) == 0)
  166. {
  167. if (Debug == true)
  168. std::clog << "Got KEYEXPIRED! " << std::endl;
  169. WorthlessSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  170. }
  171. else if (strncmp(buffer, GNUPGREVKEYSIG, sizeof(GNUPGREVKEYSIG)-1) == 0)
  172. {
  173. if (Debug == true)
  174. std::clog << "Got REVKEYSIG! " << std::endl;
  175. WorthlessSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  176. }
  177. else if (strncmp(buffer, GNUPGGOODSIG, sizeof(GNUPGGOODSIG)-1) == 0)
  178. {
  179. char *sig = buffer + sizeof(GNUPGPREFIX);
  180. char *p = sig + sizeof("GOODSIG");
  181. while (*p && isxdigit(*p))
  182. p++;
  183. *p = 0;
  184. if (Debug == true)
  185. std::clog << "Got GOODSIG, key ID:" << sig << std::endl;
  186. GoodSigners.push_back(string(sig));
  187. }
  188. else if (strncmp(buffer, GNUPGVALIDSIG, sizeof(GNUPGVALIDSIG)-1) == 0)
  189. {
  190. char *sig = buffer + sizeof(GNUPGVALIDSIG);
  191. std::istringstream iss((string(sig)));
  192. vector<string> tokens{std::istream_iterator<string>{iss},
  193. std::istream_iterator<string>{}};
  194. char *p = sig;
  195. while (*p && isxdigit(*p))
  196. p++;
  197. *p = 0;
  198. // Reject weak digest algorithms
  199. Digest digest = FindDigest(tokens[7]);
  200. switch (digest.getState()) {
  201. case Digest::State::Weak:
  202. // Treat them like an expired key: For that a message about expiry
  203. // is emitted, a VALIDSIG, but no GOODSIG.
  204. SoonWorthlessSigners.push_back({string(sig), digest.name});
  205. if (Debug == true)
  206. std::clog << "Got weak VALIDSIG, key ID: " << sig << std::endl;
  207. break;
  208. case Digest::State::Untrusted:
  209. // Treat them like an expired key: For that a message about expiry
  210. // is emitted, a VALIDSIG, but no GOODSIG.
  211. WorthlessSigners.push_back(string(sig));
  212. GoodSigners.erase(std::remove_if(GoodSigners.begin(), GoodSigners.end(), [&](std::string const &goodsig) {
  213. return IsTheSameKey(string(sig), goodsig); }), GoodSigners.end());
  214. if (Debug == true)
  215. std::clog << "Got untrusted VALIDSIG, key ID: " << sig << std::endl;
  216. break;
  217. case Digest::State::Configureable:
  218. case Digest::State::Trusted:
  219. if (Debug == true)
  220. std::clog << "Got trusted VALIDSIG, key ID: " << sig << std::endl;
  221. break;
  222. }
  223. ValidSigners.push_back(string(sig));
  224. }
  225. }
  226. fclose(pipein);
  227. free(buffer);
  228. std::move(ErrSigners.begin(), ErrSigners.end(), std::back_inserter(WorthlessSigners));
  229. // apt-key has a --keyid parameter, but this requires gpg, so we call it without it
  230. // and instead check after the fact which keyids where used for verification
  231. if (keyIsID == true)
  232. {
  233. if (Debug == true)
  234. std::clog << "GoodSigs needs to be limited to keyid " << key << std::endl;
  235. std::vector<std::string>::iterator const foundItr = std::find(ValidSigners.begin(), ValidSigners.end(), key);
  236. bool const found = (foundItr != ValidSigners.end());
  237. std::copy(GoodSigners.begin(), GoodSigners.end(), std::back_insert_iterator<std::vector<std::string> >(NoPubKeySigners));
  238. if (found)
  239. {
  240. // we look for GOODSIG here as well as an expired sig is a valid sig as well (but not a good one)
  241. std::string const goodlongkeyid = "GOODSIG " + key.substr(24, 16);
  242. bool const foundGood = std::find(GoodSigners.begin(), GoodSigners.end(), goodlongkeyid) != GoodSigners.end();
  243. if (Debug == true)
  244. std::clog << "Key " << key << " is valid sig, is " << goodlongkeyid << " also a good one? " << (foundGood ? "yes" : "no") << std::endl;
  245. GoodSigners.clear();
  246. if (foundGood)
  247. {
  248. GoodSigners.push_back(goodlongkeyid);
  249. NoPubKeySigners.erase(std::remove(NoPubKeySigners.begin(), NoPubKeySigners.end(), goodlongkeyid), NoPubKeySigners.end());
  250. }
  251. }
  252. else
  253. GoodSigners.clear();
  254. }
  255. int status;
  256. waitpid(pid, &status, 0);
  257. if (Debug == true)
  258. {
  259. ioprintf(std::clog, "gpgv exited with status %i\n", WEXITSTATUS(status));
  260. }
  261. if (Debug)
  262. {
  263. std::cerr << "Summary:" << std::endl << " Good: ";
  264. std::copy(GoodSigners.begin(), GoodSigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
  265. std::cerr << std::endl << " Bad: ";
  266. std::copy(BadSigners.begin(), BadSigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
  267. std::cerr << std::endl << " Worthless: ";
  268. std::copy(WorthlessSigners.begin(), WorthlessSigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
  269. std::cerr << std::endl << " SoonWorthless: ";
  270. std::for_each(SoonWorthlessSigners.begin(), SoonWorthlessSigners.end(), [](Signer const &sig) { std::cerr << sig.key << ", "; });
  271. std::cerr << std::endl << " NoPubKey: ";
  272. std::copy(NoPubKeySigners.begin(), NoPubKeySigners.end(), std::ostream_iterator<std::string>(std::cerr, ", "));
  273. std::cerr << std::endl;
  274. }
  275. if (WEXITSTATUS(status) == 0)
  276. {
  277. if (keyIsID)
  278. {
  279. // gpgv will report success, but we want to enforce a certain keyring
  280. // so if we haven't found the key the valid we found is in fact invalid
  281. if (GoodSigners.empty())
  282. return _("At least one invalid signature was encountered.");
  283. }
  284. else
  285. {
  286. if (GoodSigners.empty())
  287. return _("Internal error: Good signature, but could not determine key fingerprint?!");
  288. }
  289. return "";
  290. }
  291. else if (WEXITSTATUS(status) == 1)
  292. return _("At least one invalid signature was encountered.");
  293. else if (WEXITSTATUS(status) == 111)
  294. return _("Could not execute 'apt-key' to verify signature (is gnupg installed?)");
  295. else if (WEXITSTATUS(status) == 112)
  296. {
  297. // acquire system checks for "NODATA" to generate GPG errors (the others are only warnings)
  298. std::string errmsg;
  299. //TRANSLATORS: %s is a single techy word like 'NODATA'
  300. strprintf(errmsg, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NODATA");
  301. return errmsg;
  302. }
  303. else
  304. return _("Unknown error executing apt-key");
  305. }
  306. bool GPGVMethod::URIAcquire(std::string const &Message, FetchItem *Itm)
  307. {
  308. URI const Get = Itm->Uri;
  309. string const Path = Get.Host + Get.Path; // To account for relative paths
  310. std::string const key = LookupTag(Message, "Signed-By");
  311. vector<string> GoodSigners;
  312. vector<string> BadSigners;
  313. // a worthless signature is a expired or revoked one
  314. vector<string> WorthlessSigners;
  315. vector<Signer> SoonWorthlessSigners;
  316. vector<string> NoPubKeySigners;
  317. FetchResult Res;
  318. Res.Filename = Itm->DestFile;
  319. URIStart(Res);
  320. // Run apt-key on file, extract contents and get the key ID of the signer
  321. string msg = VerifyGetSigners(Path.c_str(), Itm->DestFile.c_str(), key,
  322. GoodSigners, BadSigners, WorthlessSigners,
  323. SoonWorthlessSigners, NoPubKeySigners);
  324. // Check if all good signers are soon worthless and warn in that case
  325. if (std::all_of(GoodSigners.begin(), GoodSigners.end(), [&](std::string const &good) {
  326. return std::any_of(SoonWorthlessSigners.begin(), SoonWorthlessSigners.end(), [&](Signer const &weak) {
  327. return IsTheSameKey(weak.key, good);
  328. });
  329. }))
  330. {
  331. for (auto const & Signer : SoonWorthlessSigners)
  332. // TRANSLATORS: The second %s is the reason and is untranslated for repository owners.
  333. Warning(_("Signature by key %s uses weak digest algorithm (%s)"), Signer.key.c_str(), Signer.note.c_str());
  334. }
  335. if (GoodSigners.empty() || !BadSigners.empty() || !NoPubKeySigners.empty())
  336. {
  337. string errmsg;
  338. // In this case, something bad probably happened, so we just go
  339. // with what the other method gave us for an error message.
  340. if (BadSigners.empty() && WorthlessSigners.empty() && NoPubKeySigners.empty())
  341. errmsg = msg;
  342. else
  343. {
  344. if (!BadSigners.empty())
  345. {
  346. errmsg += _("The following signatures were invalid:\n");
  347. for (vector<string>::iterator I = BadSigners.begin();
  348. I != BadSigners.end(); ++I)
  349. errmsg += (*I + "\n");
  350. }
  351. if (!WorthlessSigners.empty())
  352. {
  353. errmsg += _("The following signatures were invalid:\n");
  354. for (vector<string>::iterator I = WorthlessSigners.begin();
  355. I != WorthlessSigners.end(); ++I)
  356. errmsg += (*I + "\n");
  357. }
  358. if (!NoPubKeySigners.empty())
  359. {
  360. errmsg += _("The following signatures couldn't be verified because the public key is not available:\n");
  361. for (vector<string>::iterator I = NoPubKeySigners.begin();
  362. I != NoPubKeySigners.end(); ++I)
  363. errmsg += (*I + "\n");
  364. }
  365. }
  366. // this is only fatal if we have no good sigs or if we have at
  367. // least one bad signature. good signatures and NoPubKey signatures
  368. // happen easily when a file is signed with multiple signatures
  369. if(GoodSigners.empty() or !BadSigners.empty())
  370. return _error->Error("%s", errmsg.c_str());
  371. }
  372. // Just pass the raw output up, because passing it as a real data
  373. // structure is too difficult with the method stuff. We keep it
  374. // as three separate vectors for future extensibility.
  375. Res.GPGVOutput = GoodSigners;
  376. Res.GPGVOutput.insert(Res.GPGVOutput.end(),BadSigners.begin(),BadSigners.end());
  377. Res.GPGVOutput.insert(Res.GPGVOutput.end(),NoPubKeySigners.begin(),NoPubKeySigners.end());
  378. URIDone(Res);
  379. if (_config->FindB("Debug::Acquire::gpgv", false))
  380. {
  381. std::clog << "apt-key succeeded\n";
  382. }
  383. return true;
  384. }
  385. int main()
  386. {
  387. setlocale(LC_ALL, "");
  388. GPGVMethod Mth;
  389. return Mth.Run();
  390. }