gpgv.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. #include <apt-pkg/error.h>
  2. #include <apt-pkg/acquire-method.h>
  3. #include <apt-pkg/strutl.h>
  4. #include <apti18n.h>
  5. #include <sys/stat.h>
  6. #include <unistd.h>
  7. #include <utime.h>
  8. #include <stdio.h>
  9. #include <fcntl.h>
  10. #include <errno.h>
  11. #include <sys/wait.h>
  12. #include <iostream>
  13. #include <sstream>
  14. #define GNUPGPREFIX "[GNUPG:]"
  15. #define GNUPGBADSIG "[GNUPG:] BADSIG"
  16. #define GNUPGNOPUBKEY "[GNUPG:] NO_PUBKEY"
  17. #define GNUPGVALIDSIG "[GNUPG:] VALIDSIG"
  18. #define GNUPGNODATA "[GNUPG:] NODATA"
  19. class GPGVMethod : public pkgAcqMethod
  20. {
  21. private:
  22. string VerifyGetSigners(const char *file, const char *outfile,
  23. vector<string> &GoodSigners, vector<string> &BadSigners,
  24. vector<string> &NoPubKeySigners);
  25. protected:
  26. virtual bool Fetch(FetchItem *Itm);
  27. public:
  28. GPGVMethod() : pkgAcqMethod("1.0",SingleInstance | SendConfig) {};
  29. };
  30. string GPGVMethod::VerifyGetSigners(const char *file, const char *outfile,
  31. vector<string> &GoodSigners,
  32. vector<string> &BadSigners,
  33. vector<string> &NoPubKeySigners)
  34. {
  35. // setup a (empty) stringstream for formating the return value
  36. std::stringstream ret;
  37. ret.str("");
  38. if (_config->FindB("Debug::Acquire::gpgv", false))
  39. {
  40. std::cerr << "inside VerifyGetSigners" << std::endl;
  41. }
  42. pid_t pid;
  43. int fd[2];
  44. FILE *pipein;
  45. int status;
  46. struct stat buff;
  47. string gpgvpath = _config->Find("Dir::Bin::gpg", "/usr/bin/gpgv");
  48. string pubringpath = _config->Find("APT::GPGV::TrustedKeyring", "/etc/apt/trusted.gpg");
  49. if (_config->FindB("Debug::Acquire::gpgv", false))
  50. {
  51. std::cerr << "gpgv path: " << gpgvpath << std::endl;
  52. std::cerr << "Keyring path: " << pubringpath << std::endl;
  53. }
  54. if (stat(pubringpath.c_str(), &buff) != 0)
  55. {
  56. ioprintf(ret, _("Couldn't access keyring: '%s'"), strerror(errno));
  57. return ret.str();
  58. }
  59. if (pipe(fd) < 0)
  60. {
  61. return "Couldn't create pipe";
  62. }
  63. pid = fork();
  64. if (pid < 0)
  65. {
  66. return string("Couldn't spawn new process") + strerror(errno);
  67. }
  68. else if (pid == 0)
  69. {
  70. const char *Args[400];
  71. unsigned int i = 0;
  72. Args[i++] = gpgvpath.c_str();
  73. Args[i++] = "--status-fd";
  74. Args[i++] = "3";
  75. Args[i++] = "--keyring";
  76. Args[i++] = pubringpath.c_str();
  77. Configuration::Item const *Opts;
  78. Opts = _config->Tree("Acquire::gpgv::Options");
  79. if (Opts != 0)
  80. {
  81. Opts = Opts->Child;
  82. for (; Opts != 0; Opts = Opts->Next)
  83. {
  84. if (Opts->Value.empty() == true)
  85. continue;
  86. Args[i++] = Opts->Value.c_str();
  87. if(i >= 395) {
  88. std::cerr << _("E: Argument list from Acquire::gpgv::Options too long. Exiting.") << std::endl;
  89. exit(111);
  90. }
  91. }
  92. }
  93. Args[i++] = file;
  94. Args[i++] = outfile;
  95. Args[i++] = NULL;
  96. if (_config->FindB("Debug::Acquire::gpgv", false))
  97. {
  98. std::cerr << "Preparing to exec: " << gpgvpath;
  99. for(unsigned int j=0;Args[j] != NULL; j++)
  100. std::cerr << " " << Args[j];
  101. std::cerr << std::endl;
  102. }
  103. int nullfd = open("/dev/null", O_RDONLY);
  104. close(fd[0]);
  105. // Redirect output to /dev/null; we read from the status fd
  106. dup2(nullfd, STDOUT_FILENO);
  107. dup2(nullfd, STDERR_FILENO);
  108. // Redirect the pipe to the status fd (3)
  109. dup2(fd[1], 3);
  110. putenv("LANG=");
  111. putenv("LC_ALL=");
  112. putenv("LC_MESSAGES=");
  113. execvp(gpgvpath.c_str(), (char **)Args);
  114. exit(111);
  115. }
  116. close(fd[1]);
  117. pipein = fdopen(fd[0], "r");
  118. // Loop over the output of gpgv, and check the signatures.
  119. size_t buffersize = 64;
  120. char *buffer = (char *) malloc(buffersize);
  121. size_t bufferoff = 0;
  122. while (1)
  123. {
  124. int c;
  125. // Read a line. Sigh.
  126. while ((c = getc(pipein)) != EOF && c != '\n')
  127. {
  128. if (bufferoff == buffersize)
  129. buffer = (char *) realloc(buffer, buffersize *= 2);
  130. *(buffer+bufferoff) = c;
  131. bufferoff++;
  132. }
  133. if (bufferoff == 0 && c == EOF)
  134. break;
  135. *(buffer+bufferoff) = '\0';
  136. bufferoff = 0;
  137. if (_config->FindB("Debug::Acquire::gpgv", false))
  138. std::cerr << "Read: " << buffer << std::endl;
  139. // Push the data into three separate vectors, which
  140. // we later concatenate. They're kept separate so
  141. // if we improve the apt method communication stuff later
  142. // it will be better.
  143. if (strncmp(buffer, GNUPGBADSIG, sizeof(GNUPGBADSIG)-1) == 0)
  144. {
  145. if (_config->FindB("Debug::Acquire::gpgv", false))
  146. std::cerr << "Got BADSIG! " << std::endl;
  147. BadSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  148. }
  149. if (strncmp(buffer, GNUPGNOPUBKEY, sizeof(GNUPGNOPUBKEY)-1) == 0)
  150. {
  151. if (_config->FindB("Debug::Acquire::gpgv", false))
  152. std::cerr << "Got NO_PUBKEY " << std::endl;
  153. NoPubKeySigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  154. }
  155. if (strncmp(buffer, GNUPGNODATA, sizeof(GNUPGBADSIG)-1) == 0)
  156. {
  157. if (_config->FindB("Debug::Acquire::gpgv", false))
  158. std::cerr << "Got NODATA! " << std::endl;
  159. BadSigners.push_back(string(buffer+sizeof(GNUPGPREFIX)));
  160. }
  161. if (strncmp(buffer, GNUPGVALIDSIG, sizeof(GNUPGVALIDSIG)-1) == 0)
  162. {
  163. char *sig = buffer + sizeof(GNUPGPREFIX);
  164. char *p = sig + sizeof("VALIDSIG");
  165. while (*p && isxdigit(*p))
  166. p++;
  167. *p = 0;
  168. if (_config->FindB("Debug::Acquire::gpgv", false))
  169. std::cerr << "Got VALIDSIG, key ID:" << sig << std::endl;
  170. GoodSigners.push_back(string(sig));
  171. }
  172. }
  173. fclose(pipein);
  174. waitpid(pid, &status, 0);
  175. if (_config->FindB("Debug::Acquire::gpgv", false))
  176. {
  177. std::cerr << "gpgv exited\n";
  178. }
  179. if (WEXITSTATUS(status) == 0)
  180. {
  181. if (GoodSigners.empty())
  182. return _("Internal error: Good signature, but could not determine key fingerprint?!");
  183. return "";
  184. }
  185. else if (WEXITSTATUS(status) == 1)
  186. {
  187. return _("At least one invalid signature was encountered.");
  188. }
  189. else if (WEXITSTATUS(status) == 111)
  190. {
  191. ioprintf(ret, _("Could not execute '%s' to verify signature (is gnupg installed?)"), gpgvpath.c_str());
  192. return ret.str();
  193. }
  194. else
  195. {
  196. return _("Unknown error executing gpgv");
  197. }
  198. }
  199. bool GPGVMethod::Fetch(FetchItem *Itm)
  200. {
  201. URI Get = Itm->Uri;
  202. string Path = Get.Host + Get.Path; // To account for relative paths
  203. string keyID;
  204. vector<string> GoodSigners;
  205. vector<string> BadSigners;
  206. vector<string> NoPubKeySigners;
  207. FetchResult Res;
  208. Res.Filename = Itm->DestFile;
  209. URIStart(Res);
  210. // Run gpgv on file, extract contents and get the key ID of the signer
  211. string msg = VerifyGetSigners(Path.c_str(), Itm->DestFile.c_str(),
  212. GoodSigners, BadSigners, NoPubKeySigners);
  213. if (GoodSigners.empty() || !BadSigners.empty() || !NoPubKeySigners.empty())
  214. {
  215. string errmsg;
  216. // In this case, something bad probably happened, so we just go
  217. // with what the other method gave us for an error message.
  218. if (BadSigners.empty() && NoPubKeySigners.empty())
  219. errmsg = msg;
  220. else
  221. {
  222. if (!BadSigners.empty())
  223. {
  224. errmsg += _("The following signatures were invalid:\n");
  225. for (vector<string>::iterator I = BadSigners.begin();
  226. I != BadSigners.end(); I++)
  227. errmsg += (*I + "\n");
  228. }
  229. if (!NoPubKeySigners.empty())
  230. {
  231. errmsg += _("The following signatures couldn't be verified because the public key is not available:\n");
  232. for (vector<string>::iterator I = NoPubKeySigners.begin();
  233. I != NoPubKeySigners.end(); I++)
  234. errmsg += (*I + "\n");
  235. }
  236. }
  237. // this is only fatal if we have no good sigs or if we have at
  238. // least one bad signature. good signatures and NoPubKey signatures
  239. // happen easily when a file is signed with multiple signatures
  240. if(GoodSigners.empty() or !BadSigners.empty())
  241. return _error->Error(errmsg.c_str());
  242. }
  243. // Transfer the modification times
  244. struct stat Buf;
  245. if (stat(Path.c_str(),&Buf) != 0)
  246. return _error->Errno("stat",_("Failed to stat %s"), Path.c_str());
  247. struct utimbuf TimeBuf;
  248. TimeBuf.actime = Buf.st_atime;
  249. TimeBuf.modtime = Buf.st_mtime;
  250. if (utime(Itm->DestFile.c_str(),&TimeBuf) != 0)
  251. return _error->Errno("utime",_("Failed to set modification time"));
  252. if (stat(Itm->DestFile.c_str(),&Buf) != 0)
  253. return _error->Errno("stat",_("Failed to stat"));
  254. // Return a Done response
  255. Res.LastModified = Buf.st_mtime;
  256. Res.Size = Buf.st_size;
  257. // Just pass the raw output up, because passing it as a real data
  258. // structure is too difficult with the method stuff. We keep it
  259. // as three separate vectors for future extensibility.
  260. Res.GPGVOutput = GoodSigners;
  261. Res.GPGVOutput.insert(Res.GPGVOutput.end(),BadSigners.begin(),BadSigners.end());
  262. Res.GPGVOutput.insert(Res.GPGVOutput.end(),NoPubKeySigners.begin(),NoPubKeySigners.end());
  263. URIDone(Res);
  264. if (_config->FindB("Debug::Acquire::gpgv", false))
  265. {
  266. std::cerr << "gpgv succeeded\n";
  267. }
  268. return true;
  269. }
  270. int main()
  271. {
  272. setlocale(LC_ALL, "");
  273. GPGVMethod Mth;
  274. return Mth.Run();
  275. }