This file is indexed.

/usr/share/perl5/EBox/OpenVPN/Client.pm is in zentyal-openvpn 2.3.10+quantal1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# Copyright (C) 2008-2012 eBox Technologies S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

package EBox::OpenVPN::Client;

# Description: Class for modelling each of the OpenVPN servers
use strict;
use warnings;

use base qw(EBox::OpenVPN::Daemon);

use EBox::Validate qw(checkPort checkAbsoluteFilePath checkHost);
use EBox::NetWrappers;
use EBox::Sudo;
use EBox::FileSystem;
use EBox::Gettext;
use EBox::OpenVPN::Client::ValidateCertificate;
use EBox::OpenVPN::Server::ClientBundleGenerator::EBoxToEBox;

use Error qw(:try);
use File::Temp;
use Params::Validate qw(validate_pos SCALAR);

sub new
{
    my ($class, $row) = @_;

    my $self = $class->SUPER::new($row);
    bless $self, $class;

    return $self;
}

sub type
{
    return 'client';
}

# Method: proto
#
#  Returns:
#    the protocol used by the server
#
sub proto
{
    my ($self) = @_;

    my $conf = $self->{row}->subModel('configuration');

    my $configRow = $conf->row();
    my $portAndProtocol =  $configRow->elementByName('serverPortAndProtocol');
    return $portAndProtocol->protocol();
}

sub localAddr
{
    my ($self) = @_;
    return $self->_configAttr('localAddr');
}

sub lport
{
    my ($self) = @_;
    return $self->_configAttr('lport');
}

sub routeUpCmd
{
    my ($self) = @_;
    return $self->_configAttr('routeUpCmd');
}

sub setRouteUpCmd
{
    my ($self, $cmd) = @_;
    my $conf = $self->{row}->subModel('configuration');
    my $configRow = $conf->row();
    $configRow->elementByName('routeUpCmd')->setValue($cmd);
    $configRow->store();
}

# Method: setLocalAddrAndPort
#
#    Set the local address and local port to bind for the VPN client
#
# Parameters:
#
#     newLocalAddr - String the new local IP address
#
#     newLocalPort - Int the new local port
#
sub setLocalAddrAndPort
{
    my ($self, $newLocalAddr, $newLocalPort) = @_;

    $newLocalAddr = undef unless ( $newLocalAddr );
    $newLocalPort = undef unless ( $newLocalPort );

    my $conf = $self->{row}->subModel('configuration');
    my $configRow = $conf->row();
    $configRow->elementByName('localAddr')->setValue($newLocalAddr);
    $configRow->elementByName('lport')->setValue($newLocalPort);
    $configRow->store();
}

sub _filePath
{
    my ($self, $name) = @_;

    my $conf = $self->{row}->subModel('configuration');
    my $configRow = $conf->row();
    my $fileField = $configRow->elementByName($name);
    return $fileField->path();
}

# Method: caCertificate
#
# Returns:
#  returns the path to the CA certificate
sub caCertificate
{
    my ($self) = @_;
    return $self->_filePath('caCertificate');
}

# Method: certificate
#
# Returns:
#  returns the path to the certificate
sub certificate
{
    my ($self) = @_;
    return $self->_filePath('certificate');
}

# Method: certificateKey
#
# Returns:
#  returns the path to the private key
sub certificateKey
{
    my ($self) = @_;
    return $self->_filePath('certificateKey');
}

# Method: privateDir
#
#  gets the private dir used by the client ot store his certificates
#   and keys if it does not exists it will be created
#
# Returns:
#  returns the client's protocol
sub privateDir
{
    my ($self) = @_;
    my $name = $self->name;
    return __PACKAGE__->privateDirForName($name);
}

sub privateDirForName
{
    my ($class, $name) = @_;

    my $openVPNConfDir = $class->_openvpnModule->confDir();
    my $dir =  $openVPNConfDir . "/$name.d";
    # For compability with older version
     if (not EBox::Sudo::fileTest('-d', $dir)) {
         if  ( EBox::Sudo::fileTest('-e', $dir) ) {
             throw EBox::Exceptions::Internal("$dir exists but is not a directory");
         }
         # create dir if it does not exist
         EBox::Sudo::root("mkdir --mode 0700 '$dir'");
     }
    # end compability  block

    return $dir;
}

sub createDirectories
{
    my ($self) = @_;

    my $dir = $self->privateDir();
    if (not EBox::Sudo::fileTest('-d', $dir)) {
        if  ( EBox::Sudo::fileTest('-e', $dir) ) {
            throw EBox::Exceptions::Internal(
                                          "$dir exists but is not a directory");
        }

        # create dir if it does not exist
        EBox::Sudo::root("mkdir --mode 0700 '$dir'");
    }
}

sub _setPrivateFile
{
    my ($self, $type, $path) = @_;

    if (not EBox::Sudo::fileTest('-r', $path)) {
        throw EBox::Exceptions::Internal('Cannot read private file source');
    }

    $self->createDirectories();
    my $privateDir = $self->privateDir();

    my $newPath = "$privateDir/$type";

    try {
        EBox::Sudo::root("cp '$path' '$newPath'");
        EBox::Sudo::root("chmod 0400 '$newPath'");
        EBox::Sudo::root("chown 0.0 '$newPath'");
    }
    otherwise {
        EBox::Sudo::root("rm -f '$newPath'");
    };

    $self->setConfString($type, $newPath);

}

# Method: internal
#
#   tell wether the client must been internal for users in the UI or nodaemon
#   is a internal daemon used and created by other EBox services
#
# Returns:
#  returns the daemon's internal state
sub internal
{
    my ($self) = @_;
    return $self->_rowAttr('internal');
}

# Method: daemonFiles
# Override <EBox::OpenVPN::Daemon::daemonFiles> method
sub daemonFiles
{
    my ($class, $name) = @_;

    my @files = $class->SUPER::daemonFiles($name);
    push @files, $class->privateDirForName($name);

    return @files;
}

sub confFileTemplate
{
    my ($self) = @_;
    return "openvpn/openvpn-client.conf.mas";
}

sub confFileParams
{
    my ($self) = @_;
    my @templateParams;

    push @templateParams, (dev => $self->iface());

    my @paramsNeeded = qw(name caCertificate certificate certificateKey
                          proto user group dh localAddr lport routeUpCmd);
    foreach my $param (@paramsNeeded) {
        my $accessor_r = $self->can($param);
        defined $accessor_r or die "Cannot found accessor for param $param";
        my $value = $accessor_r->($self);
        defined $value or next;
        push @templateParams, ($param => $value);
    }

    my $mssFix = EBox::Config::configkey('mss_fix');
    if ( $mssFix ) {
        push(@templateParams, ( mssFix => $mssFix) );
    }

    push @templateParams, (servers =>  $self->servers() );
    # We can only have proxy settings with TCP clients
    if ( $self->proto() eq 'tcp' ) {
        push(@templateParams, (proxySettings => $self->_proxySettings() ));
    }

    return \@templateParams;
}

# Method: limitRespawn
#
# Overrides:
#
#     <EBox::OpenVPN::Daemon>
#
sub limitRespawn
{
    my ($self) = @_;

    if ( $self->internal() ) {
        return 1;
    } else {
        return 0;
    }
}

sub checkServer
{
    my ($self, $server) = @_;

    if (($server eq '127.0.0.1') or ($server eq 'localhost')) {
                throw EBox::Exceptions::External(
                    __x(
'VPN client should not be configured to connect to the address {addr} because is a address of the localhost itsef',
                       addr => $server
                       )
                   );

    }

    my $net = EBox::Global->modInstance('network');

    my @ifaces = @{$net->ifaces()};
    foreach my $ifc (@ifaces) {
        my $addrs = $net->ifaceAddresses($ifc);
        foreach my $addr_r (@{  $addrs}) {
            my $address = $addr_r->{address};
            if ($server eq $address) {
                throw EBox::Exceptions::External(
                    __x(
'VPN client should not be configured to connect to the address {addr} because is a address of a local network interface',
                       addr => $server
                       )
                   );
            }
        }

    }
}



# Method: servers
#
#   Get the servers to which the client will try to connect
#
# Returns:
#
#  a reference to the list of server. Each item in the list of
#  servers is a reference to a list which contains the IP address
#  and port of one server
sub servers
{
    my ($self) = @_;

    my $config = $self->{row}->subModel('configuration');

    my $server = $config->server();

    my $portAndProtocol =  $config->row()->elementByName('serverPortAndProtocol');
    my $port = $portAndProtocol->port();

    my @servers = ([ $server => $port ]);
    return \@servers;
}

# Method: _proxySettings
#
#    Get the HTTP proxy settings defined in Network module to reach
#    OpenVPN servers
#
# Returns:
#
#    Hash ref - containing the following keys
#
#         - server - the HTTP proxy server
#         - port   - the HTTP proxy port
#
#         - authFile - if authenticated, then a file path which
#                      includes the username and password in two lines
#
#    [] - if there is no proxy settings
#
sub _proxySettings
{
    my ($self) = @_;

    my $retVal = [];

    my $net = EBox::Global->getInstance(1)->modInstance('network');
    my $settings = $net->proxySettings();

    if ( defined($settings) ) {
        $retVal = { server => $settings->{server},
                    port   => $settings->{port} };
        if ( exists $settings->{username} ) {
            # Create the auth file
            my $authFile = $self->privateDir() . '/proxy-auth';
            my $tmpFile  = new File::Temp();
            open(my $fh, '>', $tmpFile->filename());
            print $fh $settings->{username} . "\n";
            print $fh $settings->{password} . "\n";
            close($fh);
            EBox::Sudo::root("cp '" . $tmpFile->filename() . qq{' '$authFile'});
            $retVal->{authFile} = $authFile;
        }
    }
    return $retVal;
}

sub ripDaemon
{
    my ($self) = @_;

    # internal client don't need to push routes to the server
    (not $self->internal)
      or return undef;

    $self->isEnabled() or return undef;

    my $iface = $self->ifaceWithRipPasswd();
    return { iface => $iface, redistribute => 1 };
}

sub ifaceMethodChanged
{
    my ($self, $iface, $oldmethod, $newmethod) = @_;
    if ($newmethod eq 'nonset') {
        return 1 if $self->_availableIfaces() == 1;
    }

    return undef;
}

sub vifaceDelete
{
    my ($self, $iface, $viface) = @_;

    return 1 if $self->_availableIfaces() == 1;
    return undef;
}

sub freeIface
{
    my ($self, $iface) = @_;
    my $ifaces = $self->_availableIfaces();
    if ($ifaces == 1) {
        $self->{row}->elementByName('service')->setValue(0);
        $self->stop() if $self->isRunning();

        EBox::warn("OpenVPN client "
            . $self->name
            . " was deactivated because there is not any network interfaces available"
        );
    }
}

sub freeViface
{
    my ($self, $iface, $viface) = @_;
    $self->freeIface($viface);
}

sub changeIfaceExternalProperty # (iface, external)
{
    my ($self, $iface, $external) = @_;

   # no effect for openvpn clients. Except that the server may not be reacheable
   # anymore but we don't check
   # this in any moment..
    return;
}

sub staticIfaceAddressChanged
{
    my ($self, $iface, $oldaddr, $oldmask, $newaddr, $newmask) = @_;
    my @servers = @{ $self->servers() };
    foreach my $server (@servers) {
        my ($addr, $port) = @{ $server };
        defined $addr or
            next;
        if ($addr eq $newaddr) {
            # trouble !
            return 1;
        }
    }

    return undef;
}


sub _availableIfaces
{
    my ($self) = @_;

    my $network = EBox::Global->modInstance('network');
    my @ifaces = @{ $network->ExternalIfaces };

    # XXX it should care of internal ifaces only until we close #391
    push @ifaces, @{ $network->InternalIfaces };

    return scalar @ifaces;
}

sub summary
{
    my ($self) = @_;

    if ($self->internal) { # no summary for internal clients
        return ();
    }

    my @summary;
    push @summary, __x('Client {name}', name => $self->name);

    my $service = $self->isEnabled() ? __('Enabled') : __('Disabled');
    push @summary,__('Service'), $service;

    my $running = $self->isRunning() ? __('Running') : __('Stopped');
    push @summary,__('Daemon status'), $running;

    my $proto   = $self->proto();
    my @servers = @{  $self->servers  };

    # XXX only one server supported now!
    my ($addr, $port) = @{ $servers[0]  };
    my $server = "$addr $port/\U$proto";
    push @summary,__('Connection target'), $server;

    my $ifAddr = $self->ifaceAddress();
    if ($ifAddr) {
        push @summary, (__('VPN interface address'), $ifAddr);
    }else {
        push @summary, (__('VPN interface address'), __('No active'));
    }

    return @summary;
}

sub backupCertificates
{
    my ($self, $dir) = @_;


    my $d = "$dir/" . $self->name;
    EBox::FileSystem::makePrivateDir($d);

    my $dirEmpty = 0;
    foreach my $cert (qw(caCertificate certificate certificateKey)) {
        my $orig = $self->$cert();
        if (EBox::Sudo::fileTest('-r', $orig)) {
            my $dest = "$d/$cert";
            EBox::Sudo::root("cp '$orig' '$dest'");
        }
        else {
            # all certifcates or nothing bz validation issues between
            # certificates ...
            $dirEmpty = 1;
            last;
        }

    }

    if ($dirEmpty) {
        # we remove the directory as to signal that the client is uninitialized
        # (no certificates)
        EBox::Sudo::root("rm -rf '$d'");
        return;
    }

    EBox::Sudo::root("chown ebox.ebox $d/*");
}

sub restoreCertificates
{
    my ($self, $dir) = @_;
    $self->createDirectories();

    my $d = "$dir/" . $self->name;
    if (not -d $d) {

        # XXX we don't abort to mantain compability with previous bakcup and
        # because uninitialized clients don't save certificates
        EBox::warn(
               'No directory found with saved certificates for client '
              . $self->name
              .'. No certificates will be restores'

        );
        next;

    }

    # before copyng and overwritting files, check if all needed files are valid
    # why? if there is a error is a little less probable we left a
    # unusable state
    my @files = ("$d/caCertificate", "$d/certificate", "$d/certificateKey" );
    EBox::OpenVPN::Client::ValidateCertificate::check("$d/caCertificate",
                                          "$d/certificate","$d/certificateKey");

    # set the files from the backup in the client
    try {
        __PACKAGE__->setCertificatesFilesForName(
                                   $self->name(),
                                   caCertificate => "$d/caCertificate",
                                   certificate   => "$d/certificate",
                                   certificateKey => "$d/certificateKey");
    }
    otherwise {
        my $e = shift;
        EBox::error(  'Error restoring certifcates for client '
                    . $self->name
                    .'. Probably the certificates will be  inconsistents');
        $e->throw();
    };

}

# Method: setCertificatesFilesForName
#
#      Copy certificates and private key to the final destination
#
# Parameters:
#
#      name - String the client's name
#
#      pathByFile - Hash containing the certificate file paths with
#      the following keys:
#
#          caCertificate
#          certificate
#          certificateKey
#
# Returns:
#
#      hash ref - containing the new paths for certificates and key
#      with the same keys as parameter pathByFile
#
sub setCertificatesFilesForName
{
    my ($class, $name, %pathByFile) = @_;

    my %retValue = ();
    my $clientConfDir = $class->privateDirForName($name);
    my @files = qw(caCertificate certificate certificateKey );
    foreach my $f (@files) {

# the destination must be firstly the same as the value obtained with
# tmpPath in the EBox::Type::File to assure the checks and then the final destination
        my $tmpDest =  EBox::Config::tmp() . $f . '_path';
        EBox::Sudo::root("cp '" . $pathByFile{$f} . "' '$tmpDest'");

        my $finalDest = "$clientConfDir/$f";
        EBox::Sudo::root("cp '" . $pathByFile{$f} . "' '$finalDest'");
        EBox::Sudo::root("chmod 0400 '$finalDest'");
        $retValue{$f} = $finalDest;
    }

    return \%retValue;

}

sub usesPort
{
    my ($self, $proto, $port, $iface) = @_;

    my $ownProto = $self->proto;
    defined $ownProto
      or return undef; # uninitialized server
    if ($proto ne $ownProto) {
        return undef;
    }

    my $ownPort = $self->lport;
    defined $ownPort
      or return undef; #uninitialized server
    if ($port ne $ownPort) {
        return undef;
    }

    my $localAddr = $self->localAddr();
    if (defined $iface and $localAddr) {
        my @ifaceAddresses = EBox::NetWrappers::iface_addresses($iface);
        foreach my $ifAddr (@ifaceAddresses) {
            if ($ifAddr eq $localAddr) {
                # client listening in the given iface
                return 1;
            }
        }

        return 0; # not listening in the given iface
    } else {
        return 1;
    }
}

1;