gpgv.cc 8.9 KB

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