gpgv.cc 13 KB

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