gpgv.cc 12 KB

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