summaryrefslogtreecommitdiff
path: root/src/genca.cc
blob: 976232103806194090a1e6e157bfa6af12f318ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// -*- mode: c++; c-basic-offset: 2; -*-

#include "common.hh"

#include <fstream>
#include <iostream>
#include <memory>
#include <string>

#include "args.hh"
#include "logger.hh"
#include "ssl.hh"

namespace {

bool genca(std::ostream& out, std::string const& name) {
  std::unique_ptr<Logger> logger(Logger::create_stderr());
  std::unique_ptr<SSLEntropy> entropy(SSLEntropy::create(logger.get()));
  if (!entropy) return false;
  std::string key;
  if (!SSLKey::generate(logger.get(), entropy.get(), &key)) return false;
  std::string cert;
  std::unique_ptr<SSLKey> pkey(SSLKey::load(logger.get(), key, entropy.get()));
  if (!SSLCert::generate(logger.get(), entropy.get(), nullptr, nullptr, name,
                         pkey.get(), &cert)) return false;
  out << cert << '\n' << key << std::endl;
  return true;
}

}  // namespace

int main(int argc, char** argv) {
  std::unique_ptr<Args> args(Args::create());
  args->add('o', "output", "FILE",
            "output certificate and key to FILE instead of stdout.");
  args->add('n', "name", "NAME",
            "Issuer name to use instead of TransparentProxy");
  args->add('h', "help", "display this text and exit.");
  args->add('V', "version", "display version and exit.");
  if (!args->run(argc, argv)) {
    std::cerr << "Try `tp-genca --help` for usage." << std::endl;
    return EXIT_FAILURE;
  }
  if (args->is_set('h')) {
    std::cout << "Usage: `tp-genca [OPTIONS...]`\n"
              << "Generate a self-signed CA to use for MITM SSL interception.\n"
              << '\n';
    args->print_help();
    return EXIT_SUCCESS;
  }
  if (args->is_set('V')) {
    std::cout << "TransparentProxy version " VERSION
              << " written by Joel Klinghed <the_jk@yahoo.com>" << std::endl;
    return EXIT_SUCCESS;
  }
  if (!args->arguments().empty()) {
    std::cerr << "Too many arguments.\n"
              << "Try `tp-genca --help` for usage." << std::endl;
    return EXIT_FAILURE;
  }
  auto name = args->arg('n', "TransparentProxy");
  auto output = args->arg('o', nullptr);
  if (output) {
    std::ofstream out(output);
    return genca(out, name) ? EXIT_SUCCESS : EXIT_FAILURE;
  } else {
    return genca(std::cout, name) ? EXIT_SUCCESS : EXIT_FAILURE;
  }
}