This file is indexed.

/usr/share/plinth/actions/openvpn is in plinth 0.24.0.

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

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
#!/usr/bin/python3
#
# This file is part of FreedomBox.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""
Configuration helper for OpenVPN server.
"""

import argparse
import os
import subprocess
import augeas

from plinth import action_utils

KEYS_DIRECTORY = '/etc/openvpn/freedombox-keys'

DH_KEY = '/etc/openvpn/freedombox-keys/dh4096.pem'

OLD_SERVER_CONFIGURATION_PATH = '/etc/openvpn/freedombox.conf'
SERVER_CONFIGURATION_PATH = '/etc/openvpn/server/freedombox.conf'

OLD_SERVICE_NAME = 'openvpn@freedombox'
SERVICE_NAME = 'openvpn-server@freedombox'

CA_CERTIFICATE_PATH = KEYS_DIRECTORY + '/ca.crt'
USER_CERTIFICATE_PATH = KEYS_DIRECTORY + '/{username}.crt'
USER_KEY_PATH = KEYS_DIRECTORY + '/{username}.key'
ATTR_FILE = KEYS_DIRECTORY + '/index.txt.attr'

SERVER_CONFIGURATION = '''
port 1194
proto udp
dev tun
ca /etc/openvpn/freedombox-keys/ca.crt
cert /etc/openvpn/freedombox-keys/server.crt
key /etc/openvpn/freedombox-keys/server.key
dh /etc/openvpn/freedombox-keys/dh4096.pem
server 10.91.0.0 255.255.255.0
keepalive 10 120
cipher AES-256-CBC
comp-lzo
verb 3
'''

CLIENT_CONFIGURATION = '''
client
remote {remote} 1194
proto udp
dev tun
nobind
remote-cert-tls server
cipher AES-256-CBC
comp-lzo
redirect-gateway
verb 3
<ca>
{ca}</ca>
<cert>
{cert}</cert>
<key>
{key}</key>'''

CERTIFICATE_CONFIGURATION = {
    'KEY_CONFIG': '/usr/share/easy-rsa/openssl-1.0.0.cnf',
    'KEY_DIR': KEYS_DIRECTORY,
    'OPENSSL': 'openssl',
    'KEY_SIZE': '4096',
    'CA_EXPIRE': '3650',
    'KEY_EXPIRE': '3650',
    'KEY_COUNTRY': 'US',
    'KEY_PROVINCE': 'NY',
    'KEY_CITY': 'New York',
    'KEY_ORG': 'FreedomBox',
    'KEY_EMAIL': 'me@freedombox',
    'KEY_OU': 'Home',
    'KEY_NAME': 'FreedomBox'
}

COMMON_ARGS = {'env': CERTIFICATE_CONFIGURATION, 'cwd': KEYS_DIRECTORY}


def parse_arguments():
    """Return parsed command line arguments as dictionary."""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')

    subparsers.add_parser('is-setup', help='Return whether setup is completed')
    subparsers.add_parser('setup', help='Setup OpenVPN server configuration')
    subparsers.add_parser(
        'upgrade',
        help='Upgrade OpenVPN server configuration from older configuration')

    get_profile = subparsers.add_parser(
        'get-profile', help='Return the OpenVPN profile of a user')
    get_profile.add_argument('username', help='User to get profile for')
    get_profile.add_argument('remote_server',
                             help='The server name for the user to connect')

    subparsers.required = True
    return parser.parse_args()


def subcommand_is_setup(_):
    """Return whether setup is complete."""
    print('true' if os.path.isfile(DH_KEY) else 'false')


def subcommand_setup(_):
    """Setup configuration, CA and certificates."""
    _create_server_config()
    _create_certificates()
    _setup_firewall()
    action_utils.service_enable(SERVICE_NAME)
    action_utils.service_restart(SERVICE_NAME)


def subcommand_upgrade(_):
    """Upgrade from an older version if configured.

    Otherwise do nothing.
    """
    if os.path.exists(OLD_SERVER_CONFIGURATION_PATH):
        os.rename(OLD_SERVER_CONFIGURATION_PATH, SERVER_CONFIGURATION_PATH)

    if action_utils.service_is_enabled(OLD_SERVICE_NAME):
        action_utils.service_disable(OLD_SERVICE_NAME)
        action_utils.service_enable(SERVICE_NAME)


def _create_server_config():
    """Write server configuration."""
    if os.path.exists(SERVER_CONFIGURATION_PATH):
        return

    with open(SERVER_CONFIGURATION_PATH, 'w') as file_handle:
        file_handle.write(SERVER_CONFIGURATION)


def _setup_firewall():
    """Add TUN device to internal zone in firewalld."""
    subprocess.call(
        ['firewall-cmd', '--zone', 'internal', '--add-interface', 'tun+'])
    subprocess.call([
        'firewall-cmd', '--permanent', '--zone', 'internal', '--add-interface',
        'tun+'
    ])


def _create_certificates():
    """Generate CA and server certificates."""
    try:
        os.mkdir(KEYS_DIRECTORY, 0o700)
    except FileExistsError:
        pass

    subprocess.check_call(['/usr/share/easy-rsa/clean-all'], **COMMON_ARGS)
    subprocess.check_call(['/usr/share/easy-rsa/pkitool', '--initca'],
                          **COMMON_ARGS)
    subprocess.check_call(
        ['/usr/share/easy-rsa/pkitool', '--server', 'server'], **COMMON_ARGS)
    subprocess.check_call(['/usr/share/easy-rsa/build-dh'], **COMMON_ARGS)


def subcommand_get_profile(arguments):
    """Return the profile for a user."""
    username = arguments.username
    remote_server = arguments.remote_server

    if username == 'ca' or username == 'server':
        raise Exception('Invalid username')

    user_certificate = USER_CERTIFICATE_PATH.format(username=username)
    user_key = USER_KEY_PATH.format(username=username)

    if not _is_non_empty_file(user_certificate) or \
       not _is_non_empty_file(user_key):
        set_unique_subject('no')  # Set unique subject in attribute file to no
        subprocess.check_call(['/usr/share/easy-rsa/pkitool', username],
                              **COMMON_ARGS)

    user_certificate_string = _read_file(user_certificate)
    user_key_string = _read_file(user_key)
    ca_string = _read_file(CA_CERTIFICATE_PATH)

    profile = CLIENT_CONFIGURATION.format(
        ca=ca_string, cert=user_certificate_string, key=user_key_string,
        remote=remote_server)

    print(profile)


def set_unique_subject(value):
    """ Sets the unique_subject value to a particular value"""
    aug = load_augeas()
    aug.set('/files' + ATTR_FILE + '/unique_subject', value)
    aug.save()


def _read_file(filename):
    """Return the entire contents of a file as string."""
    with open(filename, 'r') as file_handle:
        return ''.join(file_handle.readlines())


def _is_non_empty_file(filepath):
    """Return wheather a file exists and is not zero size."""
    return os.path.isfile(filepath) and os.path.getsize(filepath) > 0


def load_augeas():
    """Initialize Augeas."""
    aug = augeas.Augeas(
        flags=augeas.Augeas.NO_LOAD + augeas.Augeas.NO_MODL_AUTOLOAD)

    # shell-script config file lens
    aug.set('/augeas/load/Simplevars/lens', 'Simplevars.lns')
    aug.set('/augeas/load/Simplevars/incl[last() + 1]', ATTR_FILE)
    aug.load()
    return aug


def main():
    """Parse arguments and perform all duties."""
    arguments = parse_arguments()

    subcommand = arguments.subcommand.replace('-', '_')
    subcommand_method = globals()['subcommand_' + subcommand]
    subcommand_method(arguments)


if __name__ == '__main__':
    main()