Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(501)

Unified Diff: ipsec_manager.cc

Issue 6508016: vpn-manager: Add l2tp/ipsec vpn manager (Closed) Base URL: ssh://git@gitrw.chromium.org:9222/vpn-manager.git@master
Patch Set: respond to petkov Created 9 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: ipsec_manager.cc
diff --git a/ipsec_manager.cc b/ipsec_manager.cc
new file mode 100644
index 0000000000000000000000000000000000000000..7145aeccca05c08d8f0bbafc81dd6707cf620728
--- /dev/null
+++ b/ipsec_manager.cc
@@ -0,0 +1,309 @@
+// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "vpn-manager/ipsec_manager.h"
+
+#include <grp.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <string>
+#include <vector>
+
+#include "base/file_util.h"
Will Drewry 2011/03/05 04:06:39 nit: use <> unless the files are part of your pack
kmixter1 2011/03/11 01:34:27 There's some disagreement about this in the chrome
petkov 2011/03/11 19:12:53 FWIW, I agree with Will on this one. Although styl
kmixter1 2011/03/11 20:53:04 I think it comes down to how you see code from lib
+#include "base/logging.h"
+#include "base/string_util.h"
+#include "chromeos/process.h"
+#include "gflags/gflags.h"
Will Drewry 2011/03/05 04:06:39 I like gflags myself, but I thought we were trying
kmixter1 2011/03/11 01:34:27 Same thing - crash-reporter, cromo, metrics, monit
+
+#pragma GCC diagnostic ignored "-Wstrict-aliasing"
+DEFINE_int32(ipsec_timeout, 10, "timeout for ipsec to be established");
+DEFINE_string(local, "", "local IP address (needed for PSK)");
+DEFINE_string(leftprotoport, "17/1701", "client protocol/port");
+DEFINE_bool(pfs, false, "pfs");
+DEFINE_bool(rekey, false, "rekey");
+DEFINE_string(rightprotoport, "17/1701", "server protocol/port");
+#pragma GCC diagnostic error "-Wstrict-aliasing"
+
+const char kStarterPidFile[] = "/var/run/starter.pid";
Will Drewry 2011/03/05 04:06:39 Any reason not to use a subdirectory to clean up t
kmixter1 2011/03/11 01:34:27 This is written as part of strongswan, I'm just re
+const char kIpsecConnectionName[] = "ipsec_managed";
+const char kIpsecUpFile[] = "/tmp/ipsec-up";
Will Drewry 2011/03/05 04:06:39 note for myself: trace through and see where this
kmixter1 2011/03/11 01:34:27 Changed to /var/run/ipsec/up.
+const char kIpsecGroupName[] = "ipsec";
+const char kStatefulContainer[] = "/mnt/stateful_partition/etc";
+
+// Give IPsec layer 2 seconds to shut down before killing it.
+const int kTermTimeout = 2;
+
+using ::chromeos::Process;
+using ::chromeos::ProcessImpl;
+
+IpsecManager::IpsecManager()
+ : ServiceManager("ipsec"),
Will Drewry 2011/03/05 04:06:39 optional style nit: kServiceName ;)
kmixter1 2011/03/11 01:34:27 Done.
+ output_fd_(-1),
+ ike_version_(0),
+ ipsec_group_(0),
+ stateful_container_(kStatefulContainer),
+ ipsec_up_file_(kIpsecUpFile),
+ starter_pid_file_(kStarterPidFile),
+ starter_(new ProcessImpl) {
+}
+
+bool IpsecManager::Initialize(int ike_version,
+ const std::string& remote,
+ const std::string& psk_file,
+ const std::string& server_ca_file,
+ const std::string& client_key_file,
+ const std::string& client_cert_file) {
+ if (remote.empty()) {
+ LOG(ERROR) << "Missing remote to IPsec layer";
+ return false;
+ }
+ remote_ = remote;
+
+ if (psk_file.empty()) {
+ if (server_ca_file.empty() && client_key_file.empty() &&
+ client_cert_file.empty()) {
+ LOG(ERROR) << "Must specify either PSK or certificates for IPsec layer";
+ return false;
+ }
+
+ // Must be a certificate based connection.
+ if (!file_util::PathExists(FilePath(server_ca_file))) {
+ LOG(ERROR) << "Invalid server CA file for IPsec layer: "
+ << server_ca_file;
+ return false;
+ }
+ server_ca_file_ = server_ca_file;
+
+ if (!file_util::PathExists(FilePath(client_key_file))) {
+ LOG(ERROR) << "Invalid client key file for IPsec layer: "
+ << client_key_file;
+ return false;
+ }
+ client_key_file_ = client_key_file;
+
+ if (!file_util::PathExists(FilePath(client_cert_file))) {
+ LOG(ERROR) << "Invalid client certificate file for IPsec layer: "
+ << client_key_file;
+ return false;
+ }
+ client_cert_file_ = client_cert_file;
+ } else {
+ if (!server_ca_file.empty() ||
+ !client_key_file.empty() ||
+ !client_cert_file.empty()) {
+ LOG(ERROR) << "Specified both PSK and certificates for IPsec layer";
+ return false;
+ }
+ if (!file_util::PathExists(FilePath(psk_file))) {
+ LOG(ERROR) << "Invalid PSK file for IPsec layer: " << psk_file;
+ return false;
+ }
+ psk_file_ = psk_file;
+ }
+
+ if (ike_version != 1 && ike_version != 2) {
+ LOG(ERROR) << "Unsupported IKE version" << ike_version;
+ return false;
+ }
+ ike_version_ = ike_version;
+
+ file_util::Delete(FilePath(kIpsecUpFile), false);
Will Drewry 2011/03/05 04:06:39 Is this being created by the ipsec daemon or somew
kmixter1 2011/03/11 01:34:27 In the ipdown script that we install - and now it'
+
+ return true;
+}
+
+bool IpsecManager::FormatPsk(const FilePath& input_file,
+ std::string* formatted) {
+ std::string psk;
+ if (!file_util::ReadFileToString(input_file, &psk)) {
+ LOG(ERROR) << "Unable to read PSK from " << input_file.value();
+ return false;
+ }
+ if (FLAGS_local.empty()) {
+ LOG(ERROR) << "Local IP address must be supplied for PSK mode";
+ return false;
+ }
+ TrimWhitespaceASCII(psk, TRIM_TRAILING, &psk);
+ *formatted =
+ StringPrintf("%s %s : PSK \"%s\"\n", FLAGS_local.c_str(),
+ remote_.c_str(), psk.c_str());
+ return true;
+}
+
+void IpsecManager::KillCurrentlyRunning() {
+ if (!file_util::PathExists(FilePath(starter_pid_file_)))
+ return;
+ starter_->ResetPidByFile(starter_pid_file_);
+ if (Process::ProcessExists(starter_->pid()))
+ starter_->Reset(0);
+ else
+ starter_->Release();
+ file_util::Delete(FilePath(starter_pid_file_), false);
+}
+
+bool IpsecManager::StartStarter() {
+ KillCurrentlyRunning();
+ LOG(INFO) << "Starting starter";
+ starter_->AddArg(IPSEC_STARTER);
+ starter_->AddArg("--nofork");
+ starter_->RedirectUsingPipe(STDERR_FILENO, false);
+ if (!starter_->Start()) {
+ LOG(ERROR) << "Starter did not start successfully";
+ return false;
+ }
+ output_fd_ = starter_->GetPipe(STDERR_FILENO);
+ pid_t starter_pid = starter_->pid();
+ LOG(INFO) << "Starter started as pid " << starter_pid;
+ ipsec_prefix_ = StringPrintf("ipsec[%d]: ", starter_pid);
+ return true;
+}
+
+inline void AppendBoolSetting(std::string* config, const char* key,
+ bool value) {
+ config->append(StringPrintf("\t%s=%s\n", key, value ? "yes" : "no"));
+}
+
+inline void AppendStringSetting(std::string* config, const char* key,
+ const std::string& value) {
+ config->append(StringPrintf("\t%s=%s\n", key, value.c_str()));
+}
+
+inline void AppendIntSetting(std::string* config, const char* key,
+ int value) {
+ config->append(StringPrintf("\t%s=%d\n", key, value));
+}
+
+std::string IpsecManager::FormatStarterConfigFile() {
+ std::string config;
+ config.append("config setup\n");
+ if (ike_version_ == 1) {
+ AppendBoolSetting(&config, "charonstart", false);
+ } else {
+ AppendBoolSetting(&config, "plutostart", false);
+ }
+ config.append("conn managed\n");
+ AppendStringSetting(&config, "keyexchange",
+ ike_version_ == 1 ? "ikev1" : "ikev2");
+ if (!psk_file_.empty()) AppendStringSetting(&config, "authby", "psk");
+ AppendBoolSetting(&config, "pfs", FLAGS_pfs);
+ AppendBoolSetting(&config, "rekey", FLAGS_rekey);
+ AppendStringSetting(&config, "left", "%defaultroute");
+ AppendStringSetting(&config, "leftprotoport", FLAGS_leftprotoport);
+ AppendStringSetting(&config, "leftupdown", IPSEC_UPDOWN);
+ AppendStringSetting(&config, "right", remote_);
+ AppendStringSetting(&config, "rightprotoport", FLAGS_rightprotoport);
+ AppendStringSetting(&config, "auto", "start");
+ return config;
+}
+
+bool IpsecManager::SetIpsecGroup(const FilePath& file_path) {
+ return chown(file_path.value().c_str(), getuid(), ipsec_group_) == 0;
+}
+
+bool IpsecManager::WriteConfigFiles() {
+ // We need to keep secrets in /mnt/stateful_partition/etc for now
+ // because pluto loses permissions to /home/chronos before it tries
+ // reading secrets.
+ // TODO(kmixter): write this via a fifo.
+ FilePath secrets_path_ = FilePath(stateful_container_).
+ Append("ipsec.secrets");
+ file_util::Delete(secrets_path_, false);
+ if (!psk_file_.empty()) {
+ std::string formatted;
+ if (!FormatPsk(FilePath(psk_file_), &formatted)) {
+ LOG(ERROR) << "Unable to create secrets contents";
+ return false;
+ }
+ if (!file_util::WriteFile(secrets_path_, formatted.c_str(),
+ formatted.length()) ||
+ !SetIpsecGroup(secrets_path_)) {
+ LOG(ERROR) << "Unable to write secrets file " << secrets_path_.value();
+ return false;
+ }
+ } else {
+ LOG(FATAL) << "Certificate mode not yet implemented";
+ }
+ FilePath starter_config_path = temp_path_->Append("ipsec.conf");
+ std::string starter_config = FormatStarterConfigFile();
+ if (!file_util::WriteFile(starter_config_path, starter_config.c_str(),
+ starter_config.size()) ||
+ !SetIpsecGroup(starter_config_path)) {
+ LOG(ERROR) << "Unable to write ipsec config files";
+ return false;
+ }
+ FilePath config_symlink_path = FilePath(stateful_container_).
+ Append("ipsec.conf");
+ file_util::Delete(config_symlink_path, false);
+ if (symlink(starter_config_path.value().c_str(),
+ config_symlink_path.value().c_str()) < 0) {
+ LOG(ERROR) << "Unable to symlink config file";
+ return false;
+ }
+ return true;
+}
+
+bool IpsecManager::Start() {
+ if (!ipsec_group_) {
+ struct group group_buffer;
+ struct group* group_result = NULL;
+ char buffer[256];
+ if (getgrnam_r(kIpsecGroupName, &group_buffer, buffer,
+ sizeof(buffer), &group_result) != 0 || !group_result) {
+ LOG(ERROR) << "Cannot find group id for " << kIpsecGroupName;
+ return false;
+ }
+ ipsec_group_ = group_result->gr_gid;
+ DLOG(INFO) << "Using ipsec group " << ipsec_group_;
+ }
+ if (!WriteConfigFiles())
+ return false;
+ if (!StartStarter())
+ return false;
+
+ start_ticks_ = base::TimeTicks::Now();
+
+ return true;
+}
+
+int IpsecManager::Poll() {
+ if (is_running()) return -1;
+ if (start_ticks_.is_null()) return -1;
+ if (!file_util::PathExists(FilePath(ipsec_up_file_))) {
+ if (base::TimeTicks::Now() - start_ticks_ >
+ base::TimeDelta::FromSeconds(FLAGS_ipsec_timeout)) {
+ LOG(ERROR) << "IPsec connection timed out";
+ OnStopped(false);
+ // Poll in 1 second in order to check exit conditions.
+ }
+ return 1000;
+ }
+
+ // This indicates that the connection came up successfully.
+ LOG(INFO) << "IPsec connection now up";
+ OnStarted();
+ return -1;
+}
+
+void IpsecManager::ProcessOutput() {
+ ServiceManager::WriteFdToSyslog(output_fd_, ipsec_prefix_);
+}
+
+bool IpsecManager::IsChild(pid_t pid) {
+ return pid == starter_->pid();
+}
+
+void IpsecManager::Stop() {
+ if (starter_->pid() == 0) {
+ return;
+ }
+
+ if (!starter_->Kill(SIGTERM, kTermTimeout)) {
+ starter_->Kill(SIGKILL, 0);
+ OnStopped(true);
+ return;
+ }
+ OnStopped(false);
+}

Powered by Google App Engine
This is Rietveld 408576698