gpgv.cc 11 KB

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