gpgv.cc 11 KB

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