You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

461 lines
14 KiB

  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/fileutl.h>
  7. #include <apt-pkg/gpgv.h>
  8. #include <apt-pkg/strutl.h>
  9. #include <errno.h>
  10. #include <fcntl.h>
  11. #include <stddef.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <sys/wait.h>
  16. #include <unistd.h>
  17. #include <algorithm>
  18. #include <fstream>
  19. #include <iostream>
  20. #include <memory>
  21. #include <sstream>
  22. #include <string>
  23. #include <vector>
  24. #include <apti18n.h>
  25. /*}}}*/
  26. static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
  27. {
  28. std::string out;
  29. std::string tmpdir = GetTempDir();
  30. strprintf(out, "%s/%s.XXXXXX", tmpdir.c_str(), basename);
  31. return strdup(out.c_str());
  32. }
  33. /*}}}*/
  34. // ExecGPGV - returns the command needed for verify /*{{{*/
  35. // ---------------------------------------------------------------------
  36. /* Generating the commandline for calling gpg is somehow complicated as
  37. we need to add multiple keyrings and user supplied options.
  38. Also, as gpg has no options to enforce a certain reduced style of
  39. clear-signed files (=the complete content of the file is signed and
  40. the content isn't encoded) we do a divide and conquer approach here
  41. and split up the clear-signed file in message and signature for gpg.
  42. And as a cherry on the cake, we use our apt-key wrapper to do part
  43. of the lifting in regards to merging keyrings. Fun for the whole family.
  44. */
  45. static bool iovprintf(std::ostream &out, const char *format,
  46. va_list &args, ssize_t &size) {
  47. char *S = (char*)malloc(size);
  48. ssize_t const n = vsnprintf(S, size, format, args);
  49. if (n > -1 && n < size) {
  50. out << S;
  51. free(S);
  52. return true;
  53. } else {
  54. if (n > -1)
  55. size = n + 1;
  56. else
  57. size *= 2;
  58. }
  59. free(S);
  60. return false;
  61. }
  62. static void APT_PRINTF(4) apt_error(std::ostream &outterm, int const statusfd, int fd[2], const char *format, ...)
  63. {
  64. std::ostringstream outstr;
  65. std::ostream &out = (statusfd == -1) ? outterm : outstr;
  66. va_list args;
  67. ssize_t size = 400;
  68. while (true) {
  69. bool ret;
  70. va_start(args,format);
  71. ret = iovprintf(out, format, args, size);
  72. va_end(args);
  73. if (ret == true)
  74. break;
  75. }
  76. if (statusfd != -1)
  77. {
  78. auto const errtag = "[APTKEY:] ERROR ";
  79. outstr << '\n';
  80. auto const errtext = outstr.str();
  81. if (FileFd::Write(fd[1], errtag, strlen(errtag)) == false ||
  82. FileFd::Write(fd[1], errtext.data(), errtext.size()) == false)
  83. outterm << errtext << std::flush;
  84. }
  85. }
  86. void ExecGPGV(std::string const &File, std::string const &FileGPG,
  87. int const &statusfd, int fd[2], std::string const &key)
  88. {
  89. #define EINTERNAL 111
  90. std::string const aptkey = _config->Find("Dir::Bin::apt-key", CMAKE_INSTALL_FULL_BINDIR "/apt-key");
  91. bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
  92. struct exiter {
  93. std::vector<const char *> files;
  94. void operator ()(int code) APT_NORETURN {
  95. std::for_each(files.begin(), files.end(), unlink);
  96. exit(code);
  97. }
  98. } local_exit;
  99. std::vector<const char *> Args;
  100. Args.reserve(10);
  101. Args.push_back(aptkey.c_str());
  102. Args.push_back("--quiet");
  103. Args.push_back("--readonly");
  104. auto const keysFileFpr = VectorizeString(key, ',');
  105. for (auto const &k: keysFileFpr)
  106. {
  107. if (unlikely(k.empty()))
  108. continue;
  109. if (k[0] == '/')
  110. {
  111. Args.push_back("--keyring");
  112. Args.push_back(k.c_str());
  113. }
  114. else
  115. {
  116. Args.push_back("--keyid");
  117. Args.push_back(k.c_str());
  118. }
  119. }
  120. Args.push_back("verify");
  121. char statusfdstr[10];
  122. if (statusfd != -1)
  123. {
  124. Args.push_back("--status-fd");
  125. snprintf(statusfdstr, sizeof(statusfdstr), "%i", statusfd);
  126. Args.push_back(statusfdstr);
  127. }
  128. Configuration::Item const *Opts;
  129. Opts = _config->Tree("Acquire::gpgv::Options");
  130. if (Opts != 0)
  131. {
  132. Opts = Opts->Child;
  133. for (; Opts != 0; Opts = Opts->Next)
  134. {
  135. if (Opts->Value.empty() == true)
  136. continue;
  137. Args.push_back(Opts->Value.c_str());
  138. }
  139. }
  140. enum { DETACHED, CLEARSIGNED } releaseSignature = (FileGPG != File) ? DETACHED : CLEARSIGNED;
  141. char * sig = NULL;
  142. char * data = NULL;
  143. char * conf = nullptr;
  144. // Dump the configuration so apt-key picks up the correct Dir values
  145. {
  146. conf = GenerateTemporaryFileTemplate("apt.conf");
  147. if (conf == nullptr) {
  148. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for passing config to apt-key");
  149. local_exit(EINTERNAL);
  150. }
  151. int confFd = mkstemp(conf);
  152. if (confFd == -1) {
  153. apt_error(std::cerr, statusfd, fd, "Couldn't create temporary file %s for passing config to apt-key", conf);
  154. local_exit(EINTERNAL);
  155. }
  156. local_exit.files.push_back(conf);
  157. std::ofstream confStream(conf);
  158. close(confFd);
  159. _config->Dump(confStream);
  160. confStream.close();
  161. setenv("APT_CONFIG", conf, 1);
  162. }
  163. if (releaseSignature == DETACHED)
  164. {
  165. Args.push_back(FileGPG.c_str());
  166. Args.push_back(File.c_str());
  167. }
  168. else // clear-signed file
  169. {
  170. sig = GenerateTemporaryFileTemplate("apt.sig");
  171. data = GenerateTemporaryFileTemplate("apt.data");
  172. if (sig == NULL || data == NULL)
  173. {
  174. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfile names for splitting up %s", File.c_str());
  175. local_exit(EINTERNAL);
  176. }
  177. int const sigFd = mkstemp(sig);
  178. int const dataFd = mkstemp(data);
  179. if (dataFd != -1)
  180. local_exit.files.push_back(data);
  181. if (sigFd != -1)
  182. local_exit.files.push_back(sig);
  183. if (sigFd == -1 || dataFd == -1)
  184. {
  185. apt_error(std::cerr, statusfd, fd, "Couldn't create tempfiles for splitting up %s", File.c_str());
  186. local_exit(EINTERNAL);
  187. }
  188. FileFd signature;
  189. signature.OpenDescriptor(sigFd, FileFd::WriteOnly, true);
  190. FileFd message;
  191. message.OpenDescriptor(dataFd, FileFd::WriteOnly, true);
  192. if (signature.Failed() == true || message.Failed() == true ||
  193. SplitClearSignedFile(File, &message, nullptr, &signature) == false)
  194. {
  195. apt_error(std::cerr, statusfd, fd, "Splitting up %s into data and signature failed", File.c_str());
  196. local_exit(112);
  197. }
  198. Args.push_back(sig);
  199. Args.push_back(data);
  200. }
  201. Args.push_back(NULL);
  202. if (Debug == true)
  203. {
  204. std::clog << "Preparing to exec: ";
  205. for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
  206. std::clog << " " << *a;
  207. std::clog << std::endl;
  208. }
  209. if (statusfd != -1)
  210. {
  211. int const nullfd = open("/dev/null", O_WRONLY);
  212. close(fd[0]);
  213. // Redirect output to /dev/null; we read from the status fd
  214. if (statusfd != STDOUT_FILENO)
  215. dup2(nullfd, STDOUT_FILENO);
  216. if (statusfd != STDERR_FILENO)
  217. dup2(nullfd, STDERR_FILENO);
  218. // Redirect the pipe to the status fd (3)
  219. dup2(fd[1], statusfd);
  220. putenv((char *)"LANG=");
  221. putenv((char *)"LC_ALL=");
  222. putenv((char *)"LC_MESSAGES=");
  223. }
  224. // We have created tempfiles we have to clean up
  225. // and we do an additional check, so fork yet another time …
  226. pid_t pid = ExecFork();
  227. if(pid < 0) {
  228. apt_error(std::cerr, statusfd, fd, "Fork failed for %s to check %s", Args[0], File.c_str());
  229. local_exit(EINTERNAL);
  230. }
  231. if(pid == 0)
  232. {
  233. if (statusfd != -1)
  234. dup2(fd[1], statusfd);
  235. execvp(Args[0], (char **) &Args[0]);
  236. apt_error(std::cerr, statusfd, fd, "Couldn't execute %s to check %s", Args[0], File.c_str());
  237. local_exit(EINTERNAL);
  238. }
  239. // Wait and collect the error code - taken from WaitPid as we need the exact Status
  240. int Status;
  241. while (waitpid(pid,&Status,0) != pid)
  242. {
  243. if (errno == EINTR)
  244. continue;
  245. apt_error(std::cerr, statusfd, fd, _("Waited for %s but it wasn't there"), "apt-key");
  246. local_exit(EINTERNAL);
  247. }
  248. // check if it exit'ed normally …
  249. if (WIFEXITED(Status) == false)
  250. {
  251. apt_error(std::cerr, statusfd, fd, _("Sub-process %s exited unexpectedly"), "apt-key");
  252. local_exit(EINTERNAL);
  253. }
  254. // … and with a good exit code
  255. if (WEXITSTATUS(Status) != 0)
  256. {
  257. // we forward the statuscode, so don't generate a message on the fd in this case
  258. apt_error(std::cerr, -1, fd, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status));
  259. local_exit(WEXITSTATUS(Status));
  260. }
  261. // everything fine
  262. local_exit(0);
  263. }
  264. /*}}}*/
  265. // SplitClearSignedFile - split message into data/signature /*{{{*/
  266. static bool GetLineErrno(std::unique_ptr<char, decltype(&free)> &buffer, size_t *n, FILE *stream, std::string const &InFile, bool acceptEoF = false)
  267. {
  268. errno = 0;
  269. auto lineptr = buffer.release();
  270. auto const result = getline(&lineptr, n, stream);
  271. buffer.reset(lineptr);
  272. if (errno != 0)
  273. return _error->Errno("getline", "Could not read from %s", InFile.c_str());
  274. if (result == -1)
  275. {
  276. if (acceptEoF)
  277. return false;
  278. return _error->Error("Splitting of clearsigned file %s failed as it doesn't contain all expected parts", InFile.c_str());
  279. }
  280. // We remove all whitespaces including newline here as
  281. // a) gpgv ignores them for signature
  282. // b) we can write out a \n in code later instead of dealing with \r\n or not
  283. _strrstrip(buffer.get());
  284. return true;
  285. }
  286. bool SplitClearSignedFile(std::string const &InFile, FileFd * const ContentFile,
  287. std::vector<std::string> * const ContentHeader, FileFd * const SignatureFile)
  288. {
  289. std::unique_ptr<FILE, decltype(&fclose)> in{fopen(InFile.c_str(), "r"), &fclose};
  290. if (in.get() == nullptr)
  291. return _error->Errno("fopen", "can not open %s", InFile.c_str());
  292. struct ScopedErrors
  293. {
  294. ScopedErrors() { _error->PushToStack(); }
  295. ~ScopedErrors() { _error->MergeWithStack(); }
  296. } scoped;
  297. std::unique_ptr<char, decltype(&free)> buf{nullptr, &free};
  298. size_t buf_size = 0;
  299. // start of the message
  300. if (GetLineErrno(buf, &buf_size, in.get(), InFile) == false)
  301. return false; // empty or read error
  302. if (strcmp(buf.get(), "-----BEGIN PGP SIGNED MESSAGE-----") != 0)
  303. {
  304. // this might be an unsigned file we don't want to report errors for,
  305. // but still finish unsuccessful none the less.
  306. while (GetLineErrno(buf, &buf_size, in.get(), InFile, true))
  307. if (strcmp(buf.get(), "-----BEGIN PGP SIGNED MESSAGE-----") == 0)
  308. return _error->Error("Clearsigned file '%s' does not start with a signed message block.", InFile.c_str());
  309. return false;
  310. }
  311. // save "Hash" Armor Headers
  312. while (true)
  313. {
  314. if (GetLineErrno(buf, &buf_size, in.get(), InFile) == false)
  315. return false;
  316. if (*buf == '\0')
  317. break; // empty line ends the Armor Headers
  318. if (ContentHeader != NULL && strncmp(buf.get(), "Hash: ", strlen("Hash: ")) == 0)
  319. ContentHeader->push_back(buf.get());
  320. }
  321. // the message itself
  322. bool first_line = true;
  323. bool good_write = true;
  324. while (true)
  325. {
  326. if (good_write == false || GetLineErrno(buf, &buf_size, in.get(), InFile) == false)
  327. return false;
  328. if (strcmp(buf.get(), "-----BEGIN PGP SIGNATURE-----") == 0)
  329. {
  330. if (SignatureFile != nullptr)
  331. {
  332. good_write &= SignatureFile->Write(buf.get(), strlen(buf.get()));
  333. good_write &= SignatureFile->Write("\n", 1);
  334. }
  335. break;
  336. }
  337. // we don't have any fields which need dash-escaped,
  338. // but implementations are free to encode all lines …
  339. char const *dashfree = buf.get();
  340. if (strncmp(dashfree, "- ", 2) == 0)
  341. dashfree += 2;
  342. if (first_line == true) // first line does not need a newline
  343. first_line = false;
  344. else if (ContentFile != nullptr)
  345. good_write &= ContentFile->Write("\n", 1);
  346. if (ContentFile != nullptr)
  347. good_write &= ContentFile->Write(dashfree, strlen(dashfree));
  348. }
  349. // collect all signatures
  350. bool open_signature = true;
  351. while (true)
  352. {
  353. if (good_write == false)
  354. return false;
  355. if (GetLineErrno(buf, &buf_size, in.get(), InFile, true) == false)
  356. break;
  357. if (open_signature && strcmp(buf.get(), "-----END PGP SIGNATURE-----") == 0)
  358. open_signature = false;
  359. else if (open_signature == false && strcmp(buf.get(), "-----BEGIN PGP SIGNATURE-----") == 0)
  360. open_signature = true;
  361. else if (open_signature == false)
  362. return _error->Error("Clearsigned file '%s' contains unsigned lines.", InFile.c_str());
  363. if (SignatureFile != nullptr)
  364. {
  365. good_write &= SignatureFile->Write(buf.get(), strlen(buf.get()));
  366. good_write &= SignatureFile->Write("\n", 1);
  367. }
  368. }
  369. if (open_signature == true)
  370. return _error->Error("Signature in file %s wasn't closed", InFile.c_str());
  371. // Flush the files
  372. if (SignatureFile != nullptr)
  373. SignatureFile->Flush();
  374. if (ContentFile != nullptr)
  375. ContentFile->Flush();
  376. // Catch-all for "unhandled" read/sync errors
  377. if (_error->PendingError())
  378. return false;
  379. return true;
  380. }
  381. /*}}}*/
  382. bool OpenMaybeClearSignedFile(std::string const &ClearSignedFileName, FileFd &MessageFile) /*{{{*/
  383. {
  384. char * const message = GenerateTemporaryFileTemplate("fileutl.message");
  385. int const messageFd = mkstemp(message);
  386. if (messageFd == -1)
  387. {
  388. free(message);
  389. return _error->Errno("mkstemp", "Couldn't create temporary file to work with %s", ClearSignedFileName.c_str());
  390. }
  391. // we have the fd, that's enough for us
  392. unlink(message);
  393. free(message);
  394. MessageFile.OpenDescriptor(messageFd, FileFd::ReadWrite | FileFd::BufferedWrite, true);
  395. if (MessageFile.Failed() == true)
  396. return _error->Error("Couldn't open temporary file to work with %s", ClearSignedFileName.c_str());
  397. _error->PushToStack();
  398. bool const splitDone = SplitClearSignedFile(ClearSignedFileName, &MessageFile, NULL, NULL);
  399. bool const errorDone = _error->PendingError();
  400. _error->MergeWithStack();
  401. if (splitDone == false)
  402. {
  403. MessageFile.Close();
  404. if (errorDone == true)
  405. return false;
  406. // we deal with an unsigned file
  407. MessageFile.Open(ClearSignedFileName, FileFd::ReadOnly);
  408. }
  409. else // clear-signed
  410. {
  411. if (MessageFile.Seek(0) == false)
  412. return _error->Errno("lseek", "Unable to seek back in message for file %s", ClearSignedFileName.c_str());
  413. }
  414. return MessageFile.Failed() == false;
  415. }
  416. /*}}}*/