gpgv.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. 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. // check if it exit'ed normally …
  194. if (WIFEXITED(Status) == false)
  195. {
  196. ioprintf(std::cerr, _("Sub-process %s exited unexpectedly"), "gpgv");
  197. UNLINK_EXIT(EINTERNAL);
  198. }
  199. // … and with a good exit code
  200. if (WEXITSTATUS(Status) != 0)
  201. {
  202. ioprintf(std::cerr, _("Sub-process %s returned an error code (%u)"), "gpgv", WEXITSTATUS(Status));
  203. UNLINK_EXIT(WEXITSTATUS(Status));
  204. }
  205. /* looks like its fine. Our caller will check the status fd,
  206. but we construct a good-known clear-signed file without garbage
  207. and other non-sense. In a perfect world, we get the same file,
  208. but empty lines, trailing whitespaces and stuff makes it inperfect … */
  209. if (RecombineToClearSignedFile(File, dataFd, dataHeader, sigFd) == false)
  210. {
  211. _error->DumpErrors(std::cerr);
  212. UNLINK_EXIT(EINTERNAL);
  213. }
  214. // everything fine, we have a clean file now!
  215. UNLINK_EXIT(0);
  216. #undef UNLINK_EXIT
  217. }
  218. exit(EINTERNAL); // unreachable safe-guard
  219. }
  220. /*}}}*/
  221. // RecombineToClearSignedFile - combine data/signature to message /*{{{*/
  222. bool RecombineToClearSignedFile(std::string const &OutFile, int const ContentFile,
  223. std::vector<std::string> const &ContentHeader, int const SignatureFile)
  224. {
  225. FILE *clean_file = fopen(OutFile.c_str(), "w");
  226. fputs("-----BEGIN PGP SIGNED MESSAGE-----\n", clean_file);
  227. for (std::vector<std::string>::const_iterator h = ContentHeader.begin(); h != ContentHeader.end(); ++h)
  228. fprintf(clean_file, "%s\n", h->c_str());
  229. fputs("\n", clean_file);
  230. FILE *data_file = fdopen(ContentFile, "r");
  231. FILE *sig_file = fdopen(SignatureFile, "r");
  232. if (data_file == NULL || sig_file == NULL)
  233. return _error->Error("Couldn't open splitfiles to recombine them into %s", OutFile.c_str());
  234. char *buf = NULL;
  235. size_t buf_size = 0;
  236. while (getline(&buf, &buf_size, data_file) != -1)
  237. fputs(buf, clean_file);
  238. fclose(data_file);
  239. fputs("\n", clean_file);
  240. while (getline(&buf, &buf_size, sig_file) != -1)
  241. fputs(buf, clean_file);
  242. fclose(sig_file);
  243. fclose(clean_file);
  244. return true;
  245. }
  246. /*}}}*/
  247. // SplitClearSignedFile - split message into data/signature /*{{{*/
  248. bool SplitClearSignedFile(std::string const &InFile, int const ContentFile,
  249. std::vector<std::string> * const ContentHeader, int const SignatureFile)
  250. {
  251. FILE *in = fopen(InFile.c_str(), "r");
  252. if (in == NULL)
  253. return _error->Errno("fopen", "can not open %s", InFile.c_str());
  254. FILE *out_content = NULL;
  255. FILE *out_signature = NULL;
  256. if (ContentFile != -1)
  257. {
  258. out_content = fdopen(ContentFile, "w");
  259. if (out_content == NULL)
  260. return _error->Errno("fdopen", "Failed to open file to write content to from %s", InFile.c_str());
  261. }
  262. if (SignatureFile != -1)
  263. {
  264. out_signature = fdopen(SignatureFile, "w");
  265. if (out_signature == NULL)
  266. return _error->Errno("fdopen", "Failed to open file to write signature to from %s", InFile.c_str());
  267. }
  268. bool found_message_start = false;
  269. bool found_message_end = false;
  270. bool skip_until_empty_line = false;
  271. bool found_signature = false;
  272. bool first_line = true;
  273. char *buf = NULL;
  274. size_t buf_size = 0;
  275. while (getline(&buf, &buf_size, in) != -1)
  276. {
  277. _strrstrip(buf);
  278. if (found_message_start == false)
  279. {
  280. if (strcmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
  281. {
  282. found_message_start = true;
  283. skip_until_empty_line = true;
  284. }
  285. }
  286. else if (skip_until_empty_line == true)
  287. {
  288. if (strlen(buf) == 0)
  289. skip_until_empty_line = false;
  290. // save "Hash" Armor Headers, others aren't allowed
  291. else if (ContentHeader != NULL && strncmp(buf, "Hash: ", strlen("Hash: ")) == 0)
  292. ContentHeader->push_back(buf);
  293. }
  294. else if (found_signature == false)
  295. {
  296. if (strcmp(buf, "-----BEGIN PGP SIGNATURE-----") == 0)
  297. {
  298. found_signature = true;
  299. found_message_end = true;
  300. if (out_signature != NULL)
  301. fprintf(out_signature, "%s\n", buf);
  302. }
  303. else if (found_message_end == false)
  304. {
  305. // we are in the message block
  306. if(first_line == true) // first line does not need a newline
  307. {
  308. if (out_content != NULL)
  309. fprintf(out_content, "%s", buf);
  310. first_line = false;
  311. }
  312. else if (out_content != NULL)
  313. fprintf(out_content, "\n%s", buf);
  314. }
  315. }
  316. else if (found_signature == true)
  317. {
  318. if (out_signature != NULL)
  319. fprintf(out_signature, "%s\n", buf);
  320. if (strcmp(buf, "-----END PGP SIGNATURE-----") == 0)
  321. found_signature = false; // look for other signatures
  322. }
  323. // all the rest is whitespace, unsigned garbage or additional message blocks we ignore
  324. }
  325. if (out_content != NULL)
  326. fclose(out_content);
  327. if (out_signature != NULL)
  328. fclose(out_signature);
  329. return true;
  330. }