gpgv.cc 11 KB

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