summaryrefslogtreecommitdiff
path: root/kpov_judge/tasks/openvpn_simple_smb/task.py
blob: 1ff035bdd4292957f8135bae30e3f693c4fb3300 (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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# kpov_random_helpers should be imported by add_assignment.py

instructions = {
    'si':u"""
Postavi dva navidezna računalnika - SimpleArbiter z diska SimpleArbiterVPN ter
VPNClient1. Poskrbite, da bosta povezana med seboj in v Internet.
Na VPNClient1 namestite OpenVPN in program za nadzor nad virtualnimi napravami
(s katerim kreirate napravo tap).

Na strežniku SimpleArbiterVPN že teče VPN strežnik in uporablja skrivnost, 
ki jo najdete tudi na VPNClient1 v domačem imeniku uporabnika student.
Na VPNClient1 vzpostavite VPN tako, da napišete primerno datoteko z 
nastavitvami. VPNClient1 na navideznem lokalnem omrežju nastavite naslov
{IP_VPNClient1}

Nato poskrbite, da bo na VPNClient1 na navideznem omrežju prek NFS omogočen
dostop do imenika /home/test/{DIRNAME}.
V ta imenik skopirajte datoteke, ki so prek SMB dostopne na SimpleArbiter.
""",
	'en':u"""
Setup two virtual machines - SimpleArbiterVPN and a VPN client (VPNClient1). 
Set the client's network up so that it has access to the internal network and
the internet.
On VPNClient1, install OpenVPN and a program for supervising virtual devices 
(which you will use to create a tap device). On the VPN, set the IP for 
VPNClient1 to {IP_VPNClient1}.

An OpenVPN server is already running on SimpleArbiterVPN. Use the secret 
available on VPNClient1 in the home directory of user student to connect to 
the VPN server on SimpleArbiterVPN. To do that, you will have to write your
own OpenVPN configuration file. 

After you have set up the VPN, make the directory
/home/test/{DIRNAME} on VPNClient1 available over NFS from SimpleArbiter over
your VPN. Copy files that are available from SimpleArbiter over SMB to
/home/test/{DIRNAME}.
"""
}

computers = {
    'SimpleArbiter': {
        'disks': [
            {
                'name': 'simpleArbiterDhcpGWVPN',
                # attempt automount
            },
            #{   'name': 'CDROM',
            #    'options': {'readonly': True},
            #    'parts': [{'dev': 'b1', 'path': '/cdrom'}],
            #},
        ],
        'network_interfaces': [
            {
                'network': 'test-net'
            },
            {
                'network': 'net1'
            }
        ],
        'flavor': 'm1.tiny',
        'config_drive': False
    },
    'VPNClient1': {
        'disks': [
            {   'name': 'student-VPNClient1',
            },
            #{   'name': 'CDROM',
            #    'options':{'readonly': True},
            #    'parts': [],# no parts, no mounting.
            #}
        ],
        'network_interfaces': [
            {
                'network': 'net1'
            }
        ],
        'flavor': 'm1.tiny',
        'config_drive': False
    },
}

networks = {
    'test-net': {
        'public': True
    },
    # Used for the VPN tunnel
    'net1': {
        'public': False
    }
}
#Tukaj sem generiral tri parametre, prosil bi če se upoštevajo pri Tasku. 
params_meta = {
    'IP_SimpleArbiterVPN': {'descriptions':{'si':'IP za SimpleArbiter na VPN'}, 'w': False, 'public': True, 'type': 'IP', 'generated': True}, 
    'IP_VPNClient1': {'descriptions':{'si':'IP klienta na VPN'}, 'w': False, 'public': True, 'type': 'IP', 'generated': True},
    'IP_LANClient1': {'descriptions':{'si':'IP klienta na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False},
    'DIRNAME': {'descriptions':{'si':'Imenik, dostopen prek NFS'}, 'w': False, 'public': True, 'type': 'IP', 'generated': True},
    'secret_random_seed': {'descriptions':{'si':'Seme za skrivnost'}, 'w': False, 'public': False, 'type': None, 'generated': True},
}


def task(IP_SimpleArbiterVPN, IP_VPNClient1, IP_LANClient1, DIRNAME):
     
    from pexpect import pxssh    # Used to set up an SSH connection to a remote machine
    import pexpect  # Allows the script to spawn a child application and control it as if a human were typing commands
    
    
    # The necessary things we need to check if the task was performed correctly
    results = dict()
    
    # The login params (these must be used on the machines!)
    peer_user = 'student'
    peer_passwd = 'vaje'
   
    ###
    # Sets up the SSH connections to the machines
    ###
    # VPNClient1
    sC1 = pxssh.pxssh()
    
    # Logs in to the machines with the default login params
    sC1.login(
        IP_LANClient1,
        peer_user,
        peer_passwd
    )
    
    ######
    # sA
    ######
    
    results['SimpleArbiter_ifconfig'] = pexpect.run(
        '/sbin/ifconfig -a')
    
    results['SimpleArbiter_route'] = pexpect.run(
        '/sbin/route -n')
    
    # Pings each of the clients
    # 10.8.0.6 and 10.8.0.10 are the first two default addresses distributed by OpenVPN
    # Will output everything ping outputs (set to ping 3 times)
    results['SimpleArbiter_ping_C1'] = pexpect.run(
        'ping -c 3 {}'.format(IP_VPNClient1))
    results['SimpleArbiter_traceroute'] = pexpect.run(
        '/usr/bin/traceroute {}'.format(IP_VPNClient1))
    sC1.sendline('cat /etc/exports')
    sC1.prompt()
    output = sC1.before
    results['VPNClient1_nfs_access_control_list'] = output
    results['SimpleArbiter_mount'] = pexpect.run(
        'sudo mount {}:/home/test/{} /mnt'.format(IP_VPNClient1, DIRNAME))
    results['SimpleArbiter_mount_result'] = pexpect.run(
        'sudo mount')
    results['SimpleArbiter_ls'] = pexpect.run(
        'ls /mnt')
    pexpect.run(
        'sudo umount /mnt')
    # Ping the VPN server
    sC1.sendline('ping -c 3 {0}'.format( IP_SimpleArbiterVPN ))
    sC1.prompt()
    results['VPNClient1_ping_VPN_server'] = sC1.before

    sC1.sendline('/sbin/ifconfig -a')
    sC1.prompt()
    results['VPNClient1_ifconfig'] = sC1.before
 
    sC1.sendline('ps xa')
    sC1.prompt()
    results['VPNClient1_ps'] = sC1.before
    sC1.logout()
    
    
    return results


def gen_params(user_id, params_meta):
    params = dict()
    #Tukaj sem generiral te tri parametre (ime skupne skrivnosti je heidi )
    #(ime imenika kjer naj bo shranjena skupna skrivnost naj bo openvpn)
    #(HASH bo naključno generiran niz iz user_id s katerim se bo preverjalo plagiatorstvo)
    import random
    r = random.Random(user_id)
    net = kpov_random_helpers.IPv4_subnet_gen(r, '10.168.0.0/16', 24)
    params['IP_VPNClient1'], params['IP_SimpleArbiterVPN'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2)
    params['DIRNAME'] = kpov_random_helpers.fname_gen(r, extension=False)
    params['secret_random_seed']=str(r.random())
    return params


def task_check(results, params):
    
    import re
    score = 0
    hints = [] 
    # zal si se nisem prišla na jasno s pingi
    IP_SA = params['IP_SimpleArbiterVPN'].replace('.', '\.')
    IP_C1 = params['IP_VPNClient1'].replace('.', '\.')
    rs = r"tap0: flags=.* mtu 1500\r\n +inet {}".format(
        IP_SA)
    # print rs, re.match(rs, results['SimpleArbiter_ifconfig'])
    if re.search(rs,
            results['SimpleArbiter_ifconfig']):
        score += 1
    #    print "ifconfig OK"
    else:
        hints.append("ifconfig on SimpleArbiter not OK")
        pass
    #    print ('SA_ifconfig', results['SimpleArbiter_ifconfig'])
    # results['SimpleArbiter_route'] = pexpect.run(
    
    if re.search(
        "PING.*\r\n64 bytes from {}: icmp_seq=[0-9]+ ttl=64 time=[0-9.]* ms".format(
                IP_C1),
            results['SimpleArbiter_ping_C1']):
    #    print "Server ping OK"
        score += 1
    else:
        hints.append("ping from server not OK")
        pass
    #    print ("Server ping", results['SimpleArbiter_ping_C1'])
    # ignore this
    # print results['SimpleArbiter_mount']
    # print results['SimpleArbiter_traceroute']
    rs = "1 +{0} \({0}\)".format(IP_C1)
    if re.search(rs,
        results['SimpleArbiter_traceroute']):
        score += 1
    else:
        hints.append("traceroute not OK")
        pass
    #    print ("fail!", rs, results['SimpleArbiter_traceroute'])
    if results['VPNClient1_nfs_access_control_list'].find(
        '/home/test/' + params['DIRNAME'] + ' ') >= 0:
        score += 1
    if results['SimpleArbiter_mount_result'].find(
        '{}:/home/test/{} on /mnt type nfs'.format(
            params['IP_VPNClient1'],
            params['DIRNAME'])):
    #    print "mount OK"
        score += 1
    else:
        hints.append("mount not OK")
    # get r into the correct state
    r = random.Random(params['secret_random_seed'])
    s = "\n".join([
        "".join([r.choice("0123456789abcdef") for i in xrange(32)])
        for i in xrange(16)])
    keyfile = kpov_random_helpers.fname_gen(r, extension=False)
    # now check the filenames
    fnames_ok = True
    for i in xrange(3):
        fname = kpov_random_helpers.fname_gen(r, False)
        foo = kpov_random_helpers.fortune(r, 4096)
        pos = results['SimpleArbiter_ls'].find(fname + '.txt')
        fnames_ok = fnames_ok and pos >= 0
        #if pos < 0:
        #    hints.append("missing file:" + fname)
    if fnames_ok:
        score += 2
    else:
        hints.append("shared filenames not OK:")
    # Ping the VPN server
    if re.search(
        "PING.*\r\n64 bytes from {}: icmp_seq=[0-9]+ ttl=64 time=[0-9.]* ms".format(
                IP_SA), 
            results['VPNClient1_ping_VPN_server']):
    #    print "ping OK"
        score += 1
    else:
        hints.append("ping from client not OK")
        pass
    #    print "Client ping", results['VPNClient1_ping_VPN_server']

    rs = r"tap0: flags=.* mtu 1500\r\n +inet {}".format(
        IP_C1)
    if re.search(rs,
            results['VPNClient1_ifconfig']):
        score += 1
    #    print "ifconfig OK"
    else:
        hints.append("ifconfig on VPNClient1 not OK")
        pass
    #    print ('VPNClient1_ifconfig', results['VPNClient1_ifconfig'])
 
    if results['VPNClient1_ps'].find('openvpn') > 0:
        score += 1
    else:
        hints.append("openvpn not found running on VPNClient")
    return score, hints


def prepare_disks(templates, task_params, global_params):
    
    #d = templates['simpleArbiterDhcp']
    
    #guestmount -a d -m /dev/VG/LV -m /dev/sda1:/boot --ro /mnt
    #asistent je pocasnela :) 
    import random
    r = random.Random(task_params['secret_random_seed'])
    s = "\n".join([
        "".join([r.choice("0123456789abcdef") for i in xrange(32)])
        for i in xrange(16)])
    s = """#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
{}
-----END OpenVPN Static key V1-----
""".format(s)
    keyfile = kpov_random_helpers.fname_gen(r, extension=False) + ".key"
    templates['simpleArbiterDhcpGWVPN'].write("/etc/openvpn/secret.key", s)
    netaddr_s = """auto tap0
iface tap0 inet static
    openvpn server
    pre-up tunctl -t tap0
    address {}
    netmask 255.255.255.0
""".format(task_params['IP_SimpleArbiterVPN'])
    templates['simpleArbiterDhcpGWVPN'].write_append("/etc/network/interfaces", netaddr_s) 
    for i in xrange(3):
        fname = kpov_random_helpers.fname_gen(r, False)
        templates['simpleArbiterDhcpGWVPN'].write(
            "/srv/smb/" + fname + '.txt',
            kpov_random_helpers.fortune(r, 4096))
    write_default_config(templates['simpleArbiterDhcpGWVPN'], global_params)
    templates['student-VPNClient1'].write("/home/student/" + keyfile, s)
    # uid, gid (student = )
    templates['student-VPNClient1'].chown(1000, 1000, "/home/student/" + keyfile)