1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include "shill/vpn/openvpn_driver.h"
18 
19 #include <algorithm>
20 
21 #include <base/files/file_path.h>
22 #include <base/files/file_util.h>
23 #include <base/files/scoped_temp_dir.h>
24 #include <base/strings/string_util.h>
25 #include <base/strings/stringprintf.h>
26 #if defined(__ANDROID__)
27 #include <dbus/service_constants.h>
28 #else
29 #include <chromeos/dbus/service_constants.h>
30 #endif  // __ANDROID__
31 #include <gtest/gtest.h>
32 
33 #include "shill/error.h"
34 #include "shill/ipconfig.h"
35 #include "shill/logging.h"
36 #include "shill/mock_adaptors.h"
37 #include "shill/mock_certificate_file.h"
38 #include "shill/mock_device_info.h"
39 #include "shill/mock_event_dispatcher.h"
40 #include "shill/mock_manager.h"
41 #include "shill/mock_metrics.h"
42 #include "shill/mock_process_manager.h"
43 #include "shill/mock_service.h"
44 #include "shill/mock_store.h"
45 #include "shill/mock_virtual_device.h"
46 #include "shill/nice_mock_control.h"
47 #include "shill/rpc_task.h"
48 #include "shill/technology.h"
49 #include "shill/virtual_device.h"
50 #include "shill/vpn/mock_openvpn_management_server.h"
51 #include "shill/vpn/mock_vpn_service.h"
52 #include "shill/vpn/vpn_service.h"
53 
54 using base::FilePath;
55 using base::WeakPtr;
56 using std::map;
57 using std::string;
58 using std::vector;
59 using testing::_;
60 using testing::AnyNumber;
61 using testing::DoAll;
62 using testing::ElementsAreArray;
63 using testing::Field;
64 using testing::Mock;
65 using testing::Ne;
66 using testing::NiceMock;
67 using testing::Return;
68 using testing::SetArgumentPointee;
69 using testing::StrictMock;
70 
71 namespace shill {
72 
73 struct AuthenticationExpectations {
AuthenticationExpectationsshill::AuthenticationExpectations74   AuthenticationExpectations()
75       : remote_authentication_type(Metrics::kVpnRemoteAuthenticationTypeMax) {}
AuthenticationExpectationsshill::AuthenticationExpectations76   AuthenticationExpectations(
77       const string& ca_cert_in,
78       const string& client_cert_in,
79       const string& user_in,
80       const string& otp_in,
81       const string& token_in,
82       Metrics::VpnRemoteAuthenticationType remote_authentication_type_in,
83       const vector<Metrics::VpnUserAuthenticationType>
84           &user_authentication_types_in)
85       : ca_cert(ca_cert_in),
86         client_cert(client_cert_in),
87         user(user_in),
88         otp(otp_in),
89         token(token_in),
90         remote_authentication_type(remote_authentication_type_in),
91         user_authentication_types(user_authentication_types_in) {}
92   string ca_cert;
93   string client_cert;
94   string user;
95   string otp;
96   string token;
97   Metrics::VpnRemoteAuthenticationType remote_authentication_type;
98   vector<Metrics::VpnUserAuthenticationType> user_authentication_types;
99 };
100 
101 class OpenVPNDriverTest
102     : public testing::TestWithParam<AuthenticationExpectations>,
103       public RPCTaskDelegate {
104  public:
OpenVPNDriverTest()105   OpenVPNDriverTest()
106       : device_info_(&control_, &dispatcher_, &metrics_, &manager_),
107         metrics_(&dispatcher_),
108         manager_(&control_, &dispatcher_, &metrics_),
109         driver_(new OpenVPNDriver(&control_, &dispatcher_, &metrics_, &manager_,
110                                   &device_info_, &process_manager_)),
111         service_(new MockVPNService(&control_, &dispatcher_, &metrics_,
112                                     &manager_, driver_)),
113         device_(new MockVirtualDevice(
114             &control_, &dispatcher_, &metrics_, &manager_,
115             kInterfaceName, kInterfaceIndex, Technology::kVPN)),
116         certificate_file_(new MockCertificateFile()),
117         extra_certificates_file_(new MockCertificateFile()),
118         management_server_(new NiceMock<MockOpenVPNManagementServer>()) {
119     driver_->management_server_.reset(management_server_);
120     driver_->certificate_file_.reset(certificate_file_);  // Passes ownership.
121     driver_->extra_certificates_file_.reset(
122         extra_certificates_file_);  // Passes ownership.
123     CHECK(temporary_directory_.CreateUniqueTempDir());
124     driver_->openvpn_config_directory_ =
125         temporary_directory_.path().Append(kOpenVPNConfigDirectory);
126   }
127 
~OpenVPNDriverTest()128   virtual ~OpenVPNDriverTest() {}
129 
TearDown()130   virtual void TearDown() {
131     driver_->default_service_callback_tag_ = 0;
132     driver_->pid_ = 0;
133     driver_->device_ = nullptr;
134     driver_->service_ = nullptr;
135     if (!lsb_release_file_.empty()) {
136       EXPECT_TRUE(base::DeleteFile(lsb_release_file_, false));
137       lsb_release_file_.clear();
138     }
139   }
140 
141  protected:
142   static const char kOption[];
143   static const char kProperty[];
144   static const char kValue[];
145   static const char kOption2[];
146   static const char kProperty2[];
147   static const char kValue2[];
148   static const char kGateway1[];
149   static const char kNetmask1[];
150   static const char kNetwork1[];
151   static const char kGateway2[];
152   static const char kNetmask2[];
153   static const char kNetwork2[];
154   static const char kInterfaceName[];
155   static const int kInterfaceIndex;
156   static const char kOpenVPNConfigDirectory[];
157 
SetArg(const string & arg,const string & value)158   void SetArg(const string& arg, const string& value) {
159     driver_->args()->SetString(arg, value);
160   }
161 
SetArgArray(const string & arg,const vector<string> & value)162   void SetArgArray(const string& arg, const vector<string>& value) {
163     driver_->args()->SetStrings(arg, value);
164   }
165 
GetArgs()166   KeyValueStore* GetArgs() {
167     return driver_->args();
168   }
169 
GetProviderProperties(const PropertyStore & store)170   KeyValueStore GetProviderProperties(const PropertyStore& store) {
171     KeyValueStore props;
172     Error error;
173     EXPECT_TRUE(
174         store.GetKeyValueStoreProperty(kProviderProperty, &props, &error));
175     return props;
176   }
177 
RemoveStringArg(const string & arg)178   void RemoveStringArg(const string& arg) {
179     driver_->args()->RemoveString(arg);
180   }
181 
GetSelectedService()182   const ServiceRefPtr& GetSelectedService() {
183     return device_->selected_service();
184   }
185 
InitManagementChannelOptions(vector<vector<string>> * options,Error * error)186   bool InitManagementChannelOptions(
187       vector<vector<string>>* options, Error* error) {
188     return driver_->InitManagementChannelOptions(options, error);
189   }
190 
GetSockets()191   Sockets* GetSockets() {
192     return &driver_->sockets_;
193   }
194 
SetDevice(const VirtualDeviceRefPtr & device)195   void SetDevice(const VirtualDeviceRefPtr& device) {
196     driver_->device_ = device;
197   }
198 
SetService(const VPNServiceRefPtr & service)199   void SetService(const VPNServiceRefPtr& service) {
200     driver_->service_ = service;
201   }
202 
GetService()203   VPNServiceRefPtr GetService() {
204     return driver_->service_;
205   }
206 
OnConnectionDisconnected()207   void OnConnectionDisconnected() {
208     driver_->OnConnectionDisconnected();
209   }
210 
OnConnectTimeout()211   void OnConnectTimeout() {
212     driver_->OnConnectTimeout();
213   }
214 
StartConnectTimeout(int timeout_seconds)215   void StartConnectTimeout(int timeout_seconds) {
216     driver_->StartConnectTimeout(timeout_seconds);
217   }
218 
IsConnectTimeoutStarted()219   bool IsConnectTimeoutStarted() {
220     return driver_->IsConnectTimeoutStarted();
221   }
222 
GetDefaultConnectTimeoutSeconds()223   static int GetDefaultConnectTimeoutSeconds() {
224     return OpenVPNDriver::kDefaultConnectTimeoutSeconds;
225   }
226 
GetReconnectOfflineTimeoutSeconds()227   static int GetReconnectOfflineTimeoutSeconds() {
228     return OpenVPNDriver::kReconnectOfflineTimeoutSeconds;
229   }
230 
GetReconnectTLSErrorTimeoutSeconds()231   static int GetReconnectTLSErrorTimeoutSeconds() {
232     return OpenVPNDriver::kReconnectTLSErrorTimeoutSeconds;
233   }
234 
GetReconnectTimeoutSeconds(OpenVPNDriver::ReconnectReason reason)235   static int GetReconnectTimeoutSeconds(OpenVPNDriver::ReconnectReason reason) {
236     return OpenVPNDriver::GetReconnectTimeoutSeconds(reason);
237   }
238 
SetClientState(const string & state)239   void SetClientState(const string& state) {
240     management_server_->state_ = state;
241   }
242 
243   // Used to assert that a flag appears in the options.
244   void ExpectInFlags(const vector<vector<string>>& options, const string& flag);
245   void ExpectInFlags(const vector<vector<string>>& options, const string& flag,
246                      const string& value);
247   void ExpectInFlags(const vector<vector<string>>& options,
248                      const vector<string>& arguments);
249   void ExpectNotInFlags(const vector<vector<string>>& options,
250                         const string& flag);
251 
252   void SetupLSBRelease();
253 
254   // Inherited from RPCTaskDelegate.
255   virtual void GetLogin(string* user, string* password);
256   virtual void Notify(const string& reason, const map<string, string>& dict);
257 
258   NiceMockControl control_;
259   NiceMock<MockDeviceInfo> device_info_;
260   MockEventDispatcher dispatcher_;
261   MockMetrics metrics_;
262   MockProcessManager process_manager_;
263   MockManager manager_;
264   OpenVPNDriver* driver_;  // Owned by |service_|.
265   scoped_refptr<MockVPNService> service_;
266   scoped_refptr<MockVirtualDevice> device_;
267   MockCertificateFile* certificate_file_;  // Owned by |driver_|.
268   MockCertificateFile* extra_certificates_file_;  // Owned by |driver_|.
269   base::ScopedTempDir temporary_directory_;
270 
271   // Owned by |driver_|.
272   NiceMock<MockOpenVPNManagementServer>* management_server_;
273 
274   FilePath lsb_release_file_;
275 };
276 
277 const char OpenVPNDriverTest::kOption[] = "openvpn-option";
278 const char OpenVPNDriverTest::kProperty[] = "OpenVPN.SomeProperty";
279 const char OpenVPNDriverTest::kValue[] = "some-property-value";
280 const char OpenVPNDriverTest::kOption2[] = "openvpn-option2";
281 const char OpenVPNDriverTest::kProperty2[] = "OpenVPN.SomeProperty2";
282 const char OpenVPNDriverTest::kValue2[] = "some-property-value2";
283 const char OpenVPNDriverTest::kGateway1[] = "10.242.2.13";
284 const char OpenVPNDriverTest::kNetmask1[] = "255.255.255.255";
285 const char OpenVPNDriverTest::kNetwork1[] = "10.242.2.1";
286 const char OpenVPNDriverTest::kGateway2[] = "10.242.2.14";
287 const char OpenVPNDriverTest::kNetmask2[] = "255.255.0.0";
288 const char OpenVPNDriverTest::kNetwork2[] = "192.168.0.0";
289 const char OpenVPNDriverTest::kInterfaceName[] = "tun0";
290 const int OpenVPNDriverTest::kInterfaceIndex = 123;
291 const char OpenVPNDriverTest::kOpenVPNConfigDirectory[] = "openvpn";
292 
GetLogin(string *,string *)293 void OpenVPNDriverTest::GetLogin(string* /*user*/, string* /*password*/) {}
294 
Notify(const string &,const map<string,string> &)295 void OpenVPNDriverTest::Notify(const string& /*reason*/,
296                                const map<string, string>& /*dict*/) {}
297 
ExpectInFlags(const vector<vector<string>> & options,const string & flag)298 void OpenVPNDriverTest::ExpectInFlags(const vector<vector<string>>& options,
299                                       const string& flag) {
300   ExpectInFlags(options, vector<string> { flag });
301 }
302 
ExpectInFlags(const vector<vector<string>> & options,const string & flag,const string & value)303 void OpenVPNDriverTest::ExpectInFlags(const vector<vector<string>>& options,
304                                       const string& flag,
305                                       const string& value) {
306   ExpectInFlags(options, vector<string> { flag, value });
307 }
308 
ExpectInFlags(const vector<vector<string>> & options,const vector<string> & arguments)309 void OpenVPNDriverTest::ExpectInFlags(const vector<vector<string>>& options,
310                                       const vector<string>& arguments) {
311   EXPECT_TRUE(std::find(options.begin(), options.end(), arguments) !=
312               options.end());
313 }
314 
ExpectNotInFlags(const vector<vector<string>> & options,const string & flag)315 void OpenVPNDriverTest::ExpectNotInFlags(const vector<vector<string>>& options,
316                                          const string& flag) {
317   for (const auto& option : options) {
318     EXPECT_NE(flag, option[0]);
319   }
320 }
321 
SetupLSBRelease()322 void OpenVPNDriverTest::SetupLSBRelease() {
323   static const char kLSBReleaseContents[] =
324       "\n"
325       "=\n"
326       "foo=\n"
327       "=bar\n"
328       "zoo==\n"
329       "CHROMEOS_RELEASE_BOARD=x86-alex\n"
330       "CHROMEOS_RELEASE_NAME=Chromium OS\n"
331       "CHROMEOS_RELEASE_VERSION=2202.0\n";
332   EXPECT_TRUE(base::CreateTemporaryFile(&lsb_release_file_));
333   EXPECT_EQ(arraysize(kLSBReleaseContents),
334             base::WriteFile(lsb_release_file_,
335                             kLSBReleaseContents,
336                             arraysize(kLSBReleaseContents)));
337   EXPECT_EQ(OpenVPNDriver::kLSBReleaseFile, driver_->lsb_release_file_.value());
338   driver_->lsb_release_file_ = lsb_release_file_;
339 }
340 
TEST_F(OpenVPNDriverTest,Connect)341 TEST_F(OpenVPNDriverTest, Connect) {
342   EXPECT_CALL(*service_, SetState(Service::kStateConfiguring));
343   const string interface = kInterfaceName;
344   EXPECT_CALL(device_info_, CreateTunnelInterface(_))
345       .WillOnce(DoAll(SetArgumentPointee<0>(interface), Return(true)));
346   Error error;
347   driver_->Connect(service_, &error);
348   EXPECT_TRUE(error.IsSuccess());
349   EXPECT_EQ(kInterfaceName, driver_->tunnel_interface_);
350   EXPECT_TRUE(driver_->IsConnectTimeoutStarted());
351 }
352 
TEST_F(OpenVPNDriverTest,ConnectTunnelFailure)353 TEST_F(OpenVPNDriverTest, ConnectTunnelFailure) {
354   EXPECT_CALL(*service_, SetState(Service::kStateConfiguring));
355   EXPECT_CALL(device_info_, CreateTunnelInterface(_)).WillOnce(Return(false));
356   EXPECT_CALL(*service_, SetFailure(Service::kFailureInternal));
357   Error error;
358   driver_->Connect(service_, &error);
359   EXPECT_EQ(Error::kInternalError, error.type());
360   EXPECT_TRUE(driver_->tunnel_interface_.empty());
361   EXPECT_FALSE(driver_->IsConnectTimeoutStarted());
362 }
363 
364 namespace {
365 MATCHER_P(IsIPAddress, address, "") {
366   IPAddress ip_address(IPAddress::kFamilyIPv4);
367   EXPECT_TRUE(ip_address.SetAddressFromString(address));
368   return ip_address.Equals(arg);
369 }
370 }  // namespace
371 
TEST_F(OpenVPNDriverTest,Notify)372 TEST_F(OpenVPNDriverTest, Notify) {
373   map<string, string> config;
374   driver_->service_ = service_;
375   driver_->device_ = device_;
376   StartConnectTimeout(0);
377   EXPECT_CALL(*device_,
378               UpdateIPConfig(Field(&IPConfig::Properties::address, "")));
379   driver_->Notify("up", config);
380   EXPECT_FALSE(driver_->IsConnectTimeoutStarted());
381   EXPECT_TRUE(GetSelectedService().get() == service_.get());
382 
383   // Tests that existing properties are reused if no new ones provided.
384   driver_->ip_properties_.address = "1.2.3.4";
385   EXPECT_CALL(*device_,
386               UpdateIPConfig(Field(&IPConfig::Properties::address, "1.2.3.4")));
387   driver_->Notify("up", config);
388 }
389 
TEST_P(OpenVPNDriverTest,NotifyUMA)390 TEST_P(OpenVPNDriverTest, NotifyUMA) {
391   map<string, string> config;
392   driver_->service_ = service_;
393   driver_->device_ = device_;
394 
395   // Check that UMA metrics are emitted on Notify.
396   EXPECT_CALL(*device_, UpdateIPConfig(_));
397   EXPECT_CALL(metrics_, SendEnumToUMA(
398       Metrics::kMetricVpnDriver,
399       Metrics::kVpnDriverOpenVpn,
400       Metrics::kMetricVpnDriverMax));
401   EXPECT_CALL(metrics_, SendEnumToUMA(
402       Metrics::kMetricVpnRemoteAuthenticationType,
403       GetParam().remote_authentication_type,
404       Metrics::kVpnRemoteAuthenticationTypeMax));
405   for (const auto& authentication_type : GetParam().user_authentication_types) {
406     EXPECT_CALL(metrics_, SendEnumToUMA(
407         Metrics::kMetricVpnUserAuthenticationType,
408         authentication_type,
409         Metrics::kVpnUserAuthenticationTypeMax));
410   }
411 
412   Error unused_error;
413   PropertyStore store;
414   driver_->InitPropertyStore(&store);
415   if (!GetParam().ca_cert.empty()) {
416     store.SetStringsProperty(kOpenVPNCaCertPemProperty,
417                              vector<string>{ GetParam().ca_cert },
418                              &unused_error);
419   }
420   if (!GetParam().client_cert.empty()) {
421     store.SetStringProperty(kOpenVPNClientCertIdProperty,
422                             GetParam().client_cert,
423                             &unused_error);
424   }
425   if (!GetParam().user.empty()) {
426     store.SetStringProperty(kOpenVPNUserProperty, GetParam().user,
427                             &unused_error);
428   }
429   if (!GetParam().otp.empty()) {
430     store.SetStringProperty(kOpenVPNOTPProperty, GetParam().otp, &unused_error);
431   }
432   if (!GetParam().token.empty()) {
433     store.SetStringProperty(kOpenVPNTokenProperty, GetParam().token,
434                             &unused_error);
435   }
436   driver_->Notify("up", config);
437   Mock::VerifyAndClearExpectations(&metrics_);
438 }
439 
440 INSTANTIATE_TEST_CASE_P(
441     OpenVPNDriverAuthenticationTypes,
442     OpenVPNDriverTest,
443     ::testing::Values(
444       AuthenticationExpectations(
445           "", "", "", "", "",
446           Metrics::kVpnRemoteAuthenticationTypeOpenVpnDefault,
447           vector<Metrics::VpnUserAuthenticationType> {
448               Metrics::kVpnUserAuthenticationTypeOpenVpnNone }),
449       AuthenticationExpectations(
450           "", "client_cert", "", "", "",
451           Metrics::kVpnRemoteAuthenticationTypeOpenVpnDefault,
452           vector<Metrics::VpnUserAuthenticationType> {
453               Metrics::kVpnUserAuthenticationTypeOpenVpnCertificate }),
454       AuthenticationExpectations(
455           "", "client_cert", "user", "", "",
456           Metrics::kVpnRemoteAuthenticationTypeOpenVpnDefault,
457           vector<Metrics::VpnUserAuthenticationType> {
458               Metrics::kVpnUserAuthenticationTypeOpenVpnCertificate,
459               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePassword }),
460       AuthenticationExpectations(
461           "", "", "user", "", "",
462           Metrics::kVpnRemoteAuthenticationTypeOpenVpnDefault,
463           vector<Metrics::VpnUserAuthenticationType> {
464               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePassword }),
465       AuthenticationExpectations(
466           "", "client_cert", "user", "otp", "",
467           Metrics::kVpnRemoteAuthenticationTypeOpenVpnDefault,
468           vector<Metrics::VpnUserAuthenticationType> {
469               Metrics::kVpnUserAuthenticationTypeOpenVpnCertificate,
470               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePassword,
471               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePasswordOtp }),
472       AuthenticationExpectations(
473           "", "client_cert", "user", "otp", "token",
474           Metrics::kVpnRemoteAuthenticationTypeOpenVpnDefault,
475           vector<Metrics::VpnUserAuthenticationType> {
476               Metrics::kVpnUserAuthenticationTypeOpenVpnCertificate,
477               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePassword,
478               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePasswordOtp,
479               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernameToken }),
480       AuthenticationExpectations(
481           "ca_cert", "client_cert", "user", "otp", "token",
482           Metrics::kVpnRemoteAuthenticationTypeOpenVpnCertificate,
483           vector<Metrics::VpnUserAuthenticationType> {
484               Metrics::kVpnUserAuthenticationTypeOpenVpnCertificate,
485               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePassword,
486               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernamePasswordOtp,
487               Metrics::kVpnUserAuthenticationTypeOpenVpnUsernameToken })));
488 
TEST_F(OpenVPNDriverTest,NotifyFail)489 TEST_F(OpenVPNDriverTest, NotifyFail) {
490   map<string, string> dict;
491   driver_->device_ = device_;
492   StartConnectTimeout(0);
493   EXPECT_CALL(*device_, DropConnection());
494   driver_->Notify("fail", dict);
495   EXPECT_TRUE(driver_->IsConnectTimeoutStarted());
496 }
497 
TEST_F(OpenVPNDriverTest,GetRouteOptionEntry)498 TEST_F(OpenVPNDriverTest, GetRouteOptionEntry) {
499   OpenVPNDriver::RouteOptions routes;
500   EXPECT_EQ(nullptr, OpenVPNDriver::GetRouteOptionEntry("foo", "bar", &routes));
501   EXPECT_TRUE(routes.empty());
502   EXPECT_EQ(nullptr, OpenVPNDriver::GetRouteOptionEntry("foo", "foo", &routes));
503   EXPECT_TRUE(routes.empty());
504   EXPECT_EQ(nullptr,
505             OpenVPNDriver::GetRouteOptionEntry("foo", "fooz", &routes));
506   EXPECT_TRUE(routes.empty());
507   IPConfig::Route* route =
508       OpenVPNDriver::GetRouteOptionEntry("foo", "foo12", &routes);
509   EXPECT_EQ(1, routes.size());
510   EXPECT_EQ(route, &routes[12]);
511   route = OpenVPNDriver::GetRouteOptionEntry("foo", "foo13", &routes);
512   EXPECT_EQ(2, routes.size());
513   EXPECT_EQ(route, &routes[13]);
514 }
515 
TEST_F(OpenVPNDriverTest,ParseRouteOption)516 TEST_F(OpenVPNDriverTest, ParseRouteOption) {
517   OpenVPNDriver::RouteOptions routes;
518   OpenVPNDriver::ParseRouteOption("foo", "bar", &routes);
519   EXPECT_TRUE(routes.empty());
520   OpenVPNDriver::ParseRouteOption("gateway_2", kGateway2, &routes);
521   OpenVPNDriver::ParseRouteOption("netmask_2", kNetmask2, &routes);
522   OpenVPNDriver::ParseRouteOption("network_2", kNetwork2, &routes);
523   EXPECT_EQ(1, routes.size());
524   OpenVPNDriver::ParseRouteOption("gateway_1", kGateway1, &routes);
525   OpenVPNDriver::ParseRouteOption("netmask_1", kNetmask1, &routes);
526   OpenVPNDriver::ParseRouteOption("network_1", kNetwork1, &routes);
527   EXPECT_EQ(2, routes.size());
528   EXPECT_EQ(kGateway1, routes[1].gateway);
529   EXPECT_EQ(kNetmask1, routes[1].netmask);
530   EXPECT_EQ(kNetwork1, routes[1].host);
531   EXPECT_EQ(kGateway2, routes[2].gateway);
532   EXPECT_EQ(kNetmask2, routes[2].netmask);
533   EXPECT_EQ(kNetwork2, routes[2].host);
534 }
535 
TEST_F(OpenVPNDriverTest,SetRoutes)536 TEST_F(OpenVPNDriverTest, SetRoutes) {
537   OpenVPNDriver::RouteOptions routes;
538   routes[1].gateway = "1.2.3.4";
539   routes[1].host = "1.2.3.4";
540   routes[2].host = "2.3.4.5";
541   routes[2].netmask = "255.0.0.0";
542   routes[3].netmask = "255.0.0.0";
543   routes[3].gateway = "1.2.3.5";
544   routes[5].host = kNetwork2;
545   routes[5].netmask = kNetmask2;
546   routes[5].gateway = kGateway2;
547   routes[4].host = kNetwork1;
548   routes[4].netmask = kNetmask1;
549   routes[4].gateway = kGateway1;
550   IPConfig::Properties props;
551   OpenVPNDriver::SetRoutes(routes, &props);
552   ASSERT_EQ(2, props.routes.size());
553   EXPECT_EQ(kGateway1, props.routes[0].gateway);
554   EXPECT_EQ(kNetmask1, props.routes[0].netmask);
555   EXPECT_EQ(kNetwork1, props.routes[0].host);
556   EXPECT_EQ(kGateway2, props.routes[1].gateway);
557   EXPECT_EQ(kNetmask2, props.routes[1].netmask);
558   EXPECT_EQ(kNetwork2, props.routes[1].host);
559 
560   // Tests that the routes are not reset if no new routes are supplied.
561   OpenVPNDriver::SetRoutes(OpenVPNDriver::RouteOptions(), &props);
562   EXPECT_EQ(2, props.routes.size());
563 }
564 
TEST_F(OpenVPNDriverTest,SplitPortFromHost)565 TEST_F(OpenVPNDriverTest, SplitPortFromHost) {
566   string name, port;
567   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("", nullptr, nullptr));
568   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("", &name, &port));
569   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("v.com", &name, &port));
570   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("v.com:", &name, &port));
571   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost(":1234", &name, &port));
572   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("v.com:f:1234", &name, &port));
573   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("v.com:x", &name, &port));
574   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("v.com:-1", &name, &port));
575   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("v.com:+1", &name, &port));
576   EXPECT_FALSE(OpenVPNDriver::SplitPortFromHost("v.com:65536", &name, &port));
577   EXPECT_TRUE(OpenVPNDriver::SplitPortFromHost("v.com:0", &name, &port));
578   EXPECT_EQ("v.com", name);
579   EXPECT_EQ("0", port);
580   EXPECT_TRUE(OpenVPNDriver::SplitPortFromHost("w.com:65535", &name, &port));
581   EXPECT_EQ("w.com", name);
582   EXPECT_EQ("65535", port);
583   EXPECT_TRUE(OpenVPNDriver::SplitPortFromHost("x.com:12345", &name, &port));
584   EXPECT_EQ("x.com", name);
585   EXPECT_EQ("12345", port);
586 }
587 
TEST_F(OpenVPNDriverTest,ParseForeignOption)588 TEST_F(OpenVPNDriverTest, ParseForeignOption) {
589   vector<string> domain_search;
590   vector<string> dns_servers;
591   IPConfig::Properties props;
592   OpenVPNDriver::ParseForeignOption("", &domain_search, &dns_servers);
593   OpenVPNDriver::ParseForeignOption(
594       "dhcp-option DOMAIN", &domain_search, &dns_servers);
595   OpenVPNDriver::ParseForeignOption(
596       "dhcp-option DOMAIN zzz.com foo", &domain_search, &dns_servers);
597   OpenVPNDriver::ParseForeignOption(
598       "dhcp-Option DOmAIN xyz.com", &domain_search, &dns_servers);
599   ASSERT_EQ(1, domain_search.size());
600   EXPECT_EQ("xyz.com", domain_search[0]);
601   OpenVPNDriver::ParseForeignOption(
602       "dhcp-option DnS 1.2.3.4", &domain_search, &dns_servers);
603   ASSERT_EQ(1, dns_servers.size());
604   EXPECT_EQ("1.2.3.4", dns_servers[0]);
605 }
606 
TEST_F(OpenVPNDriverTest,ParseForeignOptions)607 TEST_F(OpenVPNDriverTest, ParseForeignOptions) {
608   // This also tests that std::map is a sorted container.
609   map<int, string> options;
610   options[5] = "dhcp-option DOMAIN five.com";
611   options[2] = "dhcp-option DOMAIN two.com";
612   options[8] = "dhcp-option DOMAIN eight.com";
613   options[7] = "dhcp-option DOMAIN seven.com";
614   options[4] = "dhcp-option DOMAIN four.com";
615   options[10] = "dhcp-option dns 1.2.3.4";
616   IPConfig::Properties props;
617   OpenVPNDriver::ParseForeignOptions(options, &props);
618   ASSERT_EQ(5, props.domain_search.size());
619   EXPECT_EQ("two.com", props.domain_search[0]);
620   EXPECT_EQ("four.com", props.domain_search[1]);
621   EXPECT_EQ("five.com", props.domain_search[2]);
622   EXPECT_EQ("seven.com", props.domain_search[3]);
623   EXPECT_EQ("eight.com", props.domain_search[4]);
624   ASSERT_EQ(1, props.dns_servers.size());
625   EXPECT_EQ("1.2.3.4", props.dns_servers[0]);
626 
627   // Test that the DNS properties are not updated if no new DNS properties are
628   // supplied.
629   OpenVPNDriver::ParseForeignOptions(map<int, string>(), &props);
630   EXPECT_EQ(5, props.domain_search.size());
631   ASSERT_EQ(1, props.dns_servers.size());
632 }
633 
TEST_F(OpenVPNDriverTest,ParseIPConfiguration)634 TEST_F(OpenVPNDriverTest, ParseIPConfiguration) {
635   map<string, string> config;
636   IPConfig::Properties props;
637 
638   driver_->ParseIPConfiguration(config, &props);
639   EXPECT_EQ(IPAddress::kFamilyIPv4, props.address_family);
640   EXPECT_EQ(32, props.subnet_prefix);
641 
642   props.subnet_prefix = 18;
643   driver_->ParseIPConfiguration(config, &props);
644   EXPECT_EQ(18, props.subnet_prefix);
645 
646   // An "ifconfig_remote" parameter that looks like a netmask should be
647   // applied to the subnet prefix instead of to the peer address.
648   config["ifconfig_remotE"] = "255.255.0.0";
649   driver_->ParseIPConfiguration(config, &props);
650   EXPECT_EQ(16, props.subnet_prefix);
651   EXPECT_EQ("", props.peer_address);
652 
653   config["ifconfig_loCal"] = "4.5.6.7";
654   config["ifconfiG_broadcast"] = "1.2.255.255";
655   config["ifconFig_netmAsk"] = "255.255.255.0";
656   config["ifconfig_remotE"] = "33.44.55.66";
657   config["route_vpN_gateway"] = "192.168.1.1";
658   config["trusted_ip"] = "99.88.77.66";
659   config["tun_mtu"] = "1000";
660   config["foreign_option_2"] = "dhcp-option DNS 4.4.4.4";
661   config["foreign_option_1"] = "dhcp-option DNS 1.1.1.1";
662   config["foreign_option_3"] = "dhcp-option DNS 2.2.2.2";
663   config["route_network_2"] = kNetwork2;
664   config["route_network_1"] = kNetwork1;
665   config["route_netmask_2"] = kNetmask2;
666   config["route_netmask_1"] = kNetmask1;
667   config["route_gateway_2"] = kGateway2;
668   config["route_gateway_1"] = kGateway1;
669   config["foo"] = "bar";
670   driver_->ParseIPConfiguration(config, &props);
671   EXPECT_EQ(IPAddress::kFamilyIPv4, props.address_family);
672   EXPECT_EQ("4.5.6.7", props.address);
673   EXPECT_EQ("1.2.255.255", props.broadcast_address);
674   EXPECT_EQ(24, props.subnet_prefix);
675   EXPECT_EQ("33.44.55.66", props.peer_address);
676   EXPECT_EQ("192.168.1.1", props.gateway);
677   EXPECT_EQ("99.88.77.66/32", props.exclusion_list[0]);
678   EXPECT_EQ(1, props.exclusion_list.size());
679   EXPECT_EQ(1000, props.mtu);
680   ASSERT_EQ(3, props.dns_servers.size());
681   EXPECT_EQ("1.1.1.1", props.dns_servers[0]);
682   EXPECT_EQ("4.4.4.4", props.dns_servers[1]);
683   EXPECT_EQ("2.2.2.2", props.dns_servers[2]);
684   ASSERT_EQ(2, props.routes.size());
685   EXPECT_EQ(kGateway1, props.routes[0].gateway);
686   EXPECT_EQ(kNetmask1, props.routes[0].netmask);
687   EXPECT_EQ(kNetwork1, props.routes[0].host);
688   EXPECT_EQ(kGateway2, props.routes[1].gateway);
689   EXPECT_EQ(kNetmask2, props.routes[1].netmask);
690   EXPECT_EQ(kNetwork2, props.routes[1].host);
691   EXPECT_FALSE(props.blackhole_ipv6);
692 
693   // If the driver is configured to ignore the gateway provided, it will
694   // not set the "gateway" property for the properties, however the
695   // explicitly supplied routes should still be set.
696   SetArg(kOpenVPNIgnoreDefaultRouteProperty, "some value");
697   IPConfig::Properties props_without_gateway;
698   driver_->ParseIPConfiguration(config, &props_without_gateway);
699   EXPECT_EQ(kGateway1, props_without_gateway.routes[0].gateway);
700   EXPECT_EQ("", props_without_gateway.gateway);
701 
702   // A pushed redirect flag should override the IgnoreDefaultRoute property.
703   config["redirect_gateway"] = "def1";
704   IPConfig::Properties props_with_override;
705   driver_->ParseIPConfiguration(config, &props_with_override);
706   EXPECT_EQ("192.168.1.1", props_with_override.gateway);
707 }
708 
TEST_F(OpenVPNDriverTest,InitOptionsNoHost)709 TEST_F(OpenVPNDriverTest, InitOptionsNoHost) {
710   Error error;
711   vector<vector<string>> options;
712   driver_->InitOptions(&options, &error);
713   EXPECT_EQ(Error::kInvalidArguments, error.type());
714   EXPECT_TRUE(options.empty());
715 }
716 
TEST_F(OpenVPNDriverTest,InitOptions)717 TEST_F(OpenVPNDriverTest, InitOptions) {
718   static const char kHost[] = "192.168.2.254";
719   static const char kTLSAuthContents[] = "SOME-RANDOM-CONTENTS\n";
720   static const char kID[] = "TestPKCS11ID";
721   static const char kKU0[] = "00";
722   static const char kKU1[] = "01";
723   FilePath empty_cert;
724   SetArg(kProviderHostProperty, kHost);
725   SetArg(kOpenVPNTLSAuthContentsProperty, kTLSAuthContents);
726   SetArg(kOpenVPNClientCertIdProperty, kID);
727   SetArg(kOpenVPNRemoteCertKUProperty, string(kKU0) + " " + string(kKU1));
728   driver_->rpc_task_.reset(new RPCTask(&control_, this));
729   driver_->tunnel_interface_ = kInterfaceName;
730   EXPECT_CALL(*management_server_, Start(_, _, _)).WillOnce(Return(true));
731   EXPECT_CALL(manager_, IsConnected()).WillOnce(Return(false));
732 
733   Error error;
734   vector<vector<string>> options;
735   driver_->InitOptions(&options, &error);
736   EXPECT_TRUE(error.IsSuccess());
737   EXPECT_EQ(vector<string> { "client" }, options[0]);
738   ExpectInFlags(options, "remote", kHost);
739   ExpectInFlags(options, vector<string> { "setenv", kRPCTaskPathVariable,
740                                           RPCTaskMockAdaptor::kRpcId });
741   ExpectInFlags(options, "dev", kInterfaceName);
742   ExpectInFlags(options, "group", "openvpn");
743   EXPECT_EQ(kInterfaceName, driver_->tunnel_interface_);
744   ASSERT_FALSE(driver_->tls_auth_file_.empty());
745   ExpectInFlags(options, "tls-auth", driver_->tls_auth_file_.value());
746   string contents;
747   EXPECT_TRUE(base::ReadFileToString(driver_->tls_auth_file_, &contents));
748   EXPECT_EQ(kTLSAuthContents, contents);
749   ExpectInFlags(options, "pkcs11-id", kID);
750   ExpectInFlags(options, "ca", OpenVPNDriver::kDefaultCACertificates);
751   ExpectInFlags(options, "syslog");
752   ExpectNotInFlags(options, "auth-user-pass");
753   ExpectInFlags(options, vector<string> { "remote-cert-ku", kKU0, kKU1 });
754 }
755 
TEST_F(OpenVPNDriverTest,InitOptionsHostWithPort)756 TEST_F(OpenVPNDriverTest, InitOptionsHostWithPort) {
757   SetArg(kProviderHostProperty, "v.com:1234");
758   driver_->rpc_task_.reset(new RPCTask(&control_, this));
759   driver_->tunnel_interface_ = kInterfaceName;
760   EXPECT_CALL(*management_server_, Start(_, _, _)).WillOnce(Return(true));
761   EXPECT_CALL(manager_, IsConnected()).WillOnce(Return(false));
762 
763   Error error;
764   vector<vector<string>> options;
765   driver_->InitOptions(&options, &error);
766   EXPECT_TRUE(error.IsSuccess());
767   ExpectInFlags(options, vector<string> { "remote", "v.com", "1234" });
768 }
769 
TEST_F(OpenVPNDriverTest,InitCAOptions)770 TEST_F(OpenVPNDriverTest, InitCAOptions) {
771   static const char kHost[] = "192.168.2.254";
772   static const char kCaCert[] = "foo";
773   static const char kCaCertNSS[] = "{1234}";
774 
775   Error error;
776   vector<vector<string>> options;
777   EXPECT_TRUE(driver_->InitCAOptions(&options, &error));
778   EXPECT_TRUE(error.IsSuccess());
779   ExpectInFlags(options, "ca", OpenVPNDriver::kDefaultCACertificates);
780 
781   options.clear();
782   SetArg(kOpenVPNCaCertProperty, kCaCert);
783   EXPECT_TRUE(driver_->InitCAOptions(&options, &error));
784   ExpectInFlags(options, "ca", kCaCert);
785   EXPECT_TRUE(error.IsSuccess());
786 
787   // We should ignore the CaCertNSS property.
788   SetArg(kOpenVPNCaCertNSSProperty, kCaCertNSS);
789   EXPECT_TRUE(driver_->InitCAOptions(&options, &error));
790   ExpectInFlags(options, "ca", kCaCert);
791   EXPECT_TRUE(error.IsSuccess());
792 
793   SetArg(kOpenVPNCaCertProperty, "");
794   SetArg(kProviderHostProperty, kHost);
795   FilePath empty_cert;
796   error.Reset();
797   EXPECT_TRUE(driver_->InitCAOptions(&options, &error));
798   ExpectInFlags(options, "ca", OpenVPNDriver::kDefaultCACertificates);
799   EXPECT_TRUE(error.IsSuccess());
800 
801   SetArg(kOpenVPNCaCertProperty, kCaCert);
802   const vector<string> kCaCertPEM{ "---PEM CONTENTS---" };
803   SetArgArray(kOpenVPNCaCertPemProperty, kCaCertPEM);
804   EXPECT_FALSE(driver_->InitCAOptions(&options, &error));
805   EXPECT_EQ(Error::kInvalidArguments, error.type());
806   EXPECT_EQ("Can't specify more than one of CACert and CACertPEM.",
807             error.message());
808 
809   options.clear();
810   SetArg(kOpenVPNCaCertProperty, "");
811   SetArg(kProviderHostProperty, "");
812   static const char kPEMCertfile[] = "/tmp/pem-cert";
813   FilePath pem_cert(kPEMCertfile);
814   EXPECT_CALL(*certificate_file_, CreatePEMFromStrings(kCaCertPEM))
815       .WillOnce(Return(empty_cert))
816       .WillOnce(Return(pem_cert));
817 
818   error.Reset();
819   EXPECT_FALSE(driver_->InitCAOptions(&options, &error));
820   EXPECT_EQ(Error::kInvalidArguments, error.type());
821   EXPECT_EQ("Unable to extract PEM CA certificates.", error.message());
822 
823   error.Reset();
824   options.clear();
825   EXPECT_TRUE(driver_->InitCAOptions(&options, &error));
826   ExpectInFlags(options, "ca", kPEMCertfile);
827   EXPECT_TRUE(error.IsSuccess());
828 }
829 
TEST_F(OpenVPNDriverTest,InitCertificateVerifyOptions)830 TEST_F(OpenVPNDriverTest, InitCertificateVerifyOptions) {
831   {
832     Error error;
833     vector<vector<string>> options;
834     // No options supplied.
835     driver_->InitCertificateVerifyOptions(&options);
836     EXPECT_TRUE(options.empty());
837   }
838   const char kName[] = "x509-name";
839   {
840     Error error;
841     vector<vector<string>> options;
842     // With Name property alone, we should have the 1-parameter version of the
843     // "x509-verify-name" parameter provided.
844     SetArg(kOpenVPNVerifyX509NameProperty, kName);
845     driver_->InitCertificateVerifyOptions(&options);
846     ExpectInFlags(options, "verify-x509-name", kName);
847   }
848   const char kType[] = "x509-type";
849   {
850     Error error;
851     vector<vector<string>> options;
852     // With both Name property and Type property set, we should have the
853     // 2-parameter version of the "x509-verify-name" parameter provided.
854     SetArg(kOpenVPNVerifyX509TypeProperty, kType);
855     driver_->InitCertificateVerifyOptions(&options);
856     ExpectInFlags(options, vector<string> { "verify-x509-name", kName, kType });
857   }
858   {
859     Error error;
860     vector<vector<string>> options;
861     // We should ignore the Type parameter if no Name parameter is specified.
862     SetArg(kOpenVPNVerifyX509NameProperty, "");
863     driver_->InitCertificateVerifyOptions(&options);
864     EXPECT_TRUE(options.empty());
865   }
866 }
867 
TEST_F(OpenVPNDriverTest,InitClientAuthOptions)868 TEST_F(OpenVPNDriverTest, InitClientAuthOptions) {
869   static const char kTestValue[] = "foo";
870   vector<vector<string>> options;
871 
872   // No key or cert, assume user/password authentication.
873   driver_->InitClientAuthOptions(&options);
874   ExpectInFlags(options, "auth-user-pass");
875   ExpectNotInFlags(options, "key");
876   ExpectNotInFlags(options, "cert");
877 
878   // Cert available, no user/password.
879   options.clear();
880   SetArg(kOpenVPNCertProperty, kTestValue);
881   driver_->InitClientAuthOptions(&options);
882   ExpectNotInFlags(options, "auth-user-pass");
883   ExpectNotInFlags(options, "key");
884   ExpectInFlags(options, "cert", kTestValue);
885 
886   // Key available, no user/password.
887   options.clear();
888   SetArg(kOpenVPNKeyProperty, kTestValue);
889   driver_->InitClientAuthOptions(&options);
890   ExpectNotInFlags(options, "auth-user-pass");
891   ExpectInFlags(options, "key", kTestValue);
892 
893   // Key available, AuthUserPass set.
894   options.clear();
895   SetArg(kOpenVPNAuthUserPassProperty, kTestValue);
896   driver_->InitClientAuthOptions(&options);
897   ExpectInFlags(options, "auth-user-pass");
898   ExpectInFlags(options, "key", kTestValue);
899 
900   // Key available, User set.
901   options.clear();
902   RemoveStringArg(kOpenVPNAuthUserPassProperty);
903   SetArg(kOpenVPNUserProperty, "user");
904   driver_->InitClientAuthOptions(&options);
905   ExpectInFlags(options, "auth-user-pass");
906   ExpectInFlags(options, "key", kTestValue);
907 
908   // Empty PKCS11 certificate id, no user/password/cert.
909   options.clear();
910   RemoveStringArg(kOpenVPNKeyProperty);
911   RemoveStringArg(kOpenVPNCertProperty);
912   RemoveStringArg(kOpenVPNUserProperty);
913   SetArg(kOpenVPNClientCertIdProperty, "");
914   driver_->InitClientAuthOptions(&options);
915   ExpectInFlags(options, "auth-user-pass");
916   ExpectNotInFlags(options, "key");
917   ExpectNotInFlags(options, "cert");
918   ExpectNotInFlags(options, "pkcs11-id");
919 
920   // Non-empty PKCS11 certificate id, no user/password/cert.
921   options.clear();
922   SetArg(kOpenVPNClientCertIdProperty, kTestValue);
923   driver_->InitClientAuthOptions(&options);
924   ExpectNotInFlags(options, "auth-user-pass");
925   ExpectNotInFlags(options, "key");
926   ExpectNotInFlags(options, "cert");
927   // The "--pkcs11-id" option is added in InitPKCS11Options(), not here.
928   ExpectNotInFlags(options, "pkcs11-id");
929 
930   // PKCS11 certificate id available, AuthUserPass set.
931   options.clear();
932   SetArg(kOpenVPNAuthUserPassProperty, kTestValue);
933   driver_->InitClientAuthOptions(&options);
934   ExpectInFlags(options, "auth-user-pass");
935   ExpectNotInFlags(options, "key");
936   ExpectNotInFlags(options, "cert");
937 
938   // PKCS11 certificate id available, User set.
939   options.clear();
940   RemoveStringArg(kOpenVPNAuthUserPassProperty);
941   SetArg(kOpenVPNUserProperty, "user");
942   driver_->InitClientAuthOptions(&options);
943   ExpectInFlags(options, "auth-user-pass");
944   ExpectNotInFlags(options, "key");
945   ExpectNotInFlags(options, "cert");
946 }
947 
TEST_F(OpenVPNDriverTest,InitExtraCertOptions)948 TEST_F(OpenVPNDriverTest, InitExtraCertOptions) {
949   {
950     Error error;
951     vector<vector<string>> options;
952     // No ExtraCertOptions supplied.
953     EXPECT_TRUE(driver_->InitExtraCertOptions(&options, &error));
954     EXPECT_TRUE(error.IsSuccess());
955     EXPECT_TRUE(options.empty());
956   }
957   {
958     Error error;
959     vector<vector<string>> options;
960     SetArgArray(kOpenVPNExtraCertPemProperty, vector<string>());
961     // Empty ExtraCertOptions supplied.
962     EXPECT_TRUE(driver_->InitExtraCertOptions(&options, &error));
963     EXPECT_TRUE(error.IsSuccess());
964     EXPECT_TRUE(options.empty());
965   }
966   const vector<string> kExtraCerts{ "---PEM CONTENTS---" };
967   SetArgArray(kOpenVPNExtraCertPemProperty, kExtraCerts);
968   static const char kPEMCertfile[] = "/tmp/pem-cert";
969   FilePath pem_cert(kPEMCertfile);
970   EXPECT_CALL(*extra_certificates_file_, CreatePEMFromStrings(kExtraCerts))
971       .WillOnce(Return(FilePath()))
972       .WillOnce(Return(pem_cert));
973   // CreatePemFromStrings fails.
974   {
975     Error error;
976     vector<vector<string>> options;
977     EXPECT_FALSE(driver_->InitExtraCertOptions(&options, &error));
978     EXPECT_EQ(Error::kInvalidArguments, error.type());
979     EXPECT_TRUE(options.empty());
980   }
981   // CreatePemFromStrings succeeds.
982   {
983     Error error;
984     vector<vector<string>> options;
985     EXPECT_TRUE(driver_->InitExtraCertOptions(&options, &error));
986     EXPECT_TRUE(error.IsSuccess());
987     ExpectInFlags(options, "extra-certs", kPEMCertfile);
988   }
989 }
990 
TEST_F(OpenVPNDriverTest,InitPKCS11Options)991 TEST_F(OpenVPNDriverTest, InitPKCS11Options) {
992   vector<vector<string>> options;
993   driver_->InitPKCS11Options(&options);
994   EXPECT_TRUE(options.empty());
995 
996   static const char kID[] = "TestPKCS11ID";
997   SetArg(kOpenVPNClientCertIdProperty, kID);
998   driver_->InitPKCS11Options(&options);
999   ExpectInFlags(options, "pkcs11-id", kID);
1000   ExpectInFlags(options, "pkcs11-providers", "libchaps.so");
1001 
1002   static const char kProvider[] = "libpkcs11.so";
1003   SetArg(kOpenVPNProviderProperty, kProvider);
1004   options.clear();
1005   driver_->InitPKCS11Options(&options);
1006   ExpectInFlags(options, "pkcs11-id", kID);
1007   ExpectInFlags(options, "pkcs11-providers", kProvider);
1008 }
1009 
TEST_F(OpenVPNDriverTest,InitManagementChannelOptionsServerFail)1010 TEST_F(OpenVPNDriverTest, InitManagementChannelOptionsServerFail) {
1011   vector<vector<string>> options;
1012   EXPECT_CALL(*management_server_, Start(&dispatcher_, GetSockets(), &options))
1013       .WillOnce(Return(false));
1014   Error error;
1015   EXPECT_FALSE(InitManagementChannelOptions(&options, &error));
1016   EXPECT_EQ(Error::kInternalError, error.type());
1017   EXPECT_EQ("Unable to setup management channel.", error.message());
1018 }
1019 
TEST_F(OpenVPNDriverTest,InitManagementChannelOptionsOnline)1020 TEST_F(OpenVPNDriverTest, InitManagementChannelOptionsOnline) {
1021   vector<vector<string>> options;
1022   EXPECT_CALL(*management_server_, Start(&dispatcher_, GetSockets(), &options))
1023       .WillOnce(Return(true));
1024   EXPECT_CALL(manager_, IsConnected()).WillOnce(Return(true));
1025   EXPECT_CALL(*management_server_, ReleaseHold());
1026   Error error;
1027   EXPECT_TRUE(InitManagementChannelOptions(&options, &error));
1028   EXPECT_TRUE(error.IsSuccess());
1029 }
1030 
TEST_F(OpenVPNDriverTest,InitManagementChannelOptionsOffline)1031 TEST_F(OpenVPNDriverTest, InitManagementChannelOptionsOffline) {
1032   vector<vector<string>> options;
1033   EXPECT_CALL(*management_server_, Start(&dispatcher_, GetSockets(), &options))
1034       .WillOnce(Return(true));
1035   EXPECT_CALL(manager_, IsConnected()).WillOnce(Return(false));
1036   EXPECT_CALL(*management_server_, ReleaseHold()).Times(0);
1037   Error error;
1038   EXPECT_TRUE(InitManagementChannelOptions(&options, &error));
1039   EXPECT_TRUE(error.IsSuccess());
1040 }
1041 
TEST_F(OpenVPNDriverTest,InitLoggingOptions)1042 TEST_F(OpenVPNDriverTest, InitLoggingOptions) {
1043   vector<vector<string>> options;
1044   bool vpn_logging = SLOG_IS_ON(VPN, 0);
1045   ScopeLogger::GetInstance()->EnableScopesByName("-vpn");
1046   driver_->InitLoggingOptions(&options);
1047   ASSERT_EQ(1, options.size());
1048   EXPECT_EQ(vector<string> { "syslog" }, options[0]);
1049   ScopeLogger::GetInstance()->EnableScopesByName("+vpn");
1050   options.clear();
1051   driver_->InitLoggingOptions(&options);
1052   ExpectInFlags(options, "verb", "3");
1053   ScopeLogger::GetInstance()->EnableScopesByName("-vpn");
1054   SetArg("OpenVPN.Verb", "2");
1055   options.clear();
1056   driver_->InitLoggingOptions(&options);
1057   ExpectInFlags(options, "verb", "2");
1058   ScopeLogger::GetInstance()->EnableScopesByName("+vpn");
1059   SetArg("OpenVPN.Verb", "1");
1060   options.clear();
1061   driver_->InitLoggingOptions(&options);
1062   ExpectInFlags(options, "verb", "1");
1063   if (!vpn_logging) {
1064     ScopeLogger::GetInstance()->EnableScopesByName("-vpn");
1065   }
1066 }
1067 
TEST_F(OpenVPNDriverTest,AppendValueOption)1068 TEST_F(OpenVPNDriverTest, AppendValueOption) {
1069   vector<vector<string>> options;
1070   EXPECT_FALSE(
1071       driver_->AppendValueOption("OpenVPN.UnknownProperty", kOption, &options));
1072   EXPECT_TRUE(options.empty());
1073 
1074   SetArg(kProperty, "");
1075   EXPECT_FALSE(driver_->AppendValueOption(kProperty, kOption, &options));
1076   EXPECT_TRUE(options.empty());
1077 
1078   SetArg(kProperty, kValue);
1079   SetArg(kProperty2, kValue2);
1080   EXPECT_TRUE(driver_->AppendValueOption(kProperty, kOption, &options));
1081   EXPECT_TRUE(driver_->AppendValueOption(kProperty2, kOption2, &options));
1082   EXPECT_EQ(2, options.size());
1083   vector<string> expected_value { kOption, kValue };
1084   EXPECT_EQ(expected_value, options[0]);
1085   vector<string> expected_value2 { kOption2, kValue2 };
1086   EXPECT_EQ(expected_value2, options[1]);
1087 }
1088 
TEST_F(OpenVPNDriverTest,AppendDelimitedValueOption)1089 TEST_F(OpenVPNDriverTest, AppendDelimitedValueOption) {
1090   vector<vector<string>> options;
1091   EXPECT_FALSE(
1092       driver_->AppendDelimitedValueOption(
1093           "OpenVPN.UnknownProperty", kOption, ' ', &options));
1094   EXPECT_TRUE(options.empty());
1095 
1096   SetArg(kProperty, "");
1097   EXPECT_FALSE(
1098       driver_->AppendDelimitedValueOption(kProperty, kOption, ' ', &options));
1099   EXPECT_TRUE(options.empty());
1100 
1101   string kConcatenatedValues(string(kValue) + " " + string(kValue2));
1102   SetArg(kProperty, kConcatenatedValues);
1103   SetArg(kProperty2, kConcatenatedValues);
1104   EXPECT_TRUE(driver_->AppendDelimitedValueOption(
1105       kProperty, kOption, ':', &options));
1106   EXPECT_TRUE(driver_->AppendDelimitedValueOption(
1107       kProperty2, kOption2, ' ', &options));
1108   EXPECT_EQ(2, options.size());
1109   vector<string> expected_value { kOption, kConcatenatedValues };
1110   EXPECT_EQ(expected_value, options[0]);
1111   vector<string> expected_value2 { kOption2, kValue, kValue2 };
1112   EXPECT_EQ(expected_value2, options[1]);
1113 }
1114 
TEST_F(OpenVPNDriverTest,AppendFlag)1115 TEST_F(OpenVPNDriverTest, AppendFlag) {
1116   vector<vector<string>> options;
1117   EXPECT_FALSE(
1118       driver_->AppendFlag("OpenVPN.UnknownProperty", kOption, &options));
1119   EXPECT_TRUE(options.empty());
1120 
1121   SetArg(kProperty, "");
1122   SetArg(kProperty2, kValue2);
1123   EXPECT_TRUE(driver_->AppendFlag(kProperty, kOption, &options));
1124   EXPECT_TRUE(driver_->AppendFlag(kProperty2, kOption2, &options));
1125   EXPECT_EQ(2, options.size());
1126   EXPECT_EQ(vector<string> { kOption }, options[0]);
1127   EXPECT_EQ(vector<string> { kOption2 }, options[1]);
1128 }
1129 
TEST_F(OpenVPNDriverTest,ClaimInterface)1130 TEST_F(OpenVPNDriverTest, ClaimInterface) {
1131   driver_->tunnel_interface_ = kInterfaceName;
1132   EXPECT_FALSE(driver_->ClaimInterface(string(kInterfaceName) + "XXX",
1133                                        kInterfaceIndex));
1134   EXPECT_FALSE(driver_->device_);
1135 
1136   static const char kHost[] = "192.168.2.254";
1137   SetArg(kProviderHostProperty, kHost);
1138   EXPECT_CALL(*management_server_, Start(_, _, _)).WillOnce(Return(true));
1139   EXPECT_CALL(manager_, IsConnected()).WillOnce(Return(false));
1140   EXPECT_CALL(
1141       process_manager_,
1142       StartProcess(_, _, _, _, false /* Don't exit with parent */, _))
1143       .WillOnce(Return(true));
1144   const int kServiceCallbackTag = 1;
1145   EXPECT_EQ(0, driver_->default_service_callback_tag_);
1146   EXPECT_CALL(manager_, RegisterDefaultServiceCallback(_))
1147       .WillOnce(Return(kServiceCallbackTag));
1148   EXPECT_TRUE(driver_->ClaimInterface(kInterfaceName, kInterfaceIndex));
1149   ASSERT_TRUE(driver_->device_);
1150   EXPECT_EQ(kInterfaceIndex, driver_->device_->interface_index());
1151   EXPECT_EQ(kServiceCallbackTag, driver_->default_service_callback_tag_);
1152 }
1153 
TEST_F(OpenVPNDriverTest,IdleService)1154 TEST_F(OpenVPNDriverTest, IdleService) {
1155   SetService(service_);
1156   EXPECT_CALL(*service_, SetState(Service::kStateIdle));
1157   driver_->IdleService();
1158 }
1159 
TEST_F(OpenVPNDriverTest,FailService)1160 TEST_F(OpenVPNDriverTest, FailService) {
1161   static const char kErrorDetails[] = "Bad password.";
1162   SetService(service_);
1163   EXPECT_CALL(*service_, SetFailure(Service::kFailureConnect));
1164   driver_->FailService(Service::kFailureConnect, kErrorDetails);
1165   EXPECT_EQ(kErrorDetails, service_->error_details());
1166 }
1167 
TEST_F(OpenVPNDriverTest,Cleanup)1168 TEST_F(OpenVPNDriverTest, Cleanup) {
1169   // Ensure no crash.
1170   driver_->Cleanup(Service::kStateIdle,
1171                    Service::kFailureUnknown,
1172                    Service::kErrorDetailsNone);
1173 
1174   const int kPID = 123456;
1175   const int kServiceCallbackTag = 5;
1176   static const char kErrorDetails[] = "Certificate revoked.";
1177   driver_->default_service_callback_tag_ = kServiceCallbackTag;
1178   driver_->pid_ = kPID;
1179   driver_->rpc_task_.reset(new RPCTask(&control_, this));
1180   driver_->tunnel_interface_ = kInterfaceName;
1181   driver_->device_ = device_;
1182   driver_->service_ = service_;
1183   driver_->ip_properties_.address = "1.2.3.4";
1184   StartConnectTimeout(0);
1185   FilePath tls_auth_file;
1186   EXPECT_TRUE(base::CreateTemporaryFile(&tls_auth_file));
1187   EXPECT_FALSE(tls_auth_file.empty());
1188   EXPECT_TRUE(base::PathExists(tls_auth_file));
1189   driver_->tls_auth_file_ = tls_auth_file;
1190   // Stop will be called twice -- once by Cleanup and once by the destructor.
1191   EXPECT_CALL(*management_server_, Stop()).Times(2);
1192   // UpdateExitCallback will be called twice -- once to ignore exit,
1193   // and once to re-enabling monitoring of exit.
1194   EXPECT_CALL(process_manager_, UpdateExitCallback(kPID, _)).Times(2);
1195   EXPECT_CALL(manager_, DeregisterDefaultServiceCallback(kServiceCallbackTag));
1196   EXPECT_CALL(process_manager_, StopProcess(kPID));
1197   EXPECT_CALL(device_info_, DeleteInterface(_)).Times(0);
1198   EXPECT_CALL(*device_, DropConnection());
1199   EXPECT_CALL(*device_, SetEnabled(false));
1200   EXPECT_CALL(*service_, SetFailure(Service::kFailureInternal));
1201   driver_->Cleanup(
1202       Service::kStateFailure, Service::kFailureInternal,  kErrorDetails);
1203   EXPECT_EQ(0, driver_->default_service_callback_tag_);
1204   EXPECT_EQ(0, driver_->pid_);
1205   EXPECT_FALSE(driver_->rpc_task_.get());
1206   EXPECT_TRUE(driver_->tunnel_interface_.empty());
1207   EXPECT_FALSE(driver_->device_);
1208   EXPECT_FALSE(driver_->service_);
1209   EXPECT_EQ(kErrorDetails, service_->error_details());
1210   EXPECT_FALSE(base::PathExists(tls_auth_file));
1211   EXPECT_TRUE(driver_->tls_auth_file_.empty());
1212   EXPECT_TRUE(driver_->ip_properties_.address.empty());
1213   EXPECT_FALSE(driver_->IsConnectTimeoutStarted());
1214 }
1215 
TEST_F(OpenVPNDriverTest,SpawnOpenVPN)1216 TEST_F(OpenVPNDriverTest, SpawnOpenVPN) {
1217   SetupLSBRelease();
1218 
1219   EXPECT_FALSE(driver_->SpawnOpenVPN());
1220 
1221   static const char kHost[] = "192.168.2.254";
1222   SetArg(kProviderHostProperty, kHost);
1223   driver_->tunnel_interface_ = "tun0";
1224   driver_->rpc_task_.reset(new RPCTask(&control_, this));
1225   EXPECT_CALL(*management_server_, Start(_, _, _))
1226       .Times(2)
1227       .WillRepeatedly(Return(true));
1228   EXPECT_CALL(manager_, IsConnected()).Times(2).WillRepeatedly(Return(false));
1229 
1230   const int kPID = 234678;
1231   const map<string, string> expected_env{
1232     {"IV_PLAT", "Chromium OS"},
1233     {"IV_PLAT_REL", "2202.0"}};
1234   EXPECT_CALL(process_manager_, StartProcess(_, _, _, expected_env, _, _))
1235       .WillOnce(Return(-1))
1236       .WillOnce(Return(kPID));
1237   EXPECT_FALSE(driver_->SpawnOpenVPN());
1238   EXPECT_TRUE(driver_->SpawnOpenVPN());
1239   EXPECT_EQ(kPID, driver_->pid_);
1240 }
1241 
TEST_F(OpenVPNDriverTest,OnOpenVPNDied)1242 TEST_F(OpenVPNDriverTest, OnOpenVPNDied) {
1243   const int kPID = 99999;
1244   driver_->device_ = device_;
1245   driver_->pid_ = kPID;
1246   EXPECT_CALL(*device_, DropConnection());
1247   EXPECT_CALL(*device_, SetEnabled(false));
1248   EXPECT_CALL(process_manager_, StopProcess(_)).Times(0);
1249   EXPECT_CALL(device_info_, DeleteInterface(kInterfaceIndex));
1250   driver_->OnOpenVPNDied(2);
1251   EXPECT_EQ(0, driver_->pid_);
1252 }
1253 
TEST_F(OpenVPNDriverTest,Disconnect)1254 TEST_F(OpenVPNDriverTest, Disconnect) {
1255   driver_->device_ = device_;
1256   driver_->service_ = service_;
1257   EXPECT_CALL(*device_, DropConnection());
1258   EXPECT_CALL(*device_, SetEnabled(false));
1259   EXPECT_CALL(device_info_, DeleteInterface(kInterfaceIndex));
1260   EXPECT_CALL(*service_, SetState(Service::kStateIdle));
1261   driver_->Disconnect();
1262   EXPECT_FALSE(driver_->device_);
1263   EXPECT_FALSE(driver_->service_);
1264 }
1265 
TEST_F(OpenVPNDriverTest,OnConnectionDisconnected)1266 TEST_F(OpenVPNDriverTest, OnConnectionDisconnected) {
1267   EXPECT_CALL(*management_server_, Restart());
1268   SetDevice(device_);
1269   SetService(service_);
1270   EXPECT_CALL(*device_, DropConnection());
1271   EXPECT_CALL(*service_, SetState(Service::kStateAssociating));
1272   OnConnectionDisconnected();
1273   EXPECT_TRUE(IsConnectTimeoutStarted());
1274 }
1275 
TEST_F(OpenVPNDriverTest,OnConnectTimeout)1276 TEST_F(OpenVPNDriverTest, OnConnectTimeout) {
1277   StartConnectTimeout(0);
1278   SetService(service_);
1279   EXPECT_CALL(*service_, SetFailure(Service::kFailureConnect));
1280   OnConnectTimeout();
1281   EXPECT_FALSE(GetService());
1282   EXPECT_FALSE(IsConnectTimeoutStarted());
1283 }
1284 
TEST_F(OpenVPNDriverTest,OnConnectTimeoutResolve)1285 TEST_F(OpenVPNDriverTest, OnConnectTimeoutResolve) {
1286   StartConnectTimeout(0);
1287   SetService(service_);
1288   SetClientState(OpenVPNManagementServer::kStateResolve);
1289   EXPECT_CALL(*service_, SetFailure(Service::kFailureDNSLookup));
1290   OnConnectTimeout();
1291   EXPECT_FALSE(GetService());
1292   EXPECT_FALSE(IsConnectTimeoutStarted());
1293 }
1294 
TEST_F(OpenVPNDriverTest,OnReconnectingUnknown)1295 TEST_F(OpenVPNDriverTest, OnReconnectingUnknown) {
1296   EXPECT_FALSE(IsConnectTimeoutStarted());
1297   EXPECT_CALL(dispatcher_,
1298               PostDelayedTask(_, GetDefaultConnectTimeoutSeconds() * 1000));
1299   SetDevice(device_);
1300   SetService(service_);
1301   EXPECT_CALL(*device_, DropConnection());
1302   EXPECT_CALL(*service_, SetState(Service::kStateAssociating));
1303   driver_->OnReconnecting(OpenVPNDriver::kReconnectReasonUnknown);
1304   EXPECT_TRUE(IsConnectTimeoutStarted());
1305 }
1306 
TEST_F(OpenVPNDriverTest,OnReconnectingTLSError)1307 TEST_F(OpenVPNDriverTest, OnReconnectingTLSError) {
1308   EXPECT_CALL(dispatcher_,
1309               PostDelayedTask(_, GetReconnectOfflineTimeoutSeconds() * 1000));
1310   EXPECT_CALL(dispatcher_,
1311               PostDelayedTask(_, GetReconnectTLSErrorTimeoutSeconds() * 1000));
1312 
1313   driver_->OnReconnecting(OpenVPNDriver::kReconnectReasonOffline);
1314   EXPECT_TRUE(IsConnectTimeoutStarted());
1315 
1316   // The scheduled timeout should not be affected for unknown reason.
1317   driver_->OnReconnecting(OpenVPNDriver::kReconnectReasonUnknown);
1318   EXPECT_TRUE(IsConnectTimeoutStarted());
1319 
1320   // Reconnect on TLS error reschedules the timeout once.
1321   driver_->OnReconnecting(OpenVPNDriver::kReconnectReasonTLSError);
1322   EXPECT_TRUE(IsConnectTimeoutStarted());
1323   driver_->OnReconnecting(OpenVPNDriver::kReconnectReasonTLSError);
1324   EXPECT_TRUE(IsConnectTimeoutStarted());
1325 }
1326 
TEST_F(OpenVPNDriverTest,InitPropertyStore)1327 TEST_F(OpenVPNDriverTest, InitPropertyStore) {
1328   // Sanity test property store initialization.
1329   PropertyStore store;
1330   driver_->InitPropertyStore(&store);
1331   const string kUser = "joe";
1332   Error error;
1333   EXPECT_TRUE(store.SetStringProperty(kOpenVPNUserProperty, kUser, &error));
1334   EXPECT_TRUE(error.IsSuccess());
1335   EXPECT_EQ(kUser, GetArgs()->LookupString(kOpenVPNUserProperty, ""));
1336 }
1337 
TEST_F(OpenVPNDriverTest,PassphraseRequired)1338 TEST_F(OpenVPNDriverTest, PassphraseRequired) {
1339   PropertyStore store;
1340   driver_->InitPropertyStore(&store);
1341   KeyValueStore props = GetProviderProperties(store);
1342   EXPECT_TRUE(props.LookupBool(kPassphraseRequiredProperty, false));
1343 
1344   SetArg(kOpenVPNPasswordProperty, "random-password");
1345   props = GetProviderProperties(store);
1346   EXPECT_FALSE(props.LookupBool(kPassphraseRequiredProperty, true));
1347   // This parameter should be write-only.
1348   EXPECT_FALSE(props.ContainsString(kOpenVPNPasswordProperty));
1349 
1350   SetArg(kOpenVPNPasswordProperty, "");
1351   props = GetProviderProperties(store);
1352   EXPECT_TRUE(props.LookupBool(kPassphraseRequiredProperty, false));
1353 
1354   SetArg(kOpenVPNTokenProperty, "random-token");
1355   props = GetProviderProperties(store);
1356   EXPECT_FALSE(props.LookupBool(kPassphraseRequiredProperty, true));
1357   // This parameter should be write-only.
1358   EXPECT_FALSE(props.ContainsString(kOpenVPNTokenProperty));
1359 }
1360 
TEST_F(OpenVPNDriverTest,GetEnvironment)1361 TEST_F(OpenVPNDriverTest, GetEnvironment) {
1362   SetupLSBRelease();
1363   const map<string, string> expected{
1364     {"IV_PLAT", "Chromium OS"},
1365     {"IV_PLAT_REL", "2202.0"}};
1366   ASSERT_EQ(expected, driver_->GetEnvironment());
1367 
1368   EXPECT_EQ(0, base::WriteFile(lsb_release_file_, "", 0));
1369   EXPECT_EQ(0, driver_->GetEnvironment().size());
1370 }
1371 
TEST_F(OpenVPNDriverTest,OnOpenVPNExited)1372 TEST_F(OpenVPNDriverTest, OnOpenVPNExited) {
1373   const int kExitStatus = 1;
1374   std::unique_ptr<MockDeviceInfo> device_info(
1375       new MockDeviceInfo(&control_, &dispatcher_, &metrics_, &manager_));
1376   EXPECT_CALL(*device_info, DeleteInterface(kInterfaceIndex))
1377       .WillOnce(Return(true));
1378   WeakPtr<DeviceInfo> weak = device_info->AsWeakPtr();
1379   EXPECT_TRUE(weak);
1380   OpenVPNDriver::OnOpenVPNExited(weak, kInterfaceIndex, kExitStatus);
1381   device_info.reset();
1382   EXPECT_FALSE(weak);
1383   // Expect no crash.
1384   OpenVPNDriver::OnOpenVPNExited(weak, kInterfaceIndex, kExitStatus);
1385 }
1386 
TEST_F(OpenVPNDriverTest,OnDefaultServiceChanged)1387 TEST_F(OpenVPNDriverTest, OnDefaultServiceChanged) {
1388   driver_->service_ = service_;
1389 
1390   ServiceRefPtr null_service;
1391   EXPECT_CALL(*management_server_, Hold());
1392   driver_->OnDefaultServiceChanged(null_service);
1393 
1394   EXPECT_CALL(*management_server_, Hold());
1395   driver_->OnDefaultServiceChanged(service_);
1396 
1397   scoped_refptr<MockService> mock_service(
1398       new MockService(&control_, &dispatcher_, &metrics_, &manager_));
1399 
1400   EXPECT_CALL(*mock_service, IsConnected()).WillOnce(Return(false));
1401   EXPECT_CALL(*management_server_, Hold());
1402   driver_->OnDefaultServiceChanged(mock_service);
1403 
1404   EXPECT_CALL(*mock_service, IsConnected()).WillOnce(Return(true));
1405   EXPECT_CALL(*management_server_, ReleaseHold());
1406   driver_->OnDefaultServiceChanged(mock_service);
1407 }
1408 
TEST_F(OpenVPNDriverTest,GetReconnectTimeoutSeconds)1409 TEST_F(OpenVPNDriverTest, GetReconnectTimeoutSeconds) {
1410   EXPECT_EQ(GetDefaultConnectTimeoutSeconds(),
1411             GetReconnectTimeoutSeconds(OpenVPNDriver::kReconnectReasonUnknown));
1412   EXPECT_EQ(GetReconnectOfflineTimeoutSeconds(),
1413             GetReconnectTimeoutSeconds(OpenVPNDriver::kReconnectReasonOffline));
1414   EXPECT_EQ(GetReconnectTLSErrorTimeoutSeconds(),
1415             GetReconnectTimeoutSeconds(
1416                 OpenVPNDriver::kReconnectReasonTLSError));
1417 }
1418 
TEST_F(OpenVPNDriverTest,WriteConfigFile)1419 TEST_F(OpenVPNDriverTest, WriteConfigFile) {
1420   const char kOption0[] = "option0";
1421   const char kOption1[] = "option1";
1422   const char kOption1Argument0[] = "option1-argument0";
1423   const char kOption2[] = "option2";
1424   const char kOption2Argument0[] = "option2-argument0\n\t\"'\\";
1425   const char kOption2Argument0Transformed[] = "option2-argument0 \t\\\"'\\\\";
1426   const char kOption2Argument1[] = "option2-argument1 space";
1427   vector<vector<string>> options {
1428       { kOption0 },
1429       { kOption1, kOption1Argument0 },
1430       { kOption2, kOption2Argument0, kOption2Argument1 }
1431   };
1432   FilePath config_directory(
1433       temporary_directory_.path().Append(kOpenVPNConfigDirectory));
1434   FilePath config_file;
1435   EXPECT_FALSE(base::PathExists(config_directory));
1436   EXPECT_TRUE(driver_->WriteConfigFile(options, &config_file));
1437   EXPECT_TRUE(base::PathExists(config_directory));
1438   EXPECT_TRUE(base::PathExists(config_file));
1439   EXPECT_TRUE(config_directory.IsParent(config_file));
1440 
1441   string config_contents;
1442   EXPECT_TRUE(base::ReadFileToString(config_file, &config_contents));
1443   string expected_config_contents = base::StringPrintf(
1444       "%s\n%s %s\n%s \"%s\" \"%s\"\n",
1445       kOption0,
1446       kOption1, kOption1Argument0,
1447       kOption2, kOption2Argument0Transformed, kOption2Argument1);
1448   EXPECT_EQ(expected_config_contents, config_contents);
1449 }
1450 
1451 }  // namespace shill
1452