gpgv.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // -*- mode: cpp; mode: fold -*-
  2. // Include Files /*{{{*/
  3. #include<config.h>
  4. #include<apt-pkg/configuration.h>
  5. #include<apt-pkg/error.h>
  6. #include<apt-pkg/strutl.h>
  7. #include<apt-pkg/fileutl.h>
  8. #include<apt-pkg/gpgv.h>
  9. #include <errno.h>
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include <fcntl.h>
  14. #include <sys/wait.h>
  15. #include <unistd.h>
  16. #include <stddef.h>
  17. #include <algorithm>
  18. #include <fstream>
  19. #include <iostream>
  20. #include <sstream>
  21. #include <string>
  22. #include <vector>
  23. #include <apti18n.h>
  24. /*}}}*/
  25. static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
  26. {
  27. std::string out;
  28. std::string tmpdir = GetTempDir();
  29. strprintf(out, "%s/%s.XXXXXX", tmpdir.c_str(), basename);
  30. return strdup(out.c_str());
  31. }
  32. /*}}}*/
  33. // ExecGPGV - returns the command needed for verify /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* Generating the commandline for calling gpg is somehow complicated as
  36. we need to add multiple keyrings and user supplied options.
  37. Also, as gpg has no options to enforce a certain reduced style of
  38. clear-signed files (=the complete content of the file is signed and
  39. the content isn't encoded) we do a divide and conquer approach here
  40. and split up the clear-signed file in message and signature for gpg.
  41. And as a cherry on the cake, we use our apt-key wrapper to do part
  42. of the lifting in regards to merging keyrings. Fun for the whole family.
  43. */
  44. static bool iovprintf(std::ostream &out, const char *format,
  45. va_list &args, ssize_t &size) {
  46. char *S = (char*)malloc(size);
  47. ssize_t const n = vsnprintf(S, size, format, args);
  48. if (n > -1 && n < size) {
  49. out << S;
  50. free(S);
  51. return true;
  52. } else {
  53. if (n > -1)
  54. size = n + 1;
  55. else
  56. size *= 2;
  57. }
  58. free(S);
  59. return false;
  60. }
  61. static void APT_PRINTF(4) apt_error(std::ostream &outterm, int const statusfd, int fd[2], const char *format, ...)
  62. {
  63. std::ostringstream outstr;
  64. std::ostream &out = (statusfd == -1) ? outterm : outstr;
  65. va_list args;
  66. ssize_t size = 400;
  67. while (true) {
  68. bool ret;
  69. va_start(args,format);
  70. ret = iovprintf(out, format, args, size);
  71. va_end(args);
  72. if (ret == true)
  73. break;
  74. }
  75. if (statusfd != -1)
  76. {
  77. auto const errtag = "[APTKEY:] ERROR ";
  78. outstr << '\n';
  79. auto const errtext = outstr.str();
  80. if (FileFd::Write(fd[1], errtag, strlen(errtag)) == false ||
  81. FileFd::Write(fd[1], errtext.data(), errtext.size()) == false)
  82. outterm << errtext << std::flush;
  83. }
  84. }
  85. void ExecGPGV(std::string const &File, std::string const &FileGPG,
  86. int const &statusfd, int fd[2], std::string const &key)
  87. {
  88. #define EINTERNAL 111
  89. std::string const aptkey = _config->Find("Dir::Bin::apt-key", CMAKE_INSTALL_FULL_BINDIR "/apt-key");
  90. bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
  91. struct exiter {
  92. std::vector<const char *> files;
  93. void operator ()(int code) APT_NORETURN {
  94. std::for_each(files.begin(), files.end(), unlink);
  95. exit(code);
  96. }
  97. } local_exit;
  98. std::vector<const char *> Args;
  99. Args.reserve(10);
  100. Args.push_back(aptkey.c_str());
  101. Args.push_back("--quiet");
  102. Args.push_back("--readonly");
  103. if (key.empty() == false)
  104. {
  105. if (key[0] == '/')
  106. {
  107. Args.push_back("--keyring");
  108. Args.push_back(key.c_str());
  109. }
  110. else
  111. {
  112. Args.push_back("--keyid");
  113. Args.push_back(key.c_str());
  114. }
  115. }
  116. Args.push_back("verify");
  117. char statusfdstr[10];
  118. if (statusfd != -1)
  119. {
  120. Args.push_back("--status-fd");
  121. snprintf(statusfdstr, sizeof(statusfdstr), "%i", statusfd);
  122. Args.push_back(statusfdstr);
  123. }
  124. Configuration::Item const *Opts;
  125. Opts = _config->Tree("Acquire::gpgv::Options");
  126. if (Opts != 0)
  127. {
  128. Opts = Opts->Child;
  129. for (; Opts != 0; Opts = Opts->Next)
  130. {
  131. if (Opts->Value.empty() == true)
  132. continue;
  133. Args.push_back(Opts->Value.c_str());
  134. }
  135. }
  136. enum { DETACHED, CLEARSIGNED } releaseSignature = (FileGPG != File) ? DETACHED : CLEARSIGNED;
  137. std::vector<std::string> dataHeader;
  138. char * sig = NULL;
  139. char * data = NULL;
  140. char * conf = nullptr;
  141. // Dump the configuration so apt-key picks up the correct Dir values
  142. {
  143. conf = GenerateTemporaryFileTemplate("apt.conf");
  144. if (conf == nullptr) {
  145. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for passing config to apt-key");
  146. local_exit(EINTERNAL);
  147. }
  148. int confFd = mkstemp(conf);
  149. if (confFd == -1) {
  150. apt_error(std::cerr, statusfd, fd, "Couldn't create temporary file %s for passing config to apt-key", conf);
  151. local_exit(EINTERNAL);
  152. }
  153. local_exit.files.push_back(conf);
  154. std::ofstream confStream(conf);
  155. close(confFd);
  156. _config->Dump(confStream);
  157. confStream.close();
  158. setenv("APT_CONFIG", conf, 1);
  159. }
  160. if (releaseSignature == DETACHED)
  161. {
  162. Args.push_back(FileGPG.c_str());
  163. Args.push_back(File.c_str());
  164. }
  165. else // clear-signed file
  166. {
  167. sig = GenerateTemporaryFileTemplate("apt.sig");
  168. data = GenerateTemporaryFileTemplate("apt.data");
  169. if (sig == NULL || data == NULL)
  170. {
  171. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for splitting up %s", File.c_str());
  172. local_exit(EINTERNAL);
  173. }
  174. int const sigFd = mkstemp(sig);
  175. int const dataFd = mkstemp(data);
  176. if (dataFd != -1)
  177. local_exit.files.push_back(data);
  178. if (sigFd != -1)
  179. local_exit.files.push_back(sig);
  180. if (sigFd == -1 || dataFd == -1)
  181. {
  182. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfiles for splitting up %s", File.c_str());
  183. local_exit(EINTERNAL);
  184. }
  185. FileFd signature;
  186. signature.OpenDescriptor(sigFd, FileFd::WriteOnly, true);
  187. FileFd message;
  188. message.OpenDescriptor(dataFd, FileFd::WriteOnly, true);
  189. if (signature.Failed() == true || message.Failed() == true ||
  190. SplitClearSignedFile(File, &message, &dataHeader, &signature) == false)
  191. {
  192. apt_error(std::cerr, statusfd, fd, "Splitting up %s into data and signature failed", File.c_str());
  193. local_exit(112);
  194. }
  195. Args.push_back(sig);
  196. Args.push_back(data);
  197. }
  198. Args.push_back(NULL);
  199. if (Debug == true)
  200. {
  201. std::clog << "Preparing to exec: ";
  202. for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
  203. std::clog << " " << *a;
  204. std::clog << std::endl;
  205. }
  206. if (statusfd != -1)
  207. {
  208. int const nullfd = open("/dev/null", O_WRONLY);
  209. close(fd[0]);
  210. // Redirect output to /dev/null; we read from the status fd
  211. if (statusfd != STDOUT_FILENO)
  212. dup2(nullfd, STDOUT_FILENO);
  213. if (statusfd != STDERR_FILENO)
  214. dup2(nullfd, STDERR_FILENO);
  215. // Redirect the pipe to the status fd (3)
  216. dup2(fd[1], statusfd);
  217. putenv((char *)"LANG=");
  218. putenv((char *)"LC_ALL=");
  219. putenv((char *)"LC_MESSAGES=");
  220. }
  221. // We have created tempfiles we have to clean up
  222. // and we do an additional check, so fork yet another time …
  223. pid_t pid = ExecFork();
  224. if(pid < 0) {
  225. apt_error(std::cerr, statusfd, fd, "Fork failed for %s to check %s", Args[0], File.c_str());
  226. local_exit(EINTERNAL);
  227. }
  228. if(pid == 0)
  229. {
  230. if (statusfd != -1)
  231. dup2(fd[1], statusfd);
  232. execvp(Args[0], (char **) &Args[0]);
  233. apt_error(std::cerr, statusfd, fd, "Couldn't execute %s to check %s", Args[0], File.c_str());
  234. local_exit(EINTERNAL);
  235. }
  236. // Wait and collect the error code - taken from WaitPid as we need the exact Status
  237. int Status;
  238. while (waitpid(pid,&Status,0) != pid)
  239. {
  240. if (errno == EINTR)
  241. continue;
  242. apt_error(std::cerr, statusfd, fd, _("Waited for %s but it wasn't there"), "apt-key");
  243. local_exit(EINTERNAL);
  244. }
  245. // check if it exit'ed normally …
  246. if (WIFEXITED(Status) == false)
  247. {
  248. apt_error(std::cerr, statusfd, fd, _("Sub-process %s exited unexpectedly"), "apt-key");
  249. local_exit(EINTERNAL);
  250. }
  251. // … and with a good exit code
  252. if (WEXITSTATUS(Status) != 0)
  253. {
  254. // we forward the statuscode, so don't generate a message on the fd in this case
  255. apt_error(std::cerr, -1, fd, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status));
  256. local_exit(WEXITSTATUS(Status));
  257. }
  258. // everything fine
  259. local_exit(0);
  260. }
  261. /*}}}*/
  262. // SplitClearSignedFile - split message into data/signature /*{{{*/
  263. bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile,
  264. std::vector<std::string> * const ContentHeader, FileFd * const SignatureFile)
  265. {
  266. FILE *in = fopen(InFile.c_str(), "r");
  267. if (in == NULL)
  268. return _error->Errno("fopen", "can not open %s", InFile.c_str());
  269. bool found_message_start = false;
  270. bool found_message_end = false;
  271. bool skip_until_empty_line = false;
  272. bool found_signature = false;
  273. bool first_line = true;
  274. char *buf = NULL;
  275. size_t buf_size = 0;
  276. while (getline(&buf, &buf_size, in) != -1)
  277. {
  278. _strrstrip(buf);
  279. if (found_message_start == false)
  280. {
  281. if (strcmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
  282. {
  283. found_message_start = true;
  284. skip_until_empty_line = true;
  285. }
  286. }
  287. else if (skip_until_empty_line == true)
  288. {
  289. if (strlen(buf) == 0)
  290. skip_until_empty_line = false;
  291. // save "Hash" Armor Headers, others aren't allowed
  292. else if (ContentHeader != NULL && strncmp(buf, "Hash: ", strlen("Hash: ")) == 0)
  293. ContentHeader->push_back(buf);
  294. }
  295. else if (found_signature == false)
  296. {
  297. if (strcmp(buf, "-----BEGIN PGP SIGNATURE-----") == 0)
  298. {
  299. found_signature = true;
  300. found_message_end = true;
  301. if (SignatureFile != NULL)
  302. {
  303. SignatureFile->Write(buf, strlen(buf));
  304. SignatureFile->Write("\n", 1);
  305. }
  306. }
  307. else if (found_message_end == false) // we are in the message block
  308. {
  309. // we don't have any fields which need dash-escaped,
  310. // but implementations are free to encode all lines …
  311. char const * dashfree = buf;
  312. if (strncmp(dashfree, "- ", 2) == 0)
  313. dashfree += 2;
  314. if(first_line == true) // first line does not need a newline
  315. first_line = false;
  316. else if (ContentFile != NULL)
  317. ContentFile->Write("\n", 1);
  318. else
  319. continue;
  320. if (ContentFile != NULL)
  321. ContentFile->Write(dashfree, strlen(dashfree));
  322. }
  323. }
  324. else if (found_signature == true)
  325. {
  326. if (SignatureFile != NULL)
  327. {
  328. SignatureFile->Write(buf, strlen(buf));
  329. SignatureFile->Write("\n", 1);
  330. }
  331. if (strcmp(buf, "-----END PGP SIGNATURE-----") == 0)
  332. found_signature = false; // look for other signatures
  333. }
  334. // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
  335. }
  336. fclose(in);
  337. if (buf != NULL)
  338. free(buf);
  339. if (found_signature == true)
  340. return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
  341. // if we haven't found any of them, this an unsigned file,
  342. // so don't generate an error, but splitting was unsuccessful none-the-less
  343. if (first_line == true && found_message_start == false && found_message_end == false)
  344. return false;
  345. // otherwise one missing indicates a syntax error
  346. else if (first_line == true || found_message_start == false || found_message_end == false)
  347. return _error->Error("Splitting of file %s failed as it doesn't contain all expected parts %i %i %i", InFile.c_str(), first_line, found_message_start, found_message_end);
  348. return true;
  349. }
  350. /*}}}*/
  351. bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
  352. {
  353. char * const message = GenerateTemporaryFileTemplate("fileutl.message");
  354. int const messageFd = mkstemp(message);
  355. if (messageFd == -1)
  356. {
  357. free(message);
  358. return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
  359. }
  360. // we have the fd, thats enough for us
  361. unlink(message);
  362. free(message);
  363. MessageFile.OpenDescriptor(messageFd, FileFd::ReadWrite | FileFd::BufferedWrite, true);
  364. if (MessageFile.Failed() == true)
  365. return _error->Error("Couldn't open temporary file to work with %s", ClearSignedFileName.c_str());
  366. _error->PushToStack();
  367. bool const splitDone = SplitClearSignedFile(ClearSignedFileName, &MessageFile, NULL, NULL);
  368. bool const errorDone = _error->PendingError();
  369. _error->MergeWithStack();
  370. if (splitDone == false)
  371. {
  372. MessageFile.Close();
  373. if (errorDone == true)
  374. return false;
  375. // we deal with an unsigned file
  376. MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
  377. }
  378. else // clear-signed
  379. {
  380. if (MessageFile.Seek(0) == false)
  381. return _error->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName.c_str());
  382. }
  383. return MessageFile.Failed() == false;
  384. }
  385. /*}}}*/