gpgv.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // -*- mode: cpp; mode: fold -*-
  2. // Include Files /*{{{*/
  3. #include<config.h>
  4. #include <errno.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <stdlib.h>
  8. #include <fcntl.h>
  9. #include <sys/stat.h>
  10. #include <sys/types.h>
  11. #include <sys/wait.h>
  12. #include<apt-pkg/configuration.h>
  13. #include<apt-pkg/error.h>
  14. #include<apt-pkg/strutl.h>
  15. #include<apt-pkg/fileutl.h>
  16. #include<apt-pkg/gpgv.h>
  17. #include <apti18n.h>
  18. /*}}}*/
  19. static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
  20. {
  21. const char *tmpdir = getenv("TMPDIR");
  22. #ifdef P_tmpdir
  23. if (!tmpdir)
  24. tmpdir = P_tmpdir;
  25. #endif
  26. if (!tmpdir)
  27. tmpdir = "/tmp";
  28. std::string out;
  29. strprintf(out, "%s/%s.XXXXXX", tmpdir, basename);
  30. return strdup(out.c_str());
  31. }
  32. /*}}}*/
  33. // ExecGPGV - returns the command needed for verify /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* Generating the commandline for calling gpgv is somehow complicated as
  36. we need to add multiple keyrings and user supplied options.
  37. Also, as gpgv 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. */
  41. void ExecGPGV(std::string const &File, std::string const &FileGPG,
  42. int const &statusfd, int fd[2])
  43. {
  44. #define EINTERNAL 111
  45. std::string const gpgvpath = _config->Find("Dir::Bin::gpg", "/usr/bin/gpgv");
  46. // FIXME: remove support for deprecated APT::GPGV setting
  47. std::string const trustedFile = _config->Find("APT::GPGV::TrustedKeyring", _config->FindFile("Dir::Etc::Trusted"));
  48. std::string const trustedPath = _config->FindDir("Dir::Etc::TrustedParts");
  49. bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
  50. if (Debug == true)
  51. {
  52. std::clog << "gpgv path: " << gpgvpath << std::endl;
  53. std::clog << "Keyring file: " << trustedFile << std::endl;
  54. std::clog << "Keyring path: " << trustedPath << std::endl;
  55. }
  56. std::vector<std::string> keyrings;
  57. if (DirectoryExists(trustedPath))
  58. keyrings = GetListOfFilesInDir(trustedPath, "gpg", false, true);
  59. if (RealFileExists(trustedFile) == true)
  60. keyrings.push_back(trustedFile);
  61. std::vector<const char *> Args;
  62. Args.reserve(30);
  63. if (keyrings.empty() == true)
  64. {
  65. // TRANSLATOR: %s is the trusted keyring parts directory
  66. ioprintf(std::cerr, _("No keyring installed in %s."),
  67. _config->FindDir("Dir::Etc::TrustedParts").c_str());
  68. exit(EINTERNAL);
  69. }
  70. Args.push_back(gpgvpath.c_str());
  71. Args.push_back("--ignore-time-conflict");
  72. char statusfdstr[10];
  73. if (statusfd != -1)
  74. {
  75. Args.push_back("--status-fd");
  76. snprintf(statusfdstr, sizeof(statusfdstr), "%i", statusfd);
  77. Args.push_back(statusfdstr);
  78. }
  79. for (std::vector<std::string>::const_iterator K = keyrings.begin();
  80. K != keyrings.end(); ++K)
  81. {
  82. Args.push_back("--keyring");
  83. Args.push_back(K->c_str());
  84. }
  85. Configuration::Item const *Opts;
  86. Opts = _config->Tree("Acquire::gpgv::Options");
  87. if (Opts != 0)
  88. {
  89. Opts = Opts->Child;
  90. for (; Opts != 0; Opts = Opts->Next)
  91. {
  92. if (Opts->Value.empty() == true)
  93. continue;
  94. Args.push_back(Opts->Value.c_str());
  95. }
  96. }
  97. int sigFd = -1;
  98. int dataFd = -1;
  99. std::vector<std::string> dataHeader;
  100. char * sig = NULL;
  101. char * data = NULL;
  102. // file with detached signature
  103. if (FileGPG != File)
  104. {
  105. Args.push_back(FileGPG.c_str());
  106. Args.push_back(File.c_str());
  107. }
  108. else // clear-signed file
  109. {
  110. sig = GenerateTemporaryFileTemplate("apt.sig");
  111. data = GenerateTemporaryFileTemplate("apt.data");
  112. if (sig == NULL || data == NULL)
  113. {
  114. ioprintf(std::cerr, "Couldn't create tempfiles for splitting up %s", File.c_str());
  115. exit(EINTERNAL);
  116. }
  117. sigFd = mkstemp(sig);
  118. dataFd = mkstemp(data);
  119. int const duppedSigFd = dup(sigFd);
  120. int const duppedDataFd = dup(dataFd);
  121. if (dataFd == -1 || sigFd == -1 || duppedDataFd == -1 || duppedSigFd == -1 ||
  122. SplitClearSignedFile(File, duppedDataFd, &dataHeader, duppedSigFd) == false)
  123. {
  124. if (dataFd != -1)
  125. unlink(sig);
  126. if (sigFd != -1)
  127. unlink(data);
  128. ioprintf(std::cerr, "Splitting up %s into data and signature failed", File.c_str());
  129. exit(EINTERNAL);
  130. }
  131. lseek(dataFd, 0, SEEK_SET);
  132. lseek(sigFd, 0, SEEK_SET);
  133. Args.push_back(sig);
  134. Args.push_back(data);
  135. }
  136. Args.push_back(NULL);
  137. if (Debug == true)
  138. {
  139. std::clog << "Preparing to exec: " << gpgvpath;
  140. for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
  141. std::clog << " " << *a;
  142. std::clog << std::endl;
  143. }
  144. if (statusfd != -1)
  145. {
  146. int const nullfd = open("/dev/null", O_RDONLY);
  147. close(fd[0]);
  148. // Redirect output to /dev/null; we read from the status fd
  149. if (statusfd != STDOUT_FILENO)
  150. dup2(nullfd, STDOUT_FILENO);
  151. if (statusfd != STDERR_FILENO)
  152. dup2(nullfd, STDERR_FILENO);
  153. // Redirect the pipe to the status fd (3)
  154. dup2(fd[1], statusfd);
  155. putenv((char *)"LANG=");
  156. putenv((char *)"LC_ALL=");
  157. putenv((char *)"LC_MESSAGES=");
  158. }
  159. if (FileGPG != File)
  160. {
  161. execvp(gpgvpath.c_str(), (char **) &Args[0]);
  162. ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
  163. exit(EINTERNAL);
  164. }
  165. else
  166. {
  167. //#define UNLINK_EXIT(X) exit(X)
  168. #define UNLINK_EXIT(X) unlink(sig);unlink(data);exit(X)
  169. // for clear-signed files we have created tempfiles we have to clean up
  170. // and we do an additional check, so fork yet another time …
  171. pid_t pid = ExecFork();
  172. if(pid < 0) {
  173. ioprintf(std::cerr, "Fork failed for %s to check %s", Args[0], File.c_str());
  174. UNLINK_EXIT(EINTERNAL);
  175. }
  176. if(pid == 0)
  177. {
  178. if (statusfd != -1)
  179. dup2(fd[1], statusfd);
  180. execvp(gpgvpath.c_str(), (char **) &Args[0]);
  181. ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
  182. UNLINK_EXIT(EINTERNAL);
  183. }
  184. // Wait and collect the error code - taken from WaitPid as we need the exact Status
  185. int Status;
  186. while (waitpid(pid,&Status,0) != pid)
  187. {
  188. if (errno == EINTR)
  189. continue;
  190. ioprintf(std::cerr, _("Waited for %s but it wasn't there"), "gpgv");
  191. UNLINK_EXIT(EINTERNAL);
  192. }
  193. #undef UNLINK_EXIT
  194. // we don't need the files any longer
  195. unlink(sig);
  196. unlink(data);
  197. free(sig);
  198. free(data);
  199. // check if it exit'ed normally …
  200. if (WIFEXITED(Status) == false)
  201. {
  202. ioprintf(std::cerr, _("Sub-process %s exited unexpectedly"), "gpgv");
  203. exit(EINTERNAL);
  204. }
  205. // … and with a good exit code
  206. if (WEXITSTATUS(Status) != 0)
  207. {
  208. ioprintf(std::cerr, _("Sub-process %s returned an error code (%u)"), "gpgv", WEXITSTATUS(Status));
  209. exit(WEXITSTATUS(Status));
  210. }
  211. // everything fine
  212. exit(0);
  213. }
  214. exit(EINTERNAL); // unreachable safe-guard
  215. }
  216. /*}}}*/
  217. // SplitClearSignedFile - split message into data/signature /*{{{*/
  218. bool SplitClearSignedFile(std::string const &InFile, int const ContentFile,
  219. std::vector<std::string> * const ContentHeader, int const SignatureFile)
  220. {
  221. FILE *in = fopen(InFile.c_str(), "r");
  222. if (in == NULL)
  223. return _error->Errno("fopen", "can not open %s", InFile.c_str());
  224. FILE *out_content = NULL;
  225. FILE *out_signature = NULL;
  226. if (ContentFile != -1)
  227. {
  228. out_content = fdopen(ContentFile, "w");
  229. if (out_content == NULL)
  230. {
  231. fclose(in);
  232. return _error->Errno("fdopen", "Failed to open file to write content to from %s", InFile.c_str());
  233. }
  234. }
  235. if (SignatureFile != -1)
  236. {
  237. out_signature = fdopen(SignatureFile, "w");
  238. if (out_signature == NULL)
  239. {
  240. fclose(in);
  241. if (out_content != NULL)
  242. fclose(out_content);
  243. return _error->Errno("fdopen", "Failed to open file to write signature to from %s", InFile.c_str());
  244. }
  245. }
  246. bool found_message_start = false;
  247. bool found_message_end = false;
  248. bool skip_until_empty_line = false;
  249. bool found_signature = false;
  250. bool first_line = true;
  251. char *buf = NULL;
  252. size_t buf_size = 0;
  253. while (getline(&buf, &buf_size, in) != -1)
  254. {
  255. _strrstrip(buf);
  256. if (found_message_start == false)
  257. {
  258. if (strcmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
  259. {
  260. found_message_start = true;
  261. skip_until_empty_line = true;
  262. }
  263. }
  264. else if (skip_until_empty_line == true)
  265. {
  266. if (strlen(buf) == 0)
  267. skip_until_empty_line = false;
  268. // save "Hash" Armor Headers, others aren't allowed
  269. else if (ContentHeader != NULL && strncmp(buf, "Hash: ", strlen("Hash: ")) == 0)
  270. ContentHeader->push_back(buf);
  271. }
  272. else if (found_signature == false)
  273. {
  274. if (strcmp(buf, "-----BEGIN PGP SIGNATURE-----") == 0)
  275. {
  276. found_signature = true;
  277. found_message_end = true;
  278. if (out_signature != NULL)
  279. fprintf(out_signature, "%s\n", buf);
  280. }
  281. else if (found_message_end == false)
  282. {
  283. // we are in the message block
  284. if(first_line == true) // first line does not need a newline
  285. {
  286. if (out_content != NULL)
  287. fprintf(out_content, "%s", buf);
  288. first_line = false;
  289. }
  290. else if (out_content != NULL)
  291. fprintf(out_content, "\n%s", buf);
  292. }
  293. }
  294. else if (found_signature == true)
  295. {
  296. if (out_signature != NULL)
  297. fprintf(out_signature, "%s\n", buf);
  298. if (strcmp(buf, "-----END PGP SIGNATURE-----") == 0)
  299. found_signature = false; // look for other signatures
  300. }
  301. // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
  302. }
  303. if (out_content != NULL)
  304. fclose(out_content);
  305. if (out_signature != NULL)
  306. fclose(out_signature);
  307. fclose(in);
  308. if (found_signature == true)
  309. return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
  310. // if we haven't found any of them, this an unsigned file,
  311. // so don't generate an error, but splitting was unsuccessful none-the-less
  312. if (found_message_start == false && found_message_end == false)
  313. return false;
  314. // otherwise one missing indicates a syntax error
  315. else if (found_message_start == false || found_message_end == false)
  316. return _error->Error("Splitting of file %s failed as it doesn't contain all expected parts", InFile.c_str());
  317. return true;
  318. }
  319. /*}}}*/
  320. bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
  321. {
  322. char * const message = GenerateTemporaryFileTemplate("fileutl.message");
  323. int const messageFd = mkstemp(message);
  324. if (messageFd == -1)
  325. {
  326. free(message);
  327. return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
  328. }
  329. // we have the fd, thats enough for us
  330. unlink(message);
  331. free(message);
  332. int const duppedMsg = dup(messageFd);
  333. if (duppedMsg == -1)
  334. return _error->Errno("dup", "Couldn't duplicate FD to work with %s", ClearSignedFileName.c_str());
  335. _error->PushToStack();
  336. bool const splitDone = SplitClearSignedFile(ClearSignedFileName.c_str(), messageFd, NULL, -1);
  337. bool const errorDone = _error->PendingError();
  338. _error->MergeWithStack();
  339. if (splitDone == false)
  340. {
  341. close(duppedMsg);
  342. if (errorDone == true)
  343. return false;
  344. // we deal with an unsigned file
  345. MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
  346. }
  347. else // clear-signed
  348. {
  349. if (lseek(duppedMsg, 0, SEEK_SET) < 0)
  350. return _error->Errno("lseek", "Unable to seek back in message fd for file %s", ClearSignedFileName.c_str());
  351. MessageFile.OpenDescriptor(duppedMsg, FileFd::ReadOnly, true);
  352. }
  353. return MessageFile.Failed() == false;
  354. }
  355. /*}}}*/