gpgv.cc 12 KB

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