summaryrefslogtreecommitdiff
path: root/src/conf-mode/vyos-config-ssh.py
blob: be7af64bef2ec72a01fe0f4c021113029253e66e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
#!/usr/bin/env python3
#
# Copyright (C) 2018 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later 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, see <http://www.gnu.org/licenses/>.
#
#

import sys
import os
import time

from vyos.config import Config
from vyos.util import ConfigError

config_file = r'/etc/ssh/sshd_config'

def get_config():
    ssh = {}
    conf = Config()
    conf.set_level('service ssh')
    if not conf.exists(''):
        return ssh

    if conf.exists('access-control allow'):
        ssh.setdefault('allowed-users', [])
        allow_user = []
        allow_user = conf.return_values('access-control allow user')
        for user in allow_user:
            ssh['allowed-users'].append(user)

        ssh.setdefault('allowed-groups', [])
        allow_group = []
        allow_group = conf.return_values('access-control allow group')
        for group in allow_group:
            ssh['allowed-groups'].append(group)

    if conf.exists('access-control deny'):
        ssh.setdefault('deny-users', [])
        deny_user = []
        deny_user = conf.return_values('access-control deny user')
        for user in deny_user:
            ssh['deny-users'].append(user)

        ssh.setdefault('deny-groups', [])
        deny_group = []
        deny_group = conf.return_values('access-control deny group')
        for group in deny_group:
            ssh['deny-groups'].append(group)

    if conf.exists('allow-root'):
        ssh.setdefault('allow-root', True)

    if conf.exists('ciphers'):
        ciphers = conf.return_value('ciphers')
        ssh.setdefault('ciphers', ciphers)

    if conf.exists('disable-host-validation'):
        ssh.setdefault('disable-host-validation', True)

    if conf.exists('disable-password-authentication'):
        ssh.setdefault('disable-password-authentication', True)

    if conf.exists('key-exchange'):
        kex = conf.return_value('key-exchange')
        ssh.setdefault('key-exchange', kex)

    if conf.exists('listen-address'):
        ssh.setdefault('listen-address', [])
        addresses = []
        addresses = conf.return_values('listen-address')
        for addr in addresses:
            ssh['listen-address'].append(addr)

    if conf.exists('loglevel'):
        level = conf.return_value('loglevel')
        ssh.setdefault('loglevel', level)

    if conf.exists('mac'):
        mac = conf.return_value('mac')
        ssh.setdefault('mac', mac)

    if conf.exists('port'):
        port = conf.return_value('port')
        ssh.setdefault('port', port)

    print(ssh)
    return ssh

def verify(ssh):
    return None

def generate(ssh):
    config_header = '### Autogenerated by vyos-config-ssh.py on {tm} ###\n'.format(tm=time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()))

    # write new configuration file
    f = open(config_file, 'w')
    f.write(config_header)
    f.write('\n')

    if 'port' in ssh.keys():
        f.write('Port {0}\n'.format(ssh['port']))
    else:
        f.write('Port 22\n')

    f.write('Protocol 2\n')
    f.write('HostKey /etc/ssh/ssh_host_rsa_key\n')
    f.write('HostKey /etc/ssh/ssh_host_dsa_key\n')
    f.write('HostKey /etc/ssh/ssh_host_ecdsa_key\n')
    f.write('HostKey /etc/ssh/ssh_host_ed25519_key\n')
    f.write('UsePrivilegeSeparation yes\n')
    f.write('\n')
    f.write('KeyRegenerationInterval 3600\n')
    f.write('ServerKeyBits 1024\n')
    f.write('\n')
    f.write('SyslogFacility AUTH\n')

    if 'loglevel' in ssh.keys():
        f.write('LogLevel {0}\n'.format(ssh['loglevel']))
    else:
        f.write('LogLevel INFO\n')

    f.write('\n')
    f.write('LoginGraceTime 120\n')

    if 'allow-root' in ssh.keys():
        f.write('PermitRootLogin yes\n')
    else:
        f.write('PermitRootLogin no\n')

    f.write('StrictModes yes\n')
    f.write('\n')
    f.write('RSAAuthentication yes\n')
    f.write('PubkeyAuthentication yes\n')
    f.write('\n')
    f.write('IgnoreRhosts yes\n')
    f.write('RhostsRSAAuthentication no\n')
    f.write('HostbasedAuthentication no\n')
    f.write('\n')
    f.write('PermitEmptyPasswords no\n')
    f.write('\n')
    f.write('ChallengeResponseAuthentication no\n')
    f.write('\n')

    if 'disable-password-authentication' in ssh.keys():
        f.write('PasswordAuthentication no\n')
    else:
        f.write('PasswordAuthentication yes\n')

    f.write('\n')
    f.write('X11Forwarding yes\n')
    f.write('X11DisplayOffset 10\n')
    f.write('PrintMotd no\n')
    f.write('PrintLastLog yes\n')
    f.write('TCPKeepAlive yes\n')
    f.write('\n')
    f.write('Banner /etc/issue.net\n')
    f.write('\n')
    f.write('Subsystem sftp /usr/lib/openssh/sftp-server\n')
    f.write('\n')
    f.write('UsePAM yes\n')
    f.write('HostKey /etc/ssh/ssh_host_key\n')

    if 'disable-host-validation' in ssh.keys():
        f.write('UseDNS no\n')
    else:
        f.write('UseDNS yes\n')

    if 'listen-address' in ssh.keys():
        for addr in ssh['listen-address']:
            f.write('ListenAddress {0}\n'.format(addr))

    if 'ciphers' in ssh.keys():
        f.write('Ciphers {0}\n'.format(ssh['ciphers']))

    if 'key-exchange' in ssh.keys():
        f.write('KexAlgorithms {0}\n'.format(ssh['key-exchange']))

    if 'mac' in ssh.keys():
        f.write('MACs {0}\n'.format(ssh['mac']))

    if 'allowed-users' in ssh.keys():
        print('AllowUsers {0}\n'.format(' '.join(str(usr) for usr in ssh['allowed-users'])))

    if 'allowed-groups' in ssh.keys():
        print('AllowGroups {0}\n'.format(' '.join(str(grp) for grp in ssh['allowed-groups'])))

    if 'deny-users' in ssh.keys():
        print('DenyUsers {0}\n'.format(' '.join(str(usr) for usr in ssh['deny-users'])))

    if 'deny-groups' in ssh.keys():
        print('DenyGroups {0}\n'.format(' '.join(str(grp) for grp in ssh['deny-groups'])))

    f.close()
    return None

def apply(ssh):
    if 'port' in ssh.keys():
        cmd = "sudo systemctl restart ssh"
    else:
        cmd = "sudo systemctl stop ssh"

    os.system(cmd)
    return None

if __name__ == '__main__':
    try:
        c = get_config()
        verify(c)
        generate(c)
        apply(c)
    except ConfigError as e:
        print(e)
        sys.exit(1)