diff options
author | Timotej Lazar <timotej.lazar@fri.uni-lj.si> | 2018-10-07 20:21:31 +0200 |
---|---|---|
committer | Timotej Lazar <timotej.lazar@fri.uni-lj.si> | 2018-10-07 20:21:31 +0200 |
commit | 80f050080ce11c6a0cce67c9b0281c09702b00d6 (patch) | |
tree | b486e1f6342bc757dda87df4856084f652895791 | |
parent | 43d7ef057b4ae752a60b947e523b3a56782bf5cd (diff) | |
parent | dbf585c2a59dbcb7f6d803d5756826b562cd7f43 (diff) |
Merge branch 'fix-tasks'
Fixes pexpect usage in most tasks. Several other cleanups and minor
refactoring.
39 files changed, 826 insertions, 1452 deletions
diff --git a/kpov_judge/README.txt b/kpov_judge/README.txt index b075231..1a9e772 100644 --- a/kpov_judge/README.txt +++ b/kpov_judge/README.txt @@ -77,7 +77,7 @@ Preparing tasks this task. For most tasks, most of the parameters will be randomly generated according to the metadata in params_meta. A number of helper functions for generating the parameters are available in - kpov_random_helpers.py + kpov_util.py - prepare_disks(templates, params) - prepare the disk images for this task. For some tasks it might be neccessarry to create or edit some files on the virtual disk images used by each student to set diff --git a/kpov_judge/add_task.py b/kpov_judge/add_task.py index c995583..8294a33 100755 --- a/kpov_judge/add_task.py +++ b/kpov_judge/add_task.py @@ -1,12 +1,11 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- import pymongo from bson.son import SON from bson import Binary import sys import inspect -import kpov_random_helpers +import kpov_util import settings import glob import os diff --git a/kpov_judge/create_disk_images.py b/kpov_judge/create_disk_images.py index 566c4fe..16bbcab 100755 --- a/kpov_judge/create_disk_images.py +++ b/kpov_judge/create_disk_images.py @@ -1,10 +1,9 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- import pymongo import sys import inspect -import kpov_random_helpers +import kpov_util import settings import guestfs import os diff --git a/kpov_judge/doc/DEVELOPMENT-FAQ.txt b/kpov_judge/doc/DEVELOPMENT-FAQ.txt index c5c0286..0c358cc 100644 --- a/kpov_judge/doc/DEVELOPMENT-FAQ.txt +++ b/kpov_judge/doc/DEVELOPMENT-FAQ.txt @@ -69,7 +69,7 @@ params_meta = { 'w': False, # the student is not allowed to change the value of SOME_IP 'public': True, # the student should be shown the value of SOME_IP if they run test_task.py 'type':'IP', # this can be used to pick the right function to generate the random value - # Look at kpov_random_helpers.default_generators and kpov_random_helpers.IPv4_addr_gen + # Look at kpov_util.default_generators and kpov_util.IPv4_addr_gen # for more info. 'generated': True # this parameter should be generated by gen_params }, @@ -77,7 +77,7 @@ params_meta = { 'descriptions': {'en': 'The MAC of the server', 'si': u'MAC naslov strežnika'}, 'w': True, # the student can change this value 'public': True, # the student should see this parameter when they run test_task.py - 'type':'MAC', # if 'MAC' were a key in kpov_random_helpers.default_generators, the value + 'type':'MAC', # if 'MAC' were a key in kpov_util.default_generators, the value # in that dictionary should be a random function for generating MAC addresses. # Also, in the future, the 'type' field could be used for validation. 'generated': False # the student should enter this value his or herself. @@ -86,7 +86,7 @@ params_meta = { 'descriptions': {'en': 'The name of the file to find'}, # this won't be shown anywhere 'w': False, # the student is not allowed to change this 'public': False, # the student will not be shown this parameter when they run test_task.py - 'type': 'filename', # this can be used by gen_params or kpov_random_helpers for generation + 'type': 'filename', # this can be used by gen_params or kpov_util for generation 'generated': True # the value should be generated in gen_params }, } diff --git a/kpov_judge/kpov_random_helpers.py b/kpov_judge/kpov_util.py index 491e7ce..8520a2d 100755 --- a/kpov_judge/kpov_random_helpers.py +++ b/kpov_judge/kpov_util.py @@ -1,6 +1,7 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- +import collections +import itertools import random import string import socket @@ -11,6 +12,27 @@ import subprocess import glob import os +def ssh_test(host, user, password, commands=()): + from pexpect import pxssh + results = collections.defaultdict(str) + try: + s = pxssh.pxssh(encoding='utf-8') + s.login(host, user, password, + original_prompt='~[#$] ', + auto_prompt_reset=False) + results['ssh'] = True + results['motd'] = s.before + s.set_unique_prompt() + for test, command in commands: + s.sendline(command) + s.prompt() + if test: + results[test] = s.before[len(command+'\r\n'):] + s.logout() + except Exception as ex: + results['ssh'] = str(ex) + return results + def alnum_gen(r, l=1): s = "" for i in range(l): @@ -19,7 +41,9 @@ def alnum_gen(r, l=1): def fortune(r, max_len): all_fortunes = [] - for fortune_file in glob.glob('/usr/share/games/fortunes/*.u8'): + for fortune_file in itertools.chain( + glob.iglob('/usr/share/fortune/*.u8'), + glob.iglob('/usr/share/games/fortunes/*.u8')): f = open(fortune_file) l = f.read().split('\n%\n')[:-1] for i in l: diff --git a/kpov_judge/rm_task.py b/kpov_judge/rm_task.py index 117b3f1..0856a5d 100755 --- a/kpov_judge/rm_task.py +++ b/kpov_judge/rm_task.py @@ -1,12 +1,11 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- import pymongo from bson.son import SON from bson import Binary import sys import inspect -import kpov_random_helpers +import kpov_util import settings import glob import os diff --git a/kpov_judge/tasks/basic_network_gcc/task.py b/kpov_judge/tasks/basic_network_gcc/task.py index ae690f0..c4c4393 100644 --- a/kpov_judge/tasks/basic_network_gcc/task.py +++ b/kpov_judge/tasks/basic_network_gcc/task.py @@ -1,6 +1,3 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# # TODO: # - check if everything is filled in (computers, params, preparation) # - improve scoring @@ -118,51 +115,34 @@ params_meta = { def task(student_IP, net_prog_name, P_c, P_executable, arg_c, env_c, out_stderr_c, out_stdout_c, P_script, param_gen_seed): - from pexpect import pxssh import random - conn = pxssh.pxssh() - conn.login(student_IP, 'student', 'vaje') - results = dict() + r = random.Random(int(param_gen_seed)) env_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(11)]) - arg_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(13)]) stdin_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(17)]) - conn.sendline('ls -l {}'.format(P_script)) - conn.prompt() - results['script_ls'] = conn.before - conn.sendline('ls -l {}'.format(P_executable)) - conn.prompt() - results['executable_ls'] = conn.before - conn.sendline('export {}={}; {}'.format(env_c, env_val, P_script)) - conn.prompt() - results['script_run'] = conn.before - conn.sendline('cat {}'.format(out_stderr_c)) - conn.prompt() - results['script_stderr'] = conn.before - conn.sendline('cat {}'.format(out_stdout_c)) - conn.prompt() - results['script_stdout'] = conn.before - conn.sendline('echo "{}" | {} "{}" 2> /dev/null'.format(stdin_val, P_executable, arg_val)) - conn.prompt() - results['prog_stdout'] = conn.before - conn.sendline('echo "{}" | {} "{}" > /dev/null'.format(stdin_val, P_executable, arg_val)) - conn.prompt() - results['prog_stderr'] = conn.before - conn.logout() - return results + + return kpov_util.ssh_test(student_IP, 'student', 'vaje', ( + ('script_ls', 'ls -l {}'.format(P_script)), + ('executable_ls', 'ls -l {}'.format(P_executable)), + ('script_run', 'export {}={}; {}'.format(env_c, env_val, P_script)), + ('script_stdout', 'cat {}'.format(out_stdout_c)), + ('script_stderr', 'cat {}'.format(out_stderr_c)), + ('prog_stdout', 'echo "{}" | {} "{}" 2> /dev/null'.format(stdin_val, P_executable, arg_val)), + ('prog_stderr', 'echo "{}" | {} "{}" > /dev/null'.format(stdin_val, P_executable, arg_val)), + )) def gen_params(user_id, params_meta): import random r = random.Random(user_id+'evil cornholio') - params = kpov_random_helpers.default_gen(user_id, params_meta) + params = kpov_util.default_gen(user_id, params_meta) homedir = '/home/student/' params['env_c'] = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ') for i in range(5)]) params['P_c'] = "".join([r.choice('abcdefghijklmnoprst') for i in range(5)]) + ".c" params['param_gen_seed'] = str(r.randint(0, 2**24)) params['c_destroy_gen_seed'] = str(r.randint(0, 2**24)) - dest_net = kpov_random_helpers.IPv4_subnet_gen(r, '10.0.2.128/26', 26) - params['student_IP'] = kpov_random_helpers.IPv4_addr_gen(r, dest_net)[0] + dest_net = kpov_util.IPv4_subnet_gen(r, '10.0.2.128/26', 26) + params['student_IP'] = kpov_util.IPv4_addr_gen(r, dest_net)[0] for k in ['P_c', 'P_executable', 'out_stderr_c', 'P_script', 'out_stdout_c']: params[k] = homedir + params[k] return params @@ -198,16 +178,13 @@ def task_check(results, params): expected_script_stdout, expected_script_stderr, rval = test_out_gen( params['arg_c'], env_val ) - expected_script_stderr = 'cat {}\r\n'.format(params['out_stderr_c']) + expected_script_stderr - # hints += [expected_script_stderr, results['script_run'], results['script_stderr'], params['arg_c'], env_val] if expected_script_stderr != results['script_stderr']: hints += ['wrong script stderr'] else: score += 2 split_stdout = expected_script_stdout.split('\r\n') expected_script_stdout = "\r\n".join([ i for i in split_stdout if i.find('ma') >= 0]) - expected_script_stdout = 'cat {}\r\n'.format(params['out_stdout_c']) + expected_script_stdout + "\r\n" - if expected_script_stdout != results['script_stdout']: + if expected_script_stdout != results['script_stdout'].strip(): hints += ['wrong script stdout'] else: score += 2 @@ -288,9 +265,9 @@ done; }& destroyed_c_source += 'QX' destroyed_c_source += c d.write(task_params['P_c'], destroyed_c_source) - d.chown(1000, 1000, params['P_c']) + d.chown(1000, 1000, task_params['P_c']) sh_path = r.choice(['/usr/share/doc', '/var/lib', '/usr/local/share', '/etc/alternatives']) - sh_file = sh_path + '/' + params['net_prog_name'] + sh_file = sh_path + '/' + task_params['net_prog_name'] d.write(sh_file, evil_shell_source) d.chmod(0o775, sh_file) d.write("/etc/rc.local", """#!/bin/sh -e diff --git a/kpov_judge/tasks/copy_rename_100_files/task.py b/kpov_judge/tasks/copy_rename_100_files/task.py index 9ad4d66..051f9f7 100644 --- a/kpov_judge/tasks/copy_rename_100_files/task.py +++ b/kpov_judge/tasks/copy_rename_100_files/task.py @@ -1,6 +1,3 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# # TODO: # - check if everything is filled in (computers, params, preparation) # - improve scoring @@ -73,17 +70,10 @@ params_meta = { } def task(host, folder): - from pexpect import pxssh - - # ideally, this would be done using a SFTP client instead of pxssh - target = pxssh.pxssh() - target.login(host, 'test', 'test') - results = { - 'files': target.run('ls -1').split('\n'), # XXX: file may have newlines - 'contents': target.run("cat *"), # XXX: may include other files in $HOME - } - target.logout() - return results + return kpov_util.ssh_test(host, 'test', 'test', ( + ('files', 'ls -1'), # XXX: file may have newlines + ('contents', 'cat *'), # XXX: may include other files in $HOME + )) def gen_params(user_id, params_meta): pass @@ -93,10 +83,13 @@ def task_check(results, params): score = 0 hints = [] + if results['ssh'] is not True: + hints += ['ssh failed: ' + results['ssh']] + matched = 0 files = os.listdir(params['folder']) for fn in files: - if fn in results['files']: + if fn in results['files'].splitlines(): matched += 1 if matched > 0: score = 1 @@ -110,12 +103,12 @@ def task_check(results, params): score += 3 else: hints += ["wrong number of files"] - rl = results['contents'].split('\n') + rl = results['contents'].splitlines() rl.sort() tl = [] for fn in files: - with open(fn) as f: - tl += f.read().upper().split('\n') + with open(os.path.join(params['folder'], fn)) as f: + tl += f.read().upper().splitlines() tl.sort() if rl == tl: score += 4 diff --git a/kpov_judge/tasks/copy_rename_20_files_tail_env/solution/solution.py b/kpov_judge/tasks/copy_rename_20_files_tail_env/solution/solution.py index 7a26b77..6036cd1 100644 --- a/kpov_judge/tasks/copy_rename_20_files_tail_env/solution/solution.py +++ b/kpov_judge/tasks/copy_rename_20_files_tail_env/solution/solution.py @@ -1,92 +1,92 @@ -# preimenuj vse datoteke tako, da zamenjaš minuse s podčrtaji
-def rename():
- import os
- for filename in os.listdir('.'):
- os.rename(filename, filename.replace('-', '_'))
-
-# Napiši čim krajši ukaz, ki vse datoteke iz /home/user/mapa/mojimenik premakne v /home/user/novi
-def mv_novi():
- import os
- for filename in os.listdir("/home/user/mapa/mojimenik/"):
- os.rename('/home/user/mapa/mojimenik/' + filename, '/home/user/novi/' + filename)
-
-# Napiši ukaz, ki s pomočjo ukaza grep v datoteko "mama.txt" izpiše vse navade (ne skrite) datoteke v trenutnem imeniku, ki vsebujejo niz "mama", v datoteko "napake.txt" pa izpiše vse morebitne napake (npr. to, da so nekateri objekti v trenutnem imeniku dejansko imeniki ali napačne simbolične povezave)
-def mama():
- import os
- import re
- import mmap
- mama = ''
- wrong = ''
- for filename in os.listdir('.'):
- try:
- f = open(filename, 'r+')
- data = mmap.mmap(f.fileno(), 0)
- if re.search('mama', data):
- mama = mama + filename + "\n"
- except ValueError:
- wrong = wrong + filename + "\n"
- open('mama.txt', 'w').write(mama)
- open('napake.txt', 'w').write(wrong)
-
-# Napiši ukaz, ki bo 5s sledil vsebini /var/log/syslog. V primeru, da se v syslogu pojavi niz "zmeda", naj program izpiše "imam ga". Poleg tega naj program med sledenjem syslog-u odšteva od 5 do 1 (vsako sekundo naj se izpiše naslednja številka.
-def checker():
- import time
- import re
- import mmap
- t = time.time() * 1000
- n = t
-
- f = open('/var/log/syslog', 'r+')
- data = mmap.mmap(f.fileno(), 0)
- me = re.findall('zmeda', data)
-
- c = len(me)
- for i in range(5, 0, -1):
- print(i)
- n += 1000
- while n > t:
- f = open('/var/log/syslog', 'r+')
- data = mmap.mmap(f.fileno(), 0)
- me = re.findall('zmeda', data)
- if len(me) > c:
- c = len(me)
- print('imam ga')
- t = time.time() * 1000
-
-# Nastavi okoljsko spremenljivko TEST, da bo imela isto vrednost kot okoljska spremenljivka USER + število okoljskih spremenljivk, ki v imenu ali vrednosti ne vsebujejo besede TEST. Primer: polz37
-def env():
- import os
- import re
- c = 0
- for i in os.environ:
- if not (re.search('TEST', i) or re.search('TEST', os.environ[i])):
- c = c + 1
- os.environ['TEST'] = os.environ['USER'] + repr(c)
-
-# S pomočjo programa cURL shrani vsebino spletne strani www.google.com v datoteko z imenom website.txt
-def googl():
- import urllib.request, urllib.error, urllib.parse
- open('website.txt', 'w').write(urllib.request.urlopen('http://www.google.com').read())
-
-# Napiši ukaz, ki bo število pojavitev značke <div> v datoteki website.txt dodal na konec te iste datoteke brez, da bi se ukaz zapisal v zgodovino ukazov "bash history"
-def div():
- import re
- import mmap
- f = open('website.txt', 'r+')
- data = mmap.mmap(f.fileno(), 0)
- me = re.findall('<[^/<>]*div[^>]*>', data)
- open('website.txt', 'a+').write(repr(len(me)))
-
-# Napiši ukaz brez uporabe programa cron, kateri 5 minut po izvedbi izpiše vsebino imenika v katerem se trenutno nahajaš
-def sleep():
- import time
- import os
- time.sleep(300)
- print(os.listdir('.'))
-
-# Napiši najkrajši ukaz, ki s pomočjo Pythona zažene preprost (integriran) HTTP strežnik kateri streže datoteke iz imenika iz katerega je bil pognan na vratih 8000
-def server():
- import http.server
- import socketserver
- httpd = socketserver.TCPServer(("", 8000), http.server.SimpleHTTPRequestHandler)
- httpd.serve_forever()
+# preimenuj vse datoteke tako, da zamenjaš minuse s podčrtaji +def rename(): + import os + for filename in os.listdir('.'): + os.rename(filename, filename.replace('-', '_')) + +# Napiši čim krajši ukaz, ki vse datoteke iz /home/user/mapa/mojimenik premakne v /home/user/novi +def mv_novi(): + import os + for filename in os.listdir("/home/user/mapa/mojimenik/"): + os.rename('/home/user/mapa/mojimenik/' + filename, '/home/user/novi/' + filename) + +# Napiši ukaz, ki s pomočjo ukaza grep v datoteko "mama.txt" izpiše vse navade (ne skrite) datoteke v trenutnem imeniku, ki vsebujejo niz "mama", v datoteko "napake.txt" pa izpiše vse morebitne napake (npr. to, da so nekateri objekti v trenutnem imeniku dejansko imeniki ali napačne simbolične povezave) +def mama(): + import os + import re + import mmap + mama = '' + wrong = '' + for filename in os.listdir('.'): + try: + f = open(filename, 'r+') + data = mmap.mmap(f.fileno(), 0) + if re.search('mama', data): + mama = mama + filename + "\n" + except ValueError: + wrong = wrong + filename + "\n" + open('mama.txt', 'w').write(mama) + open('napake.txt', 'w').write(wrong) + +# Napiši ukaz, ki bo 5s sledil vsebini /var/log/syslog. V primeru, da se v syslogu pojavi niz "zmeda", naj program izpiše "imam ga". Poleg tega naj program med sledenjem syslog-u odšteva od 5 do 1 (vsako sekundo naj se izpiše naslednja številka. +def checker(): + import time + import re + import mmap + t = time.time() * 1000 + n = t + + f = open('/var/log/syslog', 'r+') + data = mmap.mmap(f.fileno(), 0) + me = re.findall('zmeda', data) + + c = len(me) + for i in range(5, 0, -1): + print(i) + n += 1000 + while n > t: + f = open('/var/log/syslog', 'r+') + data = mmap.mmap(f.fileno(), 0) + me = re.findall('zmeda', data) + if len(me) > c: + c = len(me) + print('imam ga') + t = time.time() * 1000 + +# Nastavi okoljsko spremenljivko TEST, da bo imela isto vrednost kot okoljska spremenljivka USER + število okoljskih spremenljivk, ki v imenu ali vrednosti ne vsebujejo besede TEST. Primer: polz37 +def env(): + import os + import re + c = 0 + for i in os.environ: + if not (re.search('TEST', i) or re.search('TEST', os.environ[i])): + c = c + 1 + os.environ['TEST'] = os.environ['USER'] + repr(c) + +# S pomočjo programa cURL shrani vsebino spletne strani www.google.com v datoteko z imenom website.txt +def googl(): + import urllib.request, urllib.error, urllib.parse + open('website.txt', 'w').write(urllib.request.urlopen('http://www.google.com').read()) + +# Napiši ukaz, ki bo število pojavitev značke <div> v datoteki website.txt dodal na konec te iste datoteke brez, da bi se ukaz zapisal v zgodovino ukazov "bash history" +def div(): + import re + import mmap + f = open('website.txt', 'r+') + data = mmap.mmap(f.fileno(), 0) + me = re.findall('<[^/<>]*div[^>]*>', data) + open('website.txt', 'a+').write(repr(len(me))) + +# Napiši ukaz brez uporabe programa cron, kateri 5 minut po izvedbi izpiše vsebino imenika v katerem se trenutno nahajaš +def sleep(): + import time + import os + time.sleep(300) + print(os.listdir('.')) + +# Napiši najkrajši ukaz, ki s pomočjo Pythona zažene preprost (integriran) HTTP strežnik kateri streže datoteke iz imenika iz katerega je bil pognan na vratih 8000 +def server(): + import http.server + import socketserver + httpd = socketserver.TCPServer(("", 8000), http.server.SimpleHTTPRequestHandler) + httpd.serve_forever() diff --git a/kpov_judge/tasks/copy_rename_20_files_tail_env/task.py b/kpov_judge/tasks/copy_rename_20_files_tail_env/task.py index 7e3c3c8..aa57d3e 100644 --- a/kpov_judge/tasks/copy_rename_20_files_tail_env/task.py +++ b/kpov_judge/tasks/copy_rename_20_files_tail_env/task.py @@ -1,6 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py # TODO (polz): instructions = { @@ -116,90 +114,54 @@ params_meta = { } def task(IP_malishell, file_rename_dirname, mv_src_dir, mv_dst_dir, cowsay_string, curl_fname, wc_dirname): - from pexpect import pxssh + import collections import os - # TODO: (polz) this has to be changed! Get a move on! + + # TOD: (polz) this has to be changed! Get a move on! # - # sv: Z primozem lavricem sva skusala nekaj narediti + # sv: Z primozem lavricem sva skusala nekaj narediti # Ker gen params ni narejen, sklepam da je "Mapa" na namizju, # imena datotek pa so: 1,1-,2,2-,3,3-,4,5,6,7,8,9,.mama1,mama2,mama3,mama4,mama5,mojimenik,novi,oce1 # v mojimenik se nahaja mojimenikfile # mama2 vsebuje "mama" #Stirje subt-aski dodani.By Mihec. - results = dict() - conn = pxssh.pxssh() - conn.login(IP_malishell, 'student', 'vaje') - # preimenuj datoteke - conn.sendline('/bin/ls -a1 {}'.format(file_rename_dirname)) - conn.prompt() - results['preimenuj'] = conn.before - # premakni datoteke s cim krajsim ukazom - conn.sendline('/bin/ls -a1 {}'.format(mv_src_dir)) - conn.prompt() - results['pre_mv_src'] = conn.before - conn.sendline('/bin/ls -a1 {}'.format(mv_dst_dir)) - conn.prompt() - results['pre_mv_dst'] = conn.before - conn.sendline('/bin/ls -l ~/mv_ukaz') - conn.prompt() - results['mv_ls_size'] = conn.before - conn.sendline('. ~/mv_ukaz') - conn.prompt() - conn.sendline('/bin/ls -a1 {}'.format(mv_src_dir)) - conn.prompt() - results['post_mv_src'] = conn.before - conn.sendline('/bin/ls -a1 {}'.format(mv_dst_dir)) - conn.prompt() - results['post_mv_dst'] = conn.before - # mama_ukaz - # - conn.sendline('cd /home/student/grep_test_dir') - conn.prompt() - conn.sendline('. ~/mama_ukaz') - conn.prompt() - conn.sendline('cat ~/napake.txt') - conn.prompt() - results['grep_napake'] = conn.before - conn.sendline('cat ~/mama.txt') - conn.prompt() - results['grep_mama'] = conn.before - # sledenje syslog - conn.sendline('date') - conn.prompt() - conn.sendline('/usr/local/bin/syslog_spammer &') - conn.prompt() - results['syslog_start_time'] = conn.before - conn.sendline('/home/student/syslog_ukaz.sh') - conn.prompt() - results['syslog_result'] = conn.before - conn.sendline('date') - conn.prompt() - results['syslog_end_time'] = conn.before - conn.sendline('cowsay "{}"'.format(cowsay_string)) - conn.prompt() - results['cowsay'] = conn.before + results = kpov_util.ssh_test(IP_malishell, 'student', 'vaje', ( + ('preimenuj', '/bin/ls -a1 {}'.format(file_rename_dirname)), + ('pre_mv_src', '/bin/ls -a1 {}'.format(mv_src_dir)), + ('pre_mv_dst', '/bin/ls -a1 {}'.format(mv_dst_dir)), + ('mv_ls_size', '/bin/ls -l ~/mv_ukaz'), + (None, '. ~/mv_ukaz'), + ('post_mv_src', '/bin/ls -a1 {}'.format(mv_src_dir)), + ('post_mv_dst', '/bin/ls -a1 {}'.format(mv_dst_dir)), + + # mama_ukaz + (None, 'cd /home/student/grep_test_dir'), + (None, '. ~/mama_ukaz'), + ('grep_napake', 'cat ~/napake.txt'), + ('grep_mama', 'cat ~/mama.txt'), + + # sledenje syslog + (None, 'date'), + ('syslog_start_time', '/usr/local/bin/syslog_spammer &'), + ('syslog_result', '/home/student/syslog_ukaz.sh'), + ('syslog_end_time', 'date'), + + ('cowsay', 'cowsay "{}"'.format(cowsay_string)), + ('wc_origfile', 'cat {}/count.txt'.format(wc_dirname)), + ('wc_lines', 'cat {}/lines.txt'.format(wc_dirname)), + )) + try: results['curl_env'] = os.environ['images'] except: results['curl_env'] = '' - conn.sendline('cat {}/count.txt'.format(wc_dirname)) - conn.prompt() - results['wc_origfile'] = conn.before - conn.sendline('cat {}/lines.txt'.format(wc_dirname)) - conn.prompt() - results['wc_lines'] = conn.before - conn.logout() - #results['curl'] = subprocess.check_output(["cat","/home/student/Desktop/website.txt"]) + #results['curl'] = subprocess.check_output(["cat","/home/student/Desktop/website.txt"]) #results['chkimages'] = subprocess.check_output(["curl www.24ur.com >> dlg.txt && cat dlg.txt | grep -c ","images"]) - #results['count'] = subprocess.check_output(["wc","/home/student/Desktop/count.txt"]) - #results['lines'] = subprocess.check_output(["cat","/home/student/Desktop/lines.txt"]) - #results['cowsay'] = subprocess.check_output(["dpkg --get-selections | grep","cowsay"]) - #results['phttp'] = subprocess.check_output(["lsof -i ",":8080"]) return results def gen_params(user_id, params_meta): @@ -209,16 +171,15 @@ def gen_params(user_id, params_meta): homedir = '/home/student/' r = random.Random(user_id) params['file_creator_random_seed'] = str(r.random()) - params['file_rename_dirname'] = homedir + kpov_random_helpers.default_generators['dirname'](r) + params['file_rename_dirname'] = homedir + kpov_util.default_generators['dirname'](r) params['mv_src_dir'] = homedir + "".join([r.choice("abcdefgh") for i in range(6)]) params['mv_dst_dir'] = homedir + "".join([r.choice("ijklmnop") for i in range(6)]) params['syslog_n_zmeda'] = str(r.randint(5, 15)) - params['cowsay_string'] = kpov_random_helpers.default_generators['short_text'](r) - params['curl_fname'] = kpov_random_helpers.default_generators['filename'](r) + params['cowsay_string'] = kpov_util.default_generators['short_text'](r) + params['curl_fname'] = kpov_util.default_generators['filename'](r) params['curl_n_images'] = str(r.randint(30,100)) params['wc_dirname'] = homedir + "".join([r.choice("rstuvxz") for i in range(8)]) params['wc_n_lines'] = str(r.randint(200, 600)) - #params['phttp'] = "8080" #params['images'] = subprocess.check_output(["echo","$images"]) return params @@ -232,22 +193,20 @@ def task_check(results, params): for i in range(20): fnames.append("".join([ r.choice("_abcdefghijk") for j in range(8)])) #TO FINISH SCORING WE REQUIRE DICT KEYS AND FUNCTIONS gen_params AND task TO BE FINISHED - #POINTS FOR EACH TASK MAY BE ADJUSTED IN THE FUTURE - #TASK 1 - # print( results['preimenuj']) + + # preimenuj 1 lines = results['preimenuj'].split("\n") task1_ok = len(lines) == len(fnames) + 4 task1_ok = task1_ok and lines[0].find(params['file_rename_dirname']) >= 0 task1_ok = task1_ok and lines[1].strip() == "." task1_ok = task1_ok and lines[2].strip() == ".." - # print task1_ok for fname in fnames: - # print task1_ok, fname, results['preimenuj'].find(fname) task1_ok = task1_ok and results['preimenuj'].find(fname) > 0 if task1_ok: score += 2 else: hints += ["wrong dash rename"] + # premakni datoteke s cim krajsim ukazom fnames = [] try: @@ -264,6 +223,8 @@ def task_check(results, params): score += 1 else: hints += ["wrong mv_command size or owner"] + + # rename files pre_src = set([i.strip() for i in results['pre_mv_src'].split('\n')[3:-1]]) pre_dst = set([i.strip() for i in results['pre_mv_dst'].split('\n')[3:-1]]) task2_ok = task2_ok and pre_src == set(fnames) @@ -276,8 +237,8 @@ def task_check(results, params): score += 1 else: hints += ["wrong rename files"] + # mama_ukaz - # task3_ok = True mama_fnames = [] for i in range(20): @@ -291,8 +252,6 @@ def task_check(results, params): linknames = [] for i in range(20): linknames.append("".join([ r.choice("123456789abcdefghijk") for j in range(8)])) - #print( results['grep_mama']) - #print( results['grep_napake']) for i in dirnames + linknames + papa_fnames: if (i not in papa_fnames) and results['grep_napake'].find(i) < 0: task3_ok = False @@ -310,6 +269,7 @@ def task_check(results, params): score += 2 else: hints += ["mama cries"] + # sledenje syslog #print( results['syslog_start_time']) #print( results['syslog_result']) @@ -321,7 +281,7 @@ def task_check(results, params): score += 1 else: hints += ["wrong syslog count"] - # + task5_ok = True try: assert int(results['curl_env'].strip()) == int(params['curl_n_images']) @@ -332,11 +292,8 @@ def task_check(results, params): else: hints += ["wrong image count"] task6_ok = True - wc_cat_str = 'cat {}/lines.txt'.format(params['wc_dirname']) - if not wc_cat_str == results['wc_lines'][:len(wc_cat_str)]: - task6_ok = False try: - assert int(results['wc_lines'][len(wc_cat_str):].strip()) == int(params['wc_n_lines']) + assert int(results['wc_lines'].strip()) == int(params['wc_n_lines']) except: task6_ok = False if task6_ok: @@ -409,4 +366,4 @@ def prepare_disks(templates, task_params, global_params): d.mkdir(task_params['wc_dirname']) d.chown(1000, 1000, task_params['wc_dirname']) d.write("{}".format(os.path.join(task_params['wc_dirname'], 'count.txt')), "".join(lx)) - write_default_config(templates['simpleArbiterDhcpGW'], global_params) + #write_default_config(templates['simpleArbiterDhcpGW'], global_params) diff --git a/kpov_judge/tasks/custom_rdate/task.py b/kpov_judge/tasks/custom_rdate/task.py index b84a2b7..4959266 100644 --- a/kpov_judge/tasks/custom_rdate/task.py +++ b/kpov_judge/tasks/custom_rdate/task.py @@ -1,7 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +# kpov_util should be imported by add_assignment.py -# kpov_random_helpers should be imported by add_assignment.py # TODO: finish this! instructions = { 'si':""" @@ -39,10 +37,6 @@ computers = { 'disks': [ { 'name': 'student-rdate', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -52,12 +46,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcpGWRdate', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -75,37 +64,26 @@ params_meta = { } def task(IP_RDATECLIENT, PROGRAM_FILENAME): - import pexpect - import paramiko - from paramiko import SSHClient + import collections + import base64 import random import struct - import base64 - results = dict() - peer_user = 'test' - peer_passwd = 'test' - client = SSHClient() - client.load_system_host_keys() - client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - client.connect(IP_RDATECLIENT, username=peer_user, password=peer_passwd) - #client.login(IP_RDATECLIENT, peer_user, peer_passwd) + import pexpect + r = random.Random(PROGRAM_FILENAME) + results = collections.defaultdict(str) + tests = [] for i in range(10): - stdin, stdout, stderr = client.exec_command( - '~/{}'.format(PROGRAM_FILENAME)) data = struct.pack("!I", r.randint(0, 2**32)) - stdin.write(data) - results['in_' + str(i)] = base64.encodestring(data) - results['out_' + str(i)] = stdout.read() - stdin, stdout, stderr = client.exec_command( - 'date -u +"%s"') - #client.sendline('date -u "%s"') - #client.prompt() - results['date'] = stdout.read() + results['in_'+str(i)] = data_ascii = base64.encodestring(data) + tests += [('out_'+str(i), 'echo "{}" | base64 -d | ~/{}'.format(data_ascii.decode().strip(), PROGRAM_FILENAME))] + tests += [('date', 'date -u +"%s"')] + + results.update( + kpov_util.ssh_test(IP_RDATECLIENT, 'test', 'test', tests)) results['ldate'] = pexpect.run('date -u +"%s"') - client.close() - return results + return results #Dolocil sem tri parametre in sicer jih lahko vidite v prams_meta, #zato prosim da jih upostevate v naslednih nalogah. @@ -116,7 +94,7 @@ def gen_params(user_id, params_meta): import datetime params = dict() r = random.Random(user_id) - params['PROGRAM_FILENAME'] = kpov_random_helpers.fname_gen(r, False) + params['PROGRAM_FILENAME'] = kpov_util.fname_gen(r, False) params['RDATE_OFFSET'] = str(r.randint(-2**24, 2**24)) return params @@ -124,7 +102,7 @@ def task_check(results, params): import random import struct import base64 - # print results + r = random.Random(params['PROGRAM_FILENAME']) score = 0.0 hints = [] @@ -139,7 +117,7 @@ def task_check(results, params): score += 0.5 else: hints += ["wrong convert"] - # print str(struct.unpack("!I", data)[0]), res.strip() + if abs(int(results['ldate']) + \ int(params['RDATE_OFFSET']) - int(results['date'])) < 3: score += 5 @@ -148,9 +126,6 @@ def task_check(results, params): return score, hints def prepare_disks(templates, task_params, global_params): -# d = templates['simpleArbiterDhcp'] -# print templates -# print params d = templates['simpleArbiterDhcpGWRdate'] s1 = """service "time_tcp" {{ enabled yes; @@ -170,7 +145,7 @@ import time import sys offset = int(sys.argv[1]) -t = time.time() + 2208988800 + offset +t = time.time() + offset # used to have + 2208988800 sys.stdout.write(struct.pack("!I", int(t))) """ d.write('/usr/local/bin/kpovrdate', s2) diff --git a/kpov_judge/tasks/dhcp_dns_predefined_ip/task.py b/kpov_judge/tasks/dhcp_dns_predefined_ip/task.py index 40507d5..fb0de84 100644 --- a/kpov_judge/tasks/dhcp_dns_predefined_ip/task.py +++ b/kpov_judge/tasks/dhcp_dns_predefined_ip/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -65,47 +62,28 @@ params_meta = { } def task(IP_server, IP_client, MAC_client, HOSTNAME_X): - from pexpect import pxssh - #import pexpect - results = dict() - peer_user = 'student' - peer_passwd = 'vaje' - sA = pxssh.pxssh() - sB = pxssh.pxssh() - #prijavimo se na streznik (IP_NM je IP nalov streznika) - sA.login(IP_server, peer_user, peer_passwd) - #prijavimo se na klienta (IP_static je IP naslov klienta) - sB.login(IP_client, peer_user, peer_passwd) - sA.sendline('sudo ps -A') - sA.sendline(peer_passwd) - sA.prompt() - results['dhcp_proces'] = sA.before - # tukaj dobimo podatke, ce je na IP_NM naslovu res postavljen DHCP streznik - sB.sendline('sudo dhcping -s {} -h {} -c {}'.format(IP_server, MAC_client, IP_client)) - sB.sendline(peer_passwd) - sB.prompt() - results['dhcp'] = sB.before - # tukaj pa dobimo podatek, ce je IP, ki ga vraca DNS streznik za HOSTNAME_X pravilen - sB.sendline('nslookup {}'.format(HOSTNAME_X)) - sB.prompt() - results['dns_hostname'] = sB.before - sB.sendline('/sbin/ifconfig') - sB.prompt() - results['client_IP'] = sB.before - sA.logout() - sB.logout() - return results + tests = { + IP_server: ( + ('dhcp_proces', 'sudo ps -A')), + IP_client: ( + ('dhcp', 'sudo dhcping -s {} -h {} -c {}'.format(IP_server, MAC_client, IP_client)), + ('dns_hostname', 'nslookup {}'.format(HOSTNAME_X)), + ('client_IP', '/sbin/ifconfig')), + } + results = collections.defaultdict(str) + for host, host_tests in tests.items(): + results.update(kpov_util.ssh_test(host, 'student', 'vaje', host_tests)) + return results def gen_params(user_id, params_meta): params = dict() r = random.Random(user_id+"bla") - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) - params['IP_server'], params['IP_client'], params['IP_X'] = kpov_random_helpers.IPv4_addr_gen(r, net, 3) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + params['IP_server'], params['IP_client'], params['IP_X'] = kpov_util.IPv4_addr_gen(r, net, 3) params['HOSTNAME_X'] = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ') for i in range(5)]) return params - def task_check(results, params): import re score = 0 diff --git a/kpov_judge/tasks/edit_find_grep_compile_convert/task.py b/kpov_judge/tasks/edit_find_grep_compile_convert/task.py index 3d9aafa..7a96a0b 100644 --- a/kpov_judge/tasks/edit_find_grep_compile_convert/task.py +++ b/kpov_judge/tasks/edit_find_grep_compile_convert/task.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# # TODO: # - check if everything is filled in (computers, params, preparation) # - improve scoring # - test # - switch to a real SSH/SFTP client to properly handle filenames - instructions = { 'si':""" Ustvari dva navidezna računalnika s slikama diskov @@ -191,52 +187,41 @@ params_meta = { } def task(testip, testuser, passwd, magicstr, dstfile, progname, pubseed): - from pexpect import pxssh import random - N_TITA = 40 - target = pxssh.pxssh() - target.login(testip, testuser, passwd) - target.sendline('ls -l ~/{}'.format(dstfile)) - target.prompt() - dst_ls = target.before - target.sendline('cat ~/{}'.format(dstfile)) - target.prompt() - dst_file_contents = target.before - target.sendline('ls ~/'.format(dstfile)) - target.prompt() - home_ls = target.before - results = { - 'dst_ls': dst_ls, - 'dst_file_contents': dst_file_contents, - 'home_ls': home_ls, - } - tita_return = "" + r = random.Random(pubseed) + tests = [ + ('dst_ls', 'ls -l ~/{}'.format(dstfile)), + ('dst_file_contents', 'cat ~/{}'.format(dstfile)), + ('home_ls', 'ls ~/'.format(dstfile)), + ] + + N_TITA = 40 for i in range(N_TITA): b = r.randint(0, 7) x = oct(r.randint(37, 127)).replace('o', '') - target.sendline('echo -e "\\{}" | ~/{} {}'.format(x, progname, b)) - target.prompt() - tita_return += target.before - results['tita_return'] = tita_return - target.logout() + tests += [('tita-{:02}'.format(i), 'echo -e "\\{}" | ~/{} {}'.format(x, progname, b))] + + results = kpov_util.ssh_test(testip, testuser, passwd, tests) + results['tita_return'] = ''.join(val for key, val in results.items() if key.startswith('tita-')) + return results def gen_params(user_id, params_meta): import random params = dict() r = random.Random(user_id) - params['testip'] = kpov_random_helpers.IPv4_addr_gen(r, + params['testip'] = kpov_util.IPv4_addr_gen(r, network = '10.94.80.0/19', n_generated=1)[0] - params['testuser'] = kpov_random_helpers.default_generators['username'](r) - params['passwd'] = kpov_random_helpers.alnum_gen(r, 8) + params['testuser'] = kpov_util.default_generators['username'](r) + params['passwd'] = kpov_util.alnum_gen(r, 8) params['magicstr'] = "".join([r.choice("qwerztlpoQWERTPOL") for i in range(10)]) - params['dstfile'] = kpov_random_helpers.default_generators['filename'](r) - params['progname'] = kpov_random_helpers.default_generators['filename'](r) + params['dstfile'] = kpov_util.default_generators['filename'](r) + params['progname'] = kpov_util.default_generators['filename'](r) while params['dstfile'] == params['progname']: - params['progname'] = kpov_random_helpers.default_generators['filename'](r) - params['pubseed'] = kpov_random_helpers.alnum_gen(r, 8) - params['rndseed'] = kpov_random_helpers.alnum_gen(r, 8) + params['progname'] = kpov_util.default_generators['filename'](r) + params['pubseed'] = kpov_util.alnum_gen(r, 8) + params['rndseed'] = kpov_util.alnum_gen(r, 8) return params @@ -258,11 +243,6 @@ def task_check(results, params): x = start + mid + end hidden_contents += x + "\r\n" expected_contents = hidden_contents - #expected_contents = re.sub(r"^po.*lz\r$", - # r"pokakalz\r", - # hidden_contents, - # re.MULTILINE) - expected_contents = "cat ~/{}\r\n".format(params['dstfile']) + expected_contents if results["dst_file_contents"] == expected_contents: score += 3 else: @@ -275,7 +255,7 @@ def task_check(results, params): break hints += ["wrong file contents\n" + str(diff_pos[1])] #hints += ["wrong file contents"] - expected_ls = "ls -l ~/{dstfile}\r\n-rw--w---- 1 {testuser} bilbo .*{dstfile}.*\r\n".format(**params) + expected_ls = "-rw--w---- 1 {testuser} bilbo .*{dstfile}.*\r\n".format(**params) if re.match(expected_ls, results["dst_ls"]): score += 3 else: @@ -290,7 +270,6 @@ def task_check(results, params): b = r.randint(0, 7) x_i = r.randint(37, 127) x = oct(x_i).replace('o', '') - expected_tita += 'echo -e "\\{}" | ~/{} {}\r\n'.format(x, params['progname'], b) if x_i & (1 << b): expected_tita += "ta\r\n" else: @@ -298,7 +277,6 @@ def task_check(results, params): if results["tita_return"] == expected_tita: score += 2 else: - #hints += [u"program output incorrect\n" + results["tita_return"] + expected_tita] hints += ["program output incorrect\n" + results["tita_return"]] return score, hints @@ -306,10 +284,7 @@ def task_check(results, params): def prepare_disks(templates, task_params, global_params): import random import os - #print "Haha!" - #print params - #print templates - d = templates['student-entrance2'] + # first create the file contents to make it easyer to check. hidden_contents = task_params['magicstr'] r = random.Random(task_params['rndseed']) @@ -318,12 +293,15 @@ def prepare_disks(templates, task_params, global_params): x += "".join([r.choice("uiasdfghjkyxcvbnm1234567890ASDFGHJKYZXCVBNM") for i in range(60)]) x += r.choice(["lz", "1z", "Iz", "iz", "l2", "I2", "12"]) hidden_contents += x + "\n" + # create hidden file dir_list = ['Qlipper', 'Thunar', 'blender', 'autostart', 'kazam', 'mc', 'netsurf', 'pulse', 'qupzilla', 'radare2', 'teamviewer', 'texstudio', 'vlc'] ending_list = ['rc', '.conf', ''] start_list = ['net', 'dev', 'doc', 'lib', 'time', 'conf'] r.shuffle(dir_list) file_letters = ["mod", "co"] + + d = templates['student-entrance2'] for potential_dir in dir_list: try: potential_dir = os.path.join('/home/bilbo/.config', potential_dir) @@ -344,6 +322,3 @@ def prepare_disks(templates, task_params, global_params): # TODO create some additional files write_default_config(templates['simpleArbiterDhcpGW'], global_params) - # finish here - # rename - diff --git a/kpov_judge/tasks/isc_dhcp_live_boot/task.py b/kpov_judge/tasks/isc_dhcp_live_boot/task.py index c5ac728..38bbcd8 100644 --- a/kpov_judge/tasks/isc_dhcp_live_boot/task.py +++ b/kpov_judge/tasks/isc_dhcp_live_boot/task.py @@ -1,8 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - # TODO: dokoncaj! -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -161,10 +158,10 @@ def task(IP_DHCP, IP_GW, MAC_BOOT, BOOT_FNAME): def gen_params(user_id, params_meta): params = dict() r = random.Random(user_id) - net = kpov_random_helpers.IPv4_subnet_gen(r, '10.64.0.0/10', 24) - params['IP_DHCP'], params['IP_GW'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) - params['BOOT_FNAME'] = kpov_random_helpers.fname_gen(r) - params['TFTP_STRING'] = kpov_random_helpers.alnum_gen(r, 45) + net = kpov_util.IPv4_subnet_gen(r, '10.64.0.0/10', 24) + params['IP_DHCP'], params['IP_GW'] = kpov_util.IPv4_addr_gen(r, net, 2) + params['BOOT_FNAME'] = kpov_util.fname_gen(r) + params['TFTP_STRING'] = kpov_util.alnum_gen(r, 45) # IP_NM, DNS_NM, IP_static, DNS_static) return params diff --git a/kpov_judge/tasks/ldap_import/task.py b/kpov_judge/tasks/ldap_import/task.py index 0df173e..b46b432 100644 --- a/kpov_judge/tasks/ldap_import/task.py +++ b/kpov_judge/tasks/ldap_import/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -21,10 +18,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -35,10 +28,6 @@ computers = { 'disks': [ { 'name': 'maliBrezNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -48,12 +37,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcp', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -97,9 +81,9 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params diff --git a/kpov_judge/tasks/ldap_search/task.py b/kpov_judge/tasks/ldap_search/task.py index 886bf07..92a7223 100644 --- a/kpov_judge/tasks/ldap_search/task.py +++ b/kpov_judge/tasks/ldap_search/task.py @@ -1,10 +1,8 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +# kpov_util should be imported by add_assignment.py -# kpov_random_helpers should be imported by add_assignment.py # Poveži se na strežnik LDAP prek spletnega vmesnika. Ustvari uporabnika z danim imenom in geslom. # Napiši skripto, ki izpiše podatke o tem uporabniku z ldapsearch. -# + # TODO: finish this! instructions = { 'si':""" @@ -118,7 +116,7 @@ def task(LDAP_IP, DOMAIN, LDAP_USERNAME, LDAP_PASSWORD, BIND_USERNAME, BIND_PASS s = "ldapmodify -D {BIND_DN} -w {BIND_PASSWORD} -h {LDAP_IP}".format( **locals()) modify = pexpect.spawn(s) - FORTUNE = kpov_random_helpers.hostname_gen(random.Random(str(LDAP_USERNAME))) + FORTUNE = kpov_util.hostname_gen(random.Random(str(LDAP_USERNAME))) results['fortune'] = FORTUNE s1 = """ dn: cn={LDAP_USERNAME},ou=Users,{FULLDOMAIN} @@ -138,11 +136,11 @@ description: {FORTUNE} def gen_params(user_id, params_meta): params = dict() r = random.Random(user_id) - params['DOMAIN'] = kpov_random_helpers.hostname_gen(r) - params['LDAP_USERNAME'] = kpov_random_helpers.username_gen(r) - params['LDAP_PASSWORD'] = kpov_random_helpers.alnum_gen(r, 6) - params['BIND_USERNAME'] = kpov_random_helpers.username_gen(r) - params['BIND_PASSWORD'] = kpov_random_helpers.alnum_gen(r, 6) + params['DOMAIN'] = kpov_util.hostname_gen(r) + params['LDAP_USERNAME'] = kpov_util.username_gen(r) + params['LDAP_PASSWORD'] = kpov_util.alnum_gen(r, 6) + params['BIND_USERNAME'] = kpov_util.username_gen(r) + params['BIND_PASSWORD'] = kpov_util.alnum_gen(r, 6) return params def task_check(results, params): @@ -164,7 +162,7 @@ objectClass: organization\r score += 2 else: hints += ["LDAP_USERNAME missing in: " + s + str(results['ldapsearch_before'])] - fortune = kpov_random_helpers.hostname_gen(random.Random(str(params['LDAP_USERNAME']))) + fortune = kpov_util.hostname_gen(random.Random(str(params['LDAP_USERNAME']))) s = ".*cn: {0}.*description: {1}.*".format( re.escape(params['LDAP_USERNAME']), re.escape(fortune)) if re.match(s, results['ldapsearch_after'], re.DOTALL): diff --git a/kpov_judge/tasks/mock_entrance_exam/task.py b/kpov_judge/tasks/mock_entrance_exam/task.py index a6e3c8c..906df97 100644 --- a/kpov_judge/tasks/mock_entrance_exam/task.py +++ b/kpov_judge/tasks/mock_entrance_exam/task.py @@ -1,6 +1,3 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# # TODO: # - check if everything is filled in (computers, params, preparation) # - improve scoring @@ -136,51 +133,34 @@ params_meta = { def task(student_IP, net_prog_name, P_c, P_executable, arg_c, env_c, out_stderr_c, out_stdout_c, P_script, param_gen_seed): - from pexpect import pxssh import random - conn = pxssh.pxssh() - conn.login(student_IP, 'student', 'vaje') - results = dict() + r = random.Random(int(param_gen_seed)) env_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(11)]) - arg_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(13)]) stdin_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(17)]) - conn.sendline('ls -l {}'.format(P_script)) - conn.prompt() - results['script_ls'] = conn.before - conn.sendline('ls -l {}'.format(P_executable)) - conn.prompt() - results['executable_ls'] = conn.before - conn.sendline('export {}={}; {}'.format(env_c, env_val, P_script)) - conn.prompt() - results['script_run'] = conn.before - conn.sendline('cat {}'.format(out_stderr_c)) - conn.prompt() - results['script_stderr'] = conn.before - conn.sendline('cat {}'.format(out_stdout_c)) - conn.prompt() - results['script_stdout'] = conn.before - conn.sendline('echo "{}" | {} "{}" 2> /dev/null'.format(stdin_val, P_executable, arg_val)) - conn.prompt() - results['prog_stdout'] = conn.before - conn.sendline('echo "{}" | {} "{}" > /dev/null'.format(stdin_val, P_executable, arg_val)) - conn.prompt() - results['prog_stderr'] = conn.before - conn.logout() - return results + + return kpov_util.ssh_test(student_IP, 'student', 'vaje', ( + ('script_ls', 'ls -l {}'.format(P_script)), + ('executable_ls', 'ls -l {}'.format(P_executable)), + ('script_run', 'export {}={}; {}'.format(env_c, env_val, P_script)), + ('script_stderr', 'cat {}'.format(out_stderr_c)), + ('script_stdout', 'cat {}'.format(out_stdout_c)), + ('prog_stdout', 'echo "{}" | {} "{}" 2> /dev/null'.format(stdin_val, P_executable, arg_val)), + ('prog_stderr', 'echo "{}" | {} "{}" > /dev/null'.format(stdin_val, P_executable, arg_val)), + )) def gen_params(user_id, params_meta): import random r = random.Random(user_id+'evil cornholio') - params = kpov_random_helpers.default_gen(user_id, params_meta) + params = kpov_util.default_gen(user_id, params_meta) homedir = '/home/student/' params['env_c'] = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ') for i in range(5)]) params['P_c'] = "".join([r.choice('abcdefghijklmnoprst') for i in range(5)]) + ".c" params['param_gen_seed'] = str(r.randint(0, 2**24)) params['c_destroy_gen_seed'] = str(r.randint(0, 2**24)) - dest_net = kpov_random_helpers.IPv4_subnet_gen(r, '10.0.2.128/26', 26) - params['student_IP'] = kpov_random_helpers.IPv4_addr_gen(r, dest_net)[0] + dest_net = kpov_util.IPv4_subnet_gen(r, '10.0.2.128/26', 26) + params['student_IP'] = kpov_util.IPv4_addr_gen(r, dest_net)[0] for k in ['P_c', 'P_executable', 'out_stderr_c', 'P_script', 'out_stdout_c']: params[k] = homedir + params[k] return params @@ -209,6 +189,8 @@ def task_check(results, params): return(s_out, s_err, retval) score = 0 hints = [] + if results['ssh'] is not True: + hints += ['ssh failed: ' + results['ssh']] r = random.Random(int(params['param_gen_seed'])) env_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(11)]) arg_val = "".join([r.choice('ABCDEFGHIJKLMNPRSTUVZ012345') for i in range(13)]) diff --git a/kpov_judge/tasks/nat_port_forward/task.py b/kpov_judge/tasks/nat_port_forward/task.py index 2688268..8fe28d7 100644 --- a/kpov_judge/tasks/nat_port_forward/task.py +++ b/kpov_judge/tasks/nat_port_forward/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -19,10 +16,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -33,10 +26,6 @@ computers = { 'disks': [ { 'name': 'student-NATServer', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -46,12 +35,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiter', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -70,18 +54,15 @@ params_meta = { } def task(IP_TEST_CLIENT, IP_NAT, PORT_OUTER, PORT_INNER, NET): - import pexpect - from pexpect import pxssh - import re import random import time - # return None - peer_user = 'student' - peer_password = 'vaje' + import pexpect + from pexpect import pxssh + results = dict() - tcpdump = pexpect.spawn('sudo /usr/sbin/tcpdump src host {} and dst port {}'.format(IP_TEST_CLIENT, PORT_INNER)) - sshconn = pxssh.pxssh() - sshconn.login(IP_TEST_CLIENT, peer_user, peer_password) + tcpdump = pexpect.spawn('sudo /usr/sbin/tcpdump src host {} and dst port {}'.format(IP_TEST_CLIENT, PORT_INNER), encoding='utf-8') + sshconn = pxssh.pxssh(encoding='utf-8') + sshconn.login(IP_TEST_CLIENT, 'student', 'vaje') r = random.Random() k = r.randint(10, 15) results['pre_nc'] = str(k) @@ -92,7 +73,7 @@ def task(IP_TEST_CLIENT, IP_NAT, PORT_OUTER, PORT_INNER, NET): sshconn.sendintr() sshconn.prompt() results['nc_pre'] += sshconn.before - nc = pexpect.spawn('nc -l -p {}'.format(PORT_INNER)) + nc = pexpect.spawn('nc -l -p {}'.format(PORT_INNER), encoding='utf-8') sshconn.sendline() sshconn.prompt() sshconn.sendline("nc {} {}".format(IP_NAT, PORT_OUTER)) @@ -102,8 +83,8 @@ def task(IP_TEST_CLIENT, IP_NAT, PORT_OUTER, PORT_INNER, NET): sshconn.sendintr() nc.expect(pexpect.EOF) results['nc_ret'] = nc.before - results['route'] = pexpect.run('/sbin/ip route list 0/0') - results['traceroute'] = pexpect.run('traceroute {}'.format(IP_TEST_CLIENT)) + results['route'] = pexpect.run('ip route list 0/0', encoding='utf-8') + results['traceroute'] = pexpect.run('traceroute {}'.format(IP_TEST_CLIENT), encoding='utf-8') # wait for traceroute time.sleep(10) tcpdump.sendintr() @@ -118,21 +99,14 @@ def task(IP_TEST_CLIENT, IP_NAT, PORT_OUTER, PORT_INNER, NET): def gen_params(user_id, params_meta): params = dict() r = random.Random(user_id) - # IP_NM, DNS_NM, IP_static, DNS_static) params['PORT_INNER'] = str(r.randint(6000, 10000)) params['PORT_OUTER'] = str(r.randint(10001, 15000)) - params['NET'] = kpov_random_helpers.IPv4_subnet_gen(r, "10.36.0.0/14", 24) + params['NET'] = kpov_util.IPv4_subnet_gen(r, "10.36.0.0/14", 24) return params def task_check(results, params): import re import pickle - #if results is None: - # with open('bla.pickle') as f: - # results = cPickle.load(f) - #else: - # with open('bla.pickle', 'w') as f: - # cPickle.dump(results, f) score = 0 hints = [] local_net = params['NET'][:params['NET'].rfind('.')] diff --git a/kpov_judge/tasks/nat_vlc/task.py b/kpov_judge/tasks/nat_vlc/task.py index cf3947b..ffcb6c1 100644 --- a/kpov_judge/tasks/nat_vlc/task.py +++ b/kpov_judge/tasks/nat_vlc/task.py @@ -1,7 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +# kpov_util should be imported by add_assignment.py -# kpov_random_helpers should be imported by add_assignment.py # Poglej nek film na nekem določenem URL. # (?md5 vsota filma?) @@ -20,7 +18,7 @@ ustvarite še uporabnika {IP_NAT_user}. Poskrbi, da bo SimpleArbiter prek DHCP dobil naslov {IP_simple}. Poskrbi, da bo NATServer deloval kot prehod za SimpleArbiter in izvajal NAT. """, - 'en':""" + 'en':""" Set up two virtual machines - SimpleArbiter (using the disc simpleArbiter) and NATServer. NATServer should have two network adapters. Connect the first adapter to SimpleArbiter and the second adapter to the Internet. Configure the @@ -38,12 +36,7 @@ computers = { 'NATServer': { 'disks': [ { 'name': 'student-NATServer', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -53,17 +46,11 @@ computers = { 'disks': [ { 'name': 'simpleArbiter', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', 'config_drive': False - }, - } networks = { 'net1': {'public': False}, 'test-net': {'public': True} } @@ -77,24 +64,19 @@ params_meta = { } def task(IP_simple, IP_NAT, IP_NAT_user, IP_NAT_passwd): - from pexpect import pxssh import pexpect - results = dict() - # Connect to NAT - povezava = pxssh.pxssh() - povezava.login(IP_NAT,IP_NAT_user,IP_NAT_passwd) + + results = kpov_util.ssh_test(IP_NAT, IP_NAT_user, IP_NAT_passwd, ( + ('IP_NAT_ip_forward', 'cat /proc/sys/net/ipv4/ip_forward'), + )) + # Check if If IP_simple is connected to NAT - results['IP_simple_ping_to_NAT'] = pexpect.run('ping -c 5 {}'.format(IP_NAT)) + results['IP_simple_ping_to_NAT'] = pexpect.run('ping -c 5 {}'.format(IP_NAT), encoding='utf-8') # Check routing table on IP_simple - results['IP_simple_routing_table'] = pexpect.run('/sbin/route -n') + results['IP_simple_routing_table'] = pexpect.run('route -n', encoding='utf-8', env={'PATH': '/bin:/sbin'}) # Tracert Check if IP_simple is connected to internet - povezava.prompt() - results['IP_simple_to_internet'] = pexpect.run('/usr/sbin/traceroute 8.8.8.8') - povezava.prompt() - povezava.sendline('cat /proc/sys/net/ipv4/ip_forward') - povezava.prompt() - results['IP_NAT_ip_forward'] = povezava.before - povezava.logout() + results['IP_simple_to_internet'] = pexpect.run('traceroute 8.8.8.8', encoding='utf-8') + return results def gen_params(user_id, params_meta): @@ -102,12 +84,12 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) # dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_net_gen(r, 253, True, False) + net = kpov_util.IPv4_net_gen(r, 253, True, False) # params['DNS_NM'] = r.choice(dns_servers) - params['IP_NAT'], params['IP_simple'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) - params['IP_NAT_user'] = kpov_random_helpers.default_generators['username'](r) + params['IP_NAT'], params['IP_simple'] = kpov_util.IPv4_addr_gen(r, net, 2) + params['IP_NAT_user'] = kpov_util.default_generators['username'](r) # params['IP_NM'] - # params['IP_simple'] = kpov_random_helpers.IPv4_addr_gen(r, net, 1) + # params['IP_simple'] = kpov_util.IPv4_addr_gen(r, net, 1) # params['DNS_static'] = r.choice(dns_servers) return params @@ -121,8 +103,8 @@ def task_check(results, params): score += 3 else: hints.append("Ping to NAT incorrect") - if results['IP_NAT_ip_forward']=="cat /proc/sys/net/ipv4/ip_forward\r\n1\r\n": - score += 2 + if results['IP_NAT_ip_forward'].strip() == "1": + score += 2 else: hints.append("ip_forward not set on NAT?") rs = r"1 +{0} +\({0}\)".format(params['IP_NAT']) diff --git a/kpov_judge/tasks/network_boot_custom_program/task.py b/kpov_judge/tasks/network_boot_custom_program/task.py index db011c9..e81939f 100644 --- a/kpov_judge/tasks/network_boot_custom_program/task.py +++ b/kpov_judge/tasks/network_boot_custom_program/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -95,9 +92,9 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params diff --git a/kpov_judge/tasks/openvpn_multiple_hops/task.py b/kpov_judge/tasks/openvpn_multiple_hops/task.py index 5e54a1f..230393d 100644 --- a/kpov_judge/tasks/openvpn_multiple_hops/task.py +++ b/kpov_judge/tasks/openvpn_multiple_hops/task.py @@ -1,434 +1,317 @@ -#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-# kpov_random_helpers should be imported by add_assignment.py
-
-instructions = {
- 'si':"""
-Postavi 4 navidezne računalnike - SimpleArbiter z diska simpleArbiterDhcp, A, B ter C.
-Na računalnikih A, B in C ustvari uporabnika test z geslom test.
-Poskrbi, da bodo vsi štirje na istem navideznem fizičnem omrežju. Naslov omrežja (NET_PHYS) ter naslove
-(IP_A, IP_B, IP_C) preberi na SimpleArbiter. S pomočjo OpenVPN postavi navidezno omrežje med A in B na naslovih NET_VPN1.
-Nato s pomočjo OpenVPN postavi še navidezno omrežje med B in C na naslovih NET_VPN2.
-Poskrbi, da bo promet z A prek VPN prišel do C in obratno. Za avtentikacijo uporabi skupne skrivnosti, ki
-jih prebereš na SimpleArbiter - med A in B SECRET_AB ter med B in C SECRET_BC.
-"""
-}
-
-computers = {
- 'SimpleArbiter': {
- 'disks': [
- {
- 'name': 'simpleArbiterDhcp',
- }
- ],
- 'network_interfaces': [
- {
- 'network': 'nat'
- },
- {
- 'network': 'net1'
- }
- ],
- 'flavor': 'm1.tiny',
- 'config_drive': False
- },
- 'VPNClient1': {
- 'disks': [
- {
- 'name': 'student-VPNClient1',
- }
- ],
- 'network_interfaces': [
- {
- 'network': 'net1'
- },
- {
- 'network': 'vpnAB'
- }
- ],
- 'flavor': 'm1.tiny',
- 'config_drive': False
- },
- 'VPNClient2': {
- 'disks': [
- {
- 'name': 'student-VPNClient2',
- }
- ],
- 'network_interfaces': [
- {
- 'network': 'net1'
- },
- {
- 'network': 'vpnAB'
- },
- {
- 'network': 'vpnBC'
- }
- ],
- 'flavor': 'm1.tiny',
- 'config_drive': False
- },
- 'VPNClient3': {
- 'disks': [
- {
- 'name': 'student-VPNClient3',
- }
- ],
- 'network_interfaces': [
- {
- 'network': 'net1'
- },
- {
- 'network': 'vpnBC'
- }
- ],
- 'flavor': 'm1.tiny',
- 'config_drive': False
- }
-}
-
-networks = {
- 'nat': {
- 'public': True
- },
-
- 'net1': {
- 'public': True
- },
- # Used for VPN
- 'vpnAB': {
- 'public': False
- },
-
- 'vpnBC': {
- 'public': False
- }
-}
-#Tukaj sem generiral osem parametrov, prosil bi če se upoštevali pri Tasku.
-params_meta = {
- 'IP_VPNClient1': {'descriptions':{'si':'IP klienta A na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True},
- 'IP_LANClient1': {'descriptions':{'si':'IP klienta A na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False},
- 'IP1_VPNClient2': {'descriptions':{'si':'1. IP klienta B na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True},
- 'IP2_VPNClient2': {'descriptions':{'si':'2. IP klienta B na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True},
- 'IP_LANClient2': {'descriptions':{'si':'IP klienta B na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False},
- 'IP_VPNClient3': {'descriptions':{'si':'IP klienta C na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True},
- 'IP_LANClient3': {'descriptions':{'si':'IP klienta C na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False},
- 'IP_SimpleArbiterLAN': {'descriptions':{'si':'IP za SimpleArbiter na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False}
-}
-
-
-def task(IP_SimpleArbiterLAN, IP_VPNClient1, IP_LANClient1, IP1_VPNClient2, IP2_VPNClient2, IP_LANClient2, IP_VPNClient3, IP_LANClient3):
-
- 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 = 'test'
- peer_passwd = 'test'
-
- ###
- # 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
- )
-
- ######
- # Ukazi za A
- ######
-
- # ifconfig -a
- sC1.sendline('/sbin/ifconfig -a')
- sC1.prompt()
- results['VPNClient1_ifconfig'] = sC1.before
-
- # route -n
- sC1.sendline('/sbin/route -n')
- sC1.prompt()
- results['VPNClient1_route'] = sC1.before
-
- # ping C2
- sC1.sendline('ping -c 3 {}'.format(IP1_VPNClient2))
- sC1.prompt()
- results['VPNClient1_ping1_C2'] = sC1.before
-
- sC1.sendline('ping -c 3 {}'.format(IP2_VPNClient2))
- sC1.prompt()
- results['VPNClient1_ping2_C2'] = sC1.before
-
- # ping C3
- sC1.sendline('ping -c 3 {}'.format(IP_VPNClient3))
- sC1.prompt()
- results['VPNClient1_ping_C3'] = sC1.before
-
- # traceroute na C
-
- sC1.sendline('traceroute {}'.format(IP_VPNClient3))
- sC1.prompt()
- results['VPNClient1_traceroute_C3'] = sC1.before
-
- sC1.logout()
-
- ######
- # Ukazi za B
- ######
-
- # VPNClient2
- sC2 = pxssh.pxssh()
-
- sC2.login(
- IP_LANClient2,
- peer_user,
- peer_passwd
- )
-
-
- # ifconfig -a
- sC2.sendline('/sbin/ifconfig -a')
- sC2.prompt()
- results['VPNClient2_ifconfig'] = sC2.before
-
- # route -n
- sC2.sendline('/sbin/route -n')
- sC2.prompt()
- results['VPNClient2_route'] = sC2.before
-
- # ping C2
- sC2.sendline('ping -c 3 {}'.format(IP_VPNClient1))
- sC2.prompt()
- results['VPNClient2_ping_C1'] = sC2.before
-
- # ping C3
-
- sC2.sendline('ping -c 3 {}'.format(IP_VPNClient3))
- sC2.prompt()
- results['VPNClient2_ping_C3'] = sC2.before
-
- sC2.logout()
-
- ######
- # Ukazi za C
- ######
-
- # VPNClient3
- sC3 = pxssh.pxssh()
-
- sC3.login(
- IP_LANClient3,
- peer_user,
- peer_passwd
- )
-
- # ifconfig -a
- sC3.sendline('/sbin/ifconfig -a')
- sC3.prompt()
- results['VPNClient3_ifconfig'] = sC3.before
-
- # route -n
- sC3.sendline('/sbin/route -n')
- sC3.prompt()
- results['VPNClient3_route'] = sC3.before
-
- # ping C2
- sC3.sendline('ping -c 3 {}'.format(IP2_VPNClient2))
- sC3.prompt()
- results['VPNClient3_ping_C2'] = sC3.before
-
- # ping C3
- sC3.sendline('ping -c 3 {}'.format(IP_VPNClient1))
- sC3.prompt()
- results['VPNClient3_ping_C1'] = sC3.before
-
- # traceroute na C
- sC3.sendline('traceroute {}'.format(IP_VPNClient1))
- sC3.prompt()
- results['VPNClient3_traceroute_C1'] = sC3.before
-
- sC3.logout()
-
- return results
-
-def gen_params(user_id, params_meta):
- params = dict()
- import random
- r = random.Random(user_id)
- net = kpov_random_helpers.IPv4_subnet_gen(r, '10.70.0.0/16', 24)
- params['IP_VPNClient1'], params['IP1_VPNClient2'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2)
- net = kpov_random_helpers.IPv4_subnet_gen(r, '10.50.0.0/16', 24)
- params['IP_VPNClient3'], params['IP2_VPNClient2'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2)
- return params
-
-def task_check(results, params):
-
- import re
- score = 0
- hints = []
-
- IP_C1 = params['IP_VPNClient1'].replace('.', '\.')
- IP1_C2 = params['IP1_VPNClient2'].replace('.', '\.')
- IP2_C2 = params['IP2_VPNClient2'].replace('.', '\.')
- IP_C3 = params['IP_VPNClient3'].replace('.', '\.')
-
- # testi za ifconfig
- # C1
- rs = r"tun0.*\n.*inet.*{}".format(IP_C1)
- if re.search(rs,
- results['VPNClient1_ifconfig']):
- score += 1
- else:
- hints.append("ifconfig on VPNClient1 is not OK")
- pass
- # C2
- rs = r"tun.*\n.*inet.*{}".format(IP1_C2)
- if re.search(rs, results['VPNClient2_ifconfig']):
- rs = r"tun.*\n.*inet.*{}".format(IP2_C2)
- if re.search(rs, results['VPNClient2_ifconfig']):
- score += 1
- else:
- hints.append("ifconfig on VPNClient2 is not OK")
- pass
- else:
- hints.append("ifconfig on VPNClient2 is not OK")
- pass
- # C3
- rs = r"tun0.*\n.*inet.*{}".format(IP_C3)
- if re.search(rs, results['VPNClient3_ifconfig']):
- score += 1
- else:
- hints.append("ifconfig on VPNClient3 is not OK")
- pass
- # testi za route
- # C1
- rs = r"{}.*tun0".format(IP1_C2)
- if IP_C3[:-1].endswith('.'):
- ASD = IP_C3[:-1]+"0"
- elif IP_C3[:-2].endswith('.'):
- ASD = IP_C3[:-2]+"0"
- else:
- ASD = IP_C3[:-3]+"0"
- if re.search(rs, results['VPNClient1_route']):
- rs = r"{} {}.*tun0".format(ASD, IP1_C2)
- if re.search(rs, results['VPNClient1_route']):
- score += 1
- else:
- hints.append("route on VPNClient1 is not OK")
- else:
- hints.append("route on VPNClient1 is not OK")
- pass
- # C2
- rs = r"{}.*tun".format(IP_C1)
- if re.search(rs, results['VPNClient2_route']):
- rs = r"{}.*tun".format(IP_C3)
- if re.search(rs, results['VPNClient2_route']):
- score += 1
- else:
- hints.append("route on VPNClient2 is not OK")
- else:
- hints.append("route on VPNClient2 is not OK")
- pass
- # C3
- rs = r"{}.*tun0".format(IP2_C2)
- if IP_C1[:-1].endswith('.'):
- ASD = IP_C1[:-1]+"0"
- elif IP_C1[:-2].endswith('.'):
- ASD = IP_C1[:-2]+"0"
- else:
- ASD = IP_C1[:-3]+"0"
- if re.search(rs, results['VPNClient3_route']):
- rs = r"{} {}.*tun0".format(ASD, IP2_C2)
- if re.search(rs, results['VPNClient3_route']):
- score += 1
- else:
- hints.append("route on VPNClient3 is not OK")
- else:
- hints.append("route on VPNClient3 is not OK")
- pass
- # testi za ping
- # C1
- rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP1_C2)
- if re.search(rs, results['VPNClient1_ping1_C2']):
- score += 0.5
- else:
- hints.append("ping from VPNClient1 to VPNClient2 is not OK")
- pass
- rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C3)
- if re.search(rs, results['VPNClient1_ping_C3']):
- score += 0.5
- else:
- hints.append("ping from VPNClient1 to VPNClient3 is not OK")
- pass
- # C2
- rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C1)
- if re.search(rs, results['VPNClient2_ping_C1']):
- score += 0.5
- else:
- hints.append("ping from VPNClient2 to VPNClient1 is not OK")
- pass
- rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C3)
- if re.search(rs, results['VPNClient2_ping_C3']):
- score += 0.5
- else:
- hints.append("ping from VPNClient2 to VPNClient3 is not OK")
- pass
- # C3
- rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C1)
- if re.search(rs, results['VPNClient3_ping_C1']):
- score += 0.5
- else:
- hints.append("ping from VPNClient3 to VPNClient1 is not OK")
- pass
- rs = r"64 bytes from {}: icmp_seq=1 ttl=[0-9]+ time=\d+\.\d+ ms".format(IP2_C2)
- if re.search(rs, results['VPNClient3_ping_C2']):
- score += 0.5
- else:
- hints.append("ping from VPNClient3 to VPNClient2 is not OK")
- pass
- #score = int(score)
-
- # testi za tracetoute
- # C1
- rs = r"1 {}".format(IP1_C2)
- if re.search(rs, results['VPNClient1_traceroute_C3']):
- rs = r"2 {}".format(IP_C3)
- if re.search(rs, results['VPNClient1_traceroute_C3']):
- score += 1
- else:
- hints.append("traceroute from VPNClient1 to VPNClient3 is not OK")
- pass
- else:
- hints.append("traceroute from VPNClient1 to VPNClient3 is not OK")
- pass
- # C3
- rs = r"1 {}".format(IP2_C2)
- if re.search(rs, results['VPNClient3_traceroute_C1']):
- rs = r"2 {}".format(IP_C1)
- if re.search(rs, results['VPNClient3_traceroute_C1']):
- score += 1
- else:
- hints.append("traceroute from VPNClient1 to VPNClient3 is not OK")
- pass
- else:
- hints.append("traceroute from VPNClient1 to VPNClient3 is not OK")
- pass
- if score > 10 :
- score -= 1
- score = int(score)
- return score, hints
-
-
-def prepare_disks(templates, task_params, global_params):
- write_default_config(templates['simpleArbiterDhcp'], global_params)
-
-
+# kpov_util should be imported by add_assignment.py + +instructions = { + 'si':""" +Postavi 4 navidezne računalnike - SimpleArbiter z diska simpleArbiterDhcp, A, B ter C. +Na računalnikih A, B in C ustvari uporabnika test z geslom test. +Poskrbi, da bodo vsi štirje na istem navideznem fizičnem omrežju. Naslov omrežja (NET_PHYS) ter naslove +(IP_A, IP_B, IP_C) preberi na SimpleArbiter. S pomočjo OpenVPN postavi navidezno omrežje med A in B na naslovih NET_VPN1. +Nato s pomočjo OpenVPN postavi še navidezno omrežje med B in C na naslovih NET_VPN2. +Poskrbi, da bo promet z A prek VPN prišel do C in obratno. Za avtentikacijo uporabi skupne skrivnosti, ki +jih prebereš na SimpleArbiter - med A in B SECRET_AB ter med B in C SECRET_BC. +""" +} + +computers = { + 'SimpleArbiter': { + 'disks': [ + { + 'name': 'simpleArbiterDhcp', + } + ], + 'network_interfaces': [ + { + 'network': 'nat' + }, + { + 'network': 'net1' + } + ], + 'flavor': 'm1.tiny', + 'config_drive': False + }, + 'VPNClient1': { + 'disks': [ + { + 'name': 'student-VPNClient1', + } + ], + 'network_interfaces': [ + { + 'network': 'net1' + }, + { + 'network': 'vpnAB' + } + ], + 'flavor': 'm1.tiny', + 'config_drive': False + }, + 'VPNClient2': { + 'disks': [ + { + 'name': 'student-VPNClient2', + } + ], + 'network_interfaces': [ + { + 'network': 'net1' + }, + { + 'network': 'vpnAB' + }, + { + 'network': 'vpnBC' + } + ], + 'flavor': 'm1.tiny', + 'config_drive': False + }, + 'VPNClient3': { + 'disks': [ + { + 'name': 'student-VPNClient3', + } + ], + 'network_interfaces': [ + { + 'network': 'net1' + }, + { + 'network': 'vpnBC' + } + ], + 'flavor': 'm1.tiny', + 'config_drive': False + } +} + +networks = { + 'nat': { + 'public': True + }, + + 'net1': { + 'public': True + }, + # Used for VPN + 'vpnAB': { + 'public': False + }, + + 'vpnBC': { + 'public': False + } +} +#Tukaj sem generiral osem parametrov, prosil bi če se upoštevali pri Tasku. +params_meta = { + 'IP_VPNClient1': {'descriptions':{'si':'IP klienta A na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True}, + 'IP_LANClient1': {'descriptions':{'si':'IP klienta A na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False}, + 'IP1_VPNClient2': {'descriptions':{'si':'1. IP klienta B na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True}, + 'IP2_VPNClient2': {'descriptions':{'si':'2. IP klienta B na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True}, + 'IP_LANClient2': {'descriptions':{'si':'IP klienta B na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False}, + 'IP_VPNClient3': {'descriptions':{'si':'IP klienta C na VPN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': True}, + 'IP_LANClient3': {'descriptions':{'si':'IP klienta C na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False}, + 'IP_SimpleArbiterLAN': {'descriptions':{'si':'IP za SimpleArbiter na LAN'}, 'w': True, 'public': True, 'type': 'IP', 'generated': False} +} + + +def task(IP_SimpleArbiterLAN, IP_VPNClient1, IP_LANClient1, IP1_VPNClient2, IP2_VPNClient2, IP_LANClient2, IP_VPNClient3, IP_LANClient3): + tests = { + ('VPNClient1', IP_LANClient1): [ + ('VPNClient1_ping_C2', 'ping -c 3 {}'.format(IP1_VPNClient2)), + ('VPNClient1_ping_C3', 'ping -c 3 {}'.format(IP_VPNClient3)), + ('VPNClient1_traceroute_C3', 'traceroute {}'.format(IP_VPNClient3)), + ], + ('VPNClient2', IP_LANClient2): [ + ('VPNClient2_ping_C1', 'ping -c 3 {}'.format(IP_VPNClient1)), + ('VPNClient2_ping_C3', 'ping -c 3 {}'.format(IP_VPNClient3)), + ], + ('VPNClient3', IP_LANClient3): [ + ('VPNClient3_ping_C1', 'ping -c 3 {}'.format(IP_VPNClient1)), + ('VPNClient3_ping_C2', 'ping -c 3 {}'.format(IP2_VPNClient2)), + ('VPNClient3_traceroute_C1', 'traceroute {}'.format(IP_VPNClient1)), + ], + } + + for (name, host), host_tests in tests.items(): + host_tests += [ + (name+'_ifconfig', '/sbin/ifconfig -a'), + (name+'_route', '/sbin/route -n'), + ] + + results = collections.defaultdict(str) + for (name, host), host_tests in tests.items(): + results.update(kpov_util.ssh_test(host, 'test', 'test', host_tests)) + return results + +def gen_params(user_id, params_meta): + params = dict() + import random + r = random.Random(user_id) + net = kpov_util.IPv4_subnet_gen(r, '10.70.0.0/16', 24) + params['IP_VPNClient1'], params['IP1_VPNClient2'] = kpov_util.IPv4_addr_gen(r, net, 2) + net = kpov_util.IPv4_subnet_gen(r, '10.50.0.0/16', 24) + params['IP_VPNClient3'], params['IP2_VPNClient2'] = kpov_util.IPv4_addr_gen(r, net, 2) + return params + +def task_check(results, params): + + import re + score = 0 + hints = [] + + IP_C1 = params['IP_VPNClient1'].replace('.', '\.') + IP1_C2 = params['IP1_VPNClient2'].replace('.', '\.') + IP2_C2 = params['IP2_VPNClient2'].replace('.', '\.') + IP_C3 = params['IP_VPNClient3'].replace('.', '\.') + + # testi za ifconfig + # C1 + rs = r"tun0.*\n.*inet.*{}".format(IP_C1) + if re.search(rs, + results['VPNClient1_ifconfig']): + score += 1 + else: + hints.append("ifconfig on VPNClient1 is not OK") + pass + # C2 + rs = r"tun.*\n.*inet.*{}".format(IP1_C2) + if re.search(rs, results['VPNClient2_ifconfig']): + rs = r"tun.*\n.*inet.*{}".format(IP2_C2) + if re.search(rs, results['VPNClient2_ifconfig']): + score += 1 + else: + hints.append("ifconfig on VPNClient2 is not OK") + pass + else: + hints.append("ifconfig on VPNClient2 is not OK") + pass + # C3 + rs = r"tun0.*\n.*inet.*{}".format(IP_C3) + if re.search(rs, results['VPNClient3_ifconfig']): + score += 1 + else: + hints.append("ifconfig on VPNClient3 is not OK") + pass + # testi za route + # C1 + rs = r"{}.*tun0".format(IP1_C2) + if IP_C3[:-1].endswith('.'): + ASD = IP_C3[:-1]+"0" + elif IP_C3[:-2].endswith('.'): + ASD = IP_C3[:-2]+"0" + else: + ASD = IP_C3[:-3]+"0" + if re.search(rs, results['VPNClient1_route']): + rs = r"{} {}.*tun0".format(ASD, IP1_C2) + if re.search(rs, results['VPNClient1_route']): + score += 1 + else: + hints.append("route on VPNClient1 is not OK") + else: + hints.append("route on VPNClient1 is not OK") + pass + # C2 + rs = r"{}.*tun".format(IP_C1) + if re.search(rs, results['VPNClient2_route']): + rs = r"{}.*tun".format(IP_C3) + if re.search(rs, results['VPNClient2_route']): + score += 1 + else: + hints.append("route on VPNClient2 is not OK") + else: + hints.append("route on VPNClient2 is not OK") + pass + # C3 + rs = r"{}.*tun0".format(IP2_C2) + if IP_C1[:-1].endswith('.'): + ASD = IP_C1[:-1]+"0" + elif IP_C1[:-2].endswith('.'): + ASD = IP_C1[:-2]+"0" + else: + ASD = IP_C1[:-3]+"0" + if re.search(rs, results['VPNClient3_route']): + rs = r"{} {}.*tun0".format(ASD, IP2_C2) + if re.search(rs, results['VPNClient3_route']): + score += 1 + else: + hints.append("route on VPNClient3 is not OK") + else: + hints.append("route on VPNClient3 is not OK") + pass + # testi za ping + # C1 + rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP1_C2) + if re.search(rs, results['VPNClient1_ping_C2']): + score += 0.5 + else: + hints.append("ping from VPNClient1 to VPNClient2 is not OK") + pass + rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C3) + if re.search(rs, results['VPNClient1_ping_C3']): + score += 0.5 + else: + hints.append("ping from VPNClient1 to VPNClient3 is not OK") + pass + # C2 + rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C1) + if re.search(rs, results['VPNClient2_ping_C1']): + score += 0.5 + else: + hints.append("ping from VPNClient2 to VPNClient1 is not OK") + pass + rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C3) + if re.search(rs, results['VPNClient2_ping_C3']): + score += 0.5 + else: + hints.append("ping from VPNClient2 to VPNClient3 is not OK") + pass + # C3 + rs = r"64 bytes from {}: icmp_seq=[0-9]+ ttl=[0-9]+ time=\d+\.\d+ ms".format(IP_C1) + if re.search(rs, results['VPNClient3_ping_C1']): + score += 0.5 + else: + hints.append("ping from VPNClient3 to VPNClient1 is not OK") + pass + rs = r"64 bytes from {}: icmp_seq=1 ttl=[0-9]+ time=\d+\.\d+ ms".format(IP2_C2) + if re.search(rs, results['VPNClient3_ping_C2']): + score += 0.5 + else: + hints.append("ping from VPNClient3 to VPNClient2 is not OK") + pass + #score = int(score) + + # testi za tracetoute + # C1 + rs = r"1 {}".format(IP1_C2) + if re.search(rs, results['VPNClient1_traceroute_C3']): + rs = r"2 {}".format(IP_C3) + if re.search(rs, results['VPNClient1_traceroute_C3']): + score += 1 + else: + hints.append("traceroute from VPNClient1 to VPNClient3 is not OK") + pass + else: + hints.append("traceroute from VPNClient1 to VPNClient3 is not OK") + pass + # C3 + rs = r"1 {}".format(IP2_C2) + if re.search(rs, results['VPNClient3_traceroute_C1']): + rs = r"2 {}".format(IP_C1) + if re.search(rs, results['VPNClient3_traceroute_C1']): + score += 1 + else: + hints.append("traceroute from VPNClient1 to VPNClient3 is not OK") + pass + else: + hints.append("traceroute from VPNClient1 to VPNClient3 is not OK") + pass + if score > 10 : + score -= 1 + score = int(score) + return score, hints + + +def prepare_disks(templates, task_params, global_params): + write_default_config(templates['simpleArbiterDhcp'], global_params) diff --git a/kpov_judge/tasks/openvpn_simple_smb/task.py b/kpov_judge/tasks/openvpn_simple_smb/task.py index 2db4337..d4bb510 100644 --- a/kpov_judge/tasks/openvpn_simple_smb/task.py +++ b/kpov_judge/tasks/openvpn_simple_smb/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -45,12 +42,7 @@ computers = { 'disks': [ { 'name': 'simpleArbiterDhcpGWVPN', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [ { @@ -67,10 +59,6 @@ computers = { 'disks': [ { 'name': 'student-VPNClient1', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [ { @@ -91,6 +79,7 @@ networks = { '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}, @@ -100,62 +89,44 @@ params_meta = { '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): - + import collections 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() + results = collections.defaultdict(str) - # 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 - ) + sC1 = pxssh.pxssh(encoding='utf-8') + sC1.login(IP_LANClient1, 'student', 'vaje') - ###### # sA - ###### - results['SimpleArbiter_ifconfig'] = pexpect.run( - '/sbin/ifconfig -a') - + 'ifconfig -a', encoding='utf-8', env={'PATH': '/bin:/sbin'}) results['SimpleArbiter_route'] = pexpect.run( - '/sbin/route -n') + 'route -n', encoding='utf-8', env={'PATH': '/bin:/sbin'}) # 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)) + 'ping -c 3 {}'.format(IP_VPNClient1), encoding='utf-8') results['SimpleArbiter_traceroute'] = pexpect.run( - '/usr/bin/traceroute {}'.format(IP_VPNClient1)) + 'traceroute {}'.format(IP_VPNClient1), encoding='utf-8') 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)) + 'sudo mount {}:/home/test/{} /mnt'.format(IP_VPNClient1, DIRNAME), encoding='utf-8') results['SimpleArbiter_mount_result'] = pexpect.run( - 'sudo mount') + 'sudo mount', encoding='utf-8') results['SimpleArbiter_ls'] = pexpect.run( - 'ls /mnt') + 'ls /mnt', encoding='utf-8') pexpect.run( - 'sudo umount /mnt') + 'sudo umount /mnt', encoding='utf-8') + # Ping the VPN server sC1.sendline('ping -c 3 {0}'.format( IP_SimpleArbiterVPN )) sC1.prompt() @@ -169,10 +140,8 @@ def task(IP_SimpleArbiterVPN, IP_VPNClient1, IP_LANClient1, DIRNAME): sC1.prompt() results['VPNClient1_ps'] = sC1.before sC1.logout() - - - return results + return results def gen_params(user_id, params_meta): params = dict() @@ -181,107 +150,79 @@ def gen_params(user_id, params_meta): #(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) + net = kpov_util.IPv4_subnet_gen(r, '10.168.0.0/16', 24) + params['IP_VPNClient1'], params['IP_SimpleArbiterVPN'] = kpov_util.IPv4_addr_gen(r, net, 2) + params['DIRNAME'] = kpov_util.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']) + rs = r"tap0: flags=.* mtu 1500\r\n +inet {}".format(IP_SA) 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), + "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']): + 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" + '{}:/home/test/{} on /mnt type nfs'.format( + params['IP_VPNClient1'], params['DIRNAME'])): 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 range(32)]) + s = "\n".join(["".join([r.choice("0123456789abcdef") for i in range(32)]) for i in range(16)]) - keyfile = kpov_random_helpers.fname_gen(r, extension=False) + keyfile = kpov_util.fname_gen(r, extension=False) + # now check the filenames fnames_ok = True for i in range(3): - fname = kpov_random_helpers.fname_gen(r, False) - foo = kpov_random_helpers.fortune(r, 4096) + fname = kpov_util.fname_gen(r, False) + foo = kpov_util.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), + "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']): + 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 @@ -289,11 +230,7 @@ def task_check(results, params): 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 @@ -308,7 +245,7 @@ def prepare_disks(templates, task_params, global_params): {} -----END OpenVPN Static key V1----- """.format(s) - keyfile = kpov_random_helpers.fname_gen(r, extension=False) + ".key" + keyfile = kpov_util.fname_gen(r, extension=False) + ".key" templates['simpleArbiterDhcpGWVPN'].write("/etc/openvpn/secret.key", s) netaddr_s = """auto tap0 iface tap0 inet static @@ -319,14 +256,11 @@ iface tap0 inet static """.format(task_params['IP_SimpleArbiterVPN']) templates['simpleArbiterDhcpGWVPN'].write_append("/etc/network/interfaces", netaddr_s) for i in range(3): - fname = kpov_random_helpers.fname_gen(r, False) + fname = kpov_util.fname_gen(r, False) templates['simpleArbiterDhcpGWVPN'].write( "/srv/smb/" + fname + '.txt', - kpov_random_helpers.fortune(r, 4096)) + kpov_util.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) - - - diff --git a/kpov_judge/tasks/openwrt/task.py b/kpov_judge/tasks/openwrt/task.py index 057fb96..ed2783a 100644 --- a/kpov_judge/tasks/openwrt/task.py +++ b/kpov_judge/tasks/openwrt/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -18,10 +15,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -32,10 +25,6 @@ computers = { 'disks': [ { 'name': 'maliBrezNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -45,12 +34,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcp', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -94,9 +78,9 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params diff --git a/kpov_judge/tasks/public_ip_ssh/task.py b/kpov_judge/tasks/public_ip_ssh/task.py index a566aa5..561a1fa 100644 --- a/kpov_judge/tasks/public_ip_ssh/task.py +++ b/kpov_judge/tasks/public_ip_ssh/task.py @@ -1,9 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# bson.son.SON an -# kpov_random_helpers should be imported by add_assignment.py -OrderedDict = SON +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -39,21 +34,19 @@ def task(peer_ip, peer_user, peer_passwd): return dict() def gen_params(user_id, params_meta): - return kpov_random_helpers.default_gen(user_id, params_meta) + return kpov_util.default_gen(user_id, params_meta) def task_check(results, params): from pexpect import pxssh - import pexpect - results = dict() - s = pxssh.pxssh() - peer_ip, peer_user, peer_passwd = params['peer_ip'], params['peer_user'], params['peer_passwd'] + ip, user, passwd = params['peer_ip'], params['peer_user'], params['peer_passwd'] + results = {} try: - s.login(peer_ip, peer_user, peer_passwd) + s = pxssh.pxssh(encoding='utf-8') + s.login(ip, user, passwd) s.logout() - except Exception as e: - return 0, [str(e)] - return 10, [] + return 10, [] + except Exception as ex: + return 0, [str(ex)] def prepare_disks(templates, task_params, global_params): write_default_config(templates['simpleArbiter'], global_params) - # print d1.ls('/') diff --git a/kpov_judge/tasks/public_ssh_motd_http/task.py b/kpov_judge/tasks/public_ssh_motd_http/task.py index df6ba32..227425a 100644 --- a/kpov_judge/tasks/public_ssh_motd_http/task.py +++ b/kpov_judge/tasks/public_ssh_motd_http/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -18,10 +15,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -32,10 +25,6 @@ computers = { 'disks': [ { 'name': 'maliBrezNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -45,12 +34,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcp', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -94,9 +78,9 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params diff --git a/kpov_judge/tasks/radius_multiple_realms/task.py b/kpov_judge/tasks/radius_multiple_realms/task.py index c879d56..773a3f2 100644 --- a/kpov_judge/tasks/radius_multiple_realms/task.py +++ b/kpov_judge/tasks/radius_multiple_realms/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -24,10 +21,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -38,10 +31,6 @@ computers = { 'disks': [ { 'name': 'maliBrezNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -51,12 +40,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcp', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -100,9 +84,9 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params diff --git a/kpov_judge/tasks/radius_mysql_pam/task.py b/kpov_judge/tasks/radius_mysql_pam/task.py index a3f86f7..72b5a74 100644 --- a/kpov_judge/tasks/radius_mysql_pam/task.py +++ b/kpov_judge/tasks/radius_mysql_pam/task.py @@ -1,6 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -58,10 +56,6 @@ computers = { 'disks': [ { 'name': 'student-RadiusServer', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -71,12 +65,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcpGW', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -97,20 +86,23 @@ params_meta = { 'MYSQL_SEED':{'descriptions': {'si': 'seed', 'en': 'seed'}, 'w': False, 'public':True, 'type': None, 'generated': True}, } -def task(IP_RS, RADIUS_SECRET, RADIUS_USERNAME, RADIUS_PASSWORD, MYSQL_DB_NAME, MYSQL_ADMIN_USER, MYSQL_ADMIN_PASSWORD, MYSQL_SEED): - from pexpect import pxssh - import pexpect +def task(IP_RS, RADIUS_SECRET, RADIUS_USERNAME, RADIUS_PASSWORD, + MYSQL_DB_NAME, MYSQL_ADMIN_USER, MYSQL_ADMIN_PASSWORD, MYSQL_SEED): + import collections import random - results = dict() - peer_user = 'student' - peer_passwd = 'vaje' + import pexpect + r = random.Random(MYSQL_SEED) - MYSQL_TEST_USER = kpov_random_helpers.username_gen(r) - MYSQL_TEST_PASSWORD = kpov_random_helpers.alnum_gen(r, 7) - RADIUS_NEW_PASSWORD = kpov_random_helpers.alnum_gen(r, 7) - # Testiranje radius strtežnika + MYSQL_TEST_USER = kpov_util.username_gen(r) + MYSQL_TEST_PASSWORD = kpov_util.alnum_gen(r, 7) + RADIUS_NEW_PASSWORD = kpov_util.alnum_gen(r, 7) + + results = collections.defaultdict(str) + + # Testiranje radius strežnika results['Test_RadiusServer'] = pexpect.run('radtest {0} {1} {2} 1812 {3}'.format( RADIUS_USERNAME, RADIUS_PASSWORD, IP_RS, RADIUS_SECRET)) + # Testiranje podatkovne base mysql mysql = pexpect.spawn('mysql -u {MYSQL_ADMIN_USER} -p{MYSQL_ADMIN_PASSWORD} -h {IP_RS}'.format(**locals())) mysql.expect("mysql>") @@ -123,33 +115,36 @@ def task(IP_RS, RADIUS_SECRET, RADIUS_USERNAME, RADIUS_PASSWORD, MYSQL_DB_NAME, results['select_from_users'] = mysql.before mysql.sendline("INSERT INTO radcheck (UserName, Attribute, Value, Op) VALUES ('{MYSQL_TEST_USER}', 'Cleartext-Password', '{MYSQL_TEST_PASSWORD}', ':=');".format(**locals())) mysql.expect("mysql>") + results['radtest_OK'] = pexpect.run('radtest {0} {1} {2} 1812 {3}'.format( MYSQL_TEST_USER, MYSQL_TEST_PASSWORD, IP_RS, RADIUS_SECRET)) results['radtest_NOK'] = pexpect.run('radtest {0} {1} {2} 1812 {3}'.format( MYSQL_TEST_USER, "Flügzeug", IP_RS, RADIUS_SECRET)) results['radtest_NOK'] = pexpect.run('radtest {0} {1} {2} 1812 {3}'.format( MYSQL_TEST_USER, "Flügzeug", IP_RS, RADIUS_SECRET)) - sT = pxssh.pxssh() + mysql.sendline("UPDATE radcheck SET value='{RADIUS_NEW_PASSWORD}' where UserName='{RADIUS_USERNAME}' and Attribute='Cleartext-Password';".format(**locals())) - sT.login(IP_RS, RADIUS_USERNAME, RADIUS_NEW_PASSWORD) - results['login_test'] = sT.before + + results.update(kpov_util.ssh_test(IP_RS, RADIUS_USERNAME, RADIUS_NEW_PASSWORD)) + mysql.sendline("UPDATE radcheck SET value='{RADIUS_PASSWORD}' where UserName='{RADIUS_USERNAME}' and Attribute='Cleartext-Password';".format(**locals())) mysql.expect('mysql>') mysql.sendline("DELETE FROM radcheck where UserName='{MYSQL_TEST_USER}' and Attribute='Cleartext-Password';".format(**locals())) mysql.expect('mysql>') mysql.sendline('\q'); - # Testiranje PAM s testnim uporabnikom + # TODO Testiranje PAM s testnim uporabnikom + return results def gen_params(user_id, params_meta): params = dict() r = random.Random(user_id) - params['RADIUS_SECRET'] = kpov_random_helpers.alnum_gen(r, 8) - params['RADIUS_PASSWORD'] = kpov_random_helpers.alnum_gen(r, 8) - params['RADIUS_USERNAME'] = kpov_random_helpers.username_gen(r) - params['MYSQL_ADMIN_USER'] = kpov_random_helpers.alnum_gen(r, 6) - params['MYSQL_ADMIN_PASSWORD'] = kpov_random_helpers.alnum_gen(r, 6) - params['MYSQL_DB_NAME'] = kpov_random_helpers.alnum_gen(r, 4) + params['RADIUS_SECRET'] = kpov_util.alnum_gen(r, 8) + params['RADIUS_PASSWORD'] = kpov_util.alnum_gen(r, 8) + params['RADIUS_USERNAME'] = kpov_util.username_gen(r) + params['MYSQL_ADMIN_USER'] = kpov_util.alnum_gen(r, 6) + params['MYSQL_ADMIN_PASSWORD'] = kpov_util.alnum_gen(r, 6) + params['MYSQL_DB_NAME'] = kpov_util.alnum_gen(r, 4) params['MYSQL_SEED'] = str(r.random()) return params @@ -159,9 +154,9 @@ def task_check(results, params): score = 0 hints = [] r = random.Random(params['MYSQL_SEED']) - MYSQL_TEST_USER = kpov_random_helpers.username_gen(r) - MYSQL_TEST_PASSWORD = kpov_random_helpers.alnum_gen(r, 7) - RADIUS_NEW_PASSWORD = kpov_random_helpers.alnum_gen(r, 7) + MYSQL_TEST_USER = kpov_util.username_gen(r) + MYSQL_TEST_PASSWORD = kpov_util.alnum_gen(r, 7) + RADIUS_NEW_PASSWORD = kpov_util.alnum_gen(r, 7) s = r"Sent Access-Request Id [0-9]+ from ([0-9]|\.)+:[0-9]+ to {IP_RS}:1812 length [0-9]+\r\n\tUser-Name = \"{RADIUS_USERNAME}\"\r\n\tUser-Password = \"{RADIUS_PASSWORD}\".*Access-Accept Id [0-9]+ from {IP_RS}".format(**params) #with open('test.pickle', 'w') as f: # pickle.dump({'pattern': s, 'res': results['Test_RadiusServer']}, f) @@ -209,8 +204,8 @@ def task_check(results, params): else: hints.append('radtest negative output incorrect: ' + results['radtest_NOK']) print((results['radtest_NOK'], s)) - s = "{RADIUS_USERNAME}@.*:~\\$".format(**params) - if re.search(s, results['login_test'], flags=re.DOTALL): + s = "{RADIUS_USERNAME}@.*:".format(**params) + if re.search(s, results['motd'], flags=re.DOTALL): # print "login_test OK" score += 1 else: @@ -220,4 +215,3 @@ def task_check(results, params): def prepare_disks(templates, task_params, global_params): write_default_config(templates['simpleArbiterDhcpGW'], global_params) - diff --git a/kpov_judge/tasks/rdate_64bit/task.py b/kpov_judge/tasks/rdate_64bit/task.py index 87de002..b08cddc 100644 --- a/kpov_judge/tasks/rdate_64bit/task.py +++ b/kpov_judge/tasks/rdate_64bit/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -19,10 +16,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -33,10 +26,6 @@ computers = { 'disks': [ { 'name': 'maliBrezNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -46,12 +35,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcp', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -95,9 +79,9 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params diff --git a/kpov_judge/tasks/rename_grep_network/task.py b/kpov_judge/tasks/rename_grep_network/task.py index e8ce0b2..4f8f1ad 100644 --- a/kpov_judge/tasks/rename_grep_network/task.py +++ b/kpov_judge/tasks/rename_grep_network/task.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# # TODO: # - check if everything is filled in (computers, params, preparation) # - improve scoring # - test # - switch to a real SSH/SFTP client to properly handle filenames - instructions = { 'si': """ Ustvari dva navidezna računalnika s slikama diskov @@ -139,26 +135,6 @@ params_meta = { 'generated': True, }, - # 'progname': { - # 'descriptions': { - # 'si': 'Ime programa', - # 'en': 'Program filename', - # }, - # 'w': False, - # 'public': True, - # 'type': 'filename', - # 'generated': True, - # }, - 'pubseed': { - 'descriptions': { - 'si': 'Nekaj nepredvidenega', - 'en': 'A random seed', - }, - 'w': False, - 'public': True, - 'type': None, - 'generated': True, - }, 'rndseed': { 'descriptions': { 'si': 'random seed za skrito datoteko', @@ -171,47 +147,25 @@ params_meta = { }, } -def task(testip, testuser, passwd, mntdir, magicstr, pubseed): - from pexpect import pxssh - import random - target = pxssh.pxssh() - target.login(testip, testuser, passwd) - target.sendline('ls ~/') - target.prompt() - home_ls = target.before - target.sendline('cat ~/*I*.txt') - target.prompt() - dst_file_contents = target.before - target.sendline('ls -l ~/*I*.txt') - target.prompt() - dst_ls = target.before - target.sendline('mount') - target.prompt() - mnt = target.before - results = { - 'home_ls': home_ls, - 'dst_ls': dst_ls, - 'mnt': mnt, - 'dst_file_contents': dst_file_contents, - } - target.logout() - return results +def task(testip, testuser, passwd, mntdir, magicstr): + return kpov_util.ssh_test(testip, testuser, passwd, ( + ('home_ls', 'ls ~/'), + ('dst_file_contents', 'cat ~/*I*.txt'), + ('dst_ls', 'ls -l ~/*I*.txt'), + ('mnt', 'mount'), + )) def gen_params(user_id, params_meta): import random params = dict() r = random.Random(user_id) - params['testip'] = kpov_random_helpers.IPv4_addr_gen(r, + params['testip'] = kpov_util.IPv4_addr_gen(r, network = '10.94.80.0/19', n_generated=1)[0] - params['testuser'] = kpov_random_helpers.default_generators['username'](r) - params['passwd'] = kpov_random_helpers.alnum_gen(r, 8) + params['testuser'] = kpov_util.default_generators['username'](r) + params['passwd'] = kpov_util.alnum_gen(r, 8) params['magicstr'] = "".join([r.choice("qwerztlpoQWERTPOL") for i in range(10)]) - params['mntdir'] = "/" + kpov_random_helpers.default_generators['filename'](r) - # params['progname'] = kpov_random_helpers.default_generators['filename'](r) - # while params['dstfile'] == params['progname']: - # params['progname'] = kpov_random_helpers.default_generators['filename'](r) - params['pubseed'] = kpov_random_helpers.alnum_gen(r, 8) - params['rndseed'] = kpov_random_helpers.alnum_gen(r, 8) + params['mntdir'] = "/" + kpov_util.default_generators['filename'](r) + params['rndseed'] = kpov_util.alnum_gen(r, 8) return params @@ -220,6 +174,8 @@ def task_check(results, params): import re hints = [] score = 0 + if results['ssh'] is not True: + hints += ['ssh failed: ' + results['ssh']] hidden_contents = params['magicstr'] r = random.Random(params['rndseed']) dstfile = "".join([r.choice("qQoOp") for i in range(64)]) + "I.txt" @@ -238,11 +194,10 @@ def task_check(results, params): # r"pokakalz\r", # hidden_contents, # re.MULTILINE) - expected_contents = "cat ~/*I*.txt\r\n".format(dstfile) + expected_contents if results["dst_file_contents"] == expected_contents: score += 3 else: - diff_pos = "" + diff_pos = (0, "") for i, c in enumerate(results["dst_file_contents"]): if len(expected_contents) < i or c != expected_contents[i]: start = max(0, i-10) @@ -250,9 +205,8 @@ def task_check(results, params): diff_pos = (i, results["dst_file_contents"][start:end]) break hints += ["wrong file contents\n" + str(diff_pos[1])] - #hints += ["wrong file contents"] params['dstfile'] = dstfile - expected_dst_ls = "ls -l ~/\\*I\\*.txt\r\n-rw--w---- 1 {testuser} bilbo .*{dstfile}\r\n".format(**params) + expected_dst_ls = "-rw--w---- 1 {testuser} bilbo .*{dstfile}".format(**params) if re.match(expected_dst_ls, results["dst_ls"]): score += 2 else: @@ -275,10 +229,7 @@ def task_check(results, params): def prepare_disks(templates, task_params, global_params): import random import os - #print "Haha!" - #print params - #print templates - d = templates['smallstudent-personal'] + # first create the file contents to make it easyer to check. hidden_contents = task_params['magicstr'] r = random.Random(task_params['rndseed']) @@ -288,6 +239,7 @@ def prepare_disks(templates, task_params, global_params): x += "".join([r.choice("uiasdfghjkyxcvbnm1234567890ASDFGHJKYZXCVBNM") for i in range(60)]) x += r.choice(["lz", "1z", "Iz", "iz", "l2", "I2", "12"]) hidden_contents += x + "\n" + # create hidden file dir_list = ['Qlipper', 'Thunar', 'blender', 'autostart', 'kazam', 'mc', 'netsurf', 'pulse', 'qupzilla', 'radare2', 'teamviewer', 'texstudio', 'vlc'] ending_list = ['rc', '.conf', '', '.txt'] @@ -296,6 +248,8 @@ def prepare_disks(templates, task_params, global_params): start_list.append("".join([r.choice("qQoOp") for i in range(64)]) + "O") r.shuffle(dir_list) file_letters = ["mod", "co"] + + d = templates['smallstudent-personal'] d.mkdir('/mnt/.hideme') d.mkdir('/media/.hideme') for potential_dir in dir_list: @@ -326,6 +280,3 @@ def prepare_disks(templates, task_params, global_params): # TODO create some additional files # write_default_config(templates['simpleArbiterDhcpGW'], global_params) - # finish here - # rename - diff --git a/kpov_judge/tasks/set_ip_dhcp_hostname/task.py b/kpov_judge/tasks/set_ip_dhcp_hostname/task.py index f68c71b..77648e6 100644 --- a/kpov_judge/tasks/set_ip_dhcp_hostname/task.py +++ b/kpov_judge/tasks/set_ip_dhcp_hostname/task.py @@ -1,8 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# TODO: finish thi -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -84,9 +80,9 @@ def task(IP_DHCP, Hostname_DHCP, IP_static, MAC_static, IP_dhcp_static): def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) - params['IP_DHCP'], params['IP_static'], params['IP_dhcp_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 3) - params['Hostname_DHCP'] = kpov_random_helpers.hostname_gen(r) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + params['IP_DHCP'], params['IP_static'], params['IP_dhcp_static'] = kpov_util.IPv4_addr_gen(r, net, 3) + params['Hostname_DHCP'] = kpov_util.hostname_gen(r) return params def task_check(results, params): diff --git a/kpov_judge/tasks/set_ip_static_dhcp/task.py b/kpov_judge/tasks/set_ip_static_dhcp/task.py index 0553585..aac93f7 100644 --- a/kpov_judge/tasks/set_ip_static_dhcp/task.py +++ b/kpov_judge/tasks/set_ip_static_dhcp/task.py @@ -1,7 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +# kpov_util should be imported by add_assignment.py -# kpov_random_helpers should be imported by add_assignment.py instructions = { 'si':""" Ustvari tri navidezne racunalnike. Za prvega @@ -34,10 +32,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -48,10 +42,6 @@ computers = { 'disks': [ { 'name': 'maliBrezNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -61,12 +51,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcpGW', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -84,41 +69,27 @@ params_meta = { } def task(IP_NM, DNS_NM, IP_static, DNS_static): - from pexpect import pxssh - import pexpect - results = dict() - peer_user = 'student' - peer_passwd = 'vaje' - # sA - network manager - sA = pxssh.pxssh() - sA.login(IP_NM, peer_user, peer_passwd) - sA.sendline('nmcli -c no d') - sA.prompt() - results['NM_nmcli'] = sA.before - sA.sendline('nslookup www.arnes.si') - sA.prompt() - results['NM_nslookup'] = sA.before - sA.logout() - # sB - brez network manager - sB = pxssh.pxssh() - sB.login(IP_static, peer_user, peer_passwd) - sB.sendline('nmcli -c no d') - sB.prompt() - results['static_nmcli'] = sB.before - sB.sendline('nslookup www.arnes.si') - sB.prompt() - results['static_nslookup'] = sB.before - sB.logout() + import collections + + tests = ( + ('nmcli', 'nmcli -c no d'), + ('nslookup', 'nslookup www.arnes.si'), + ) + + results = collections.defaultdict(str) + for name, host in [('nm', IP_NM), ('static', IP_static)]: + host_results = kpov_util.ssh_test(host, 'student', 'vaje', tests) + for key, value in host_results.items(): + results[key+'-'+name] = value return results def gen_params(user_id, params_meta): params = dict() r = random.Random(user_id) - # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '10.94.96.0/19', 25) + net = kpov_util.IPv4_subnet_gen(r, '10.94.96.0/19', 25) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params @@ -126,29 +97,31 @@ def task_check(results, params): import re score = 0 hints = [] - #print results, params - if results['NM_nslookup'].find(params['DNS_NM']) > -1: - # print "NM_nslookup OK" + if results['ssh-nm'] is True: + score += 1 + else: + hints += ['mali ssh failed: ' + results['ssh-nm']] + if results['ssh-static'] is True: + score += 1 + else: + hints += ['malibrez ssh failed: ' + results['ssh-static']] + if params['DNS_NM'] in results['nslookup-nm']: score += 2 else: hints += ['NM nslookup incorrect'] - if results['static_nslookup'].find(params['DNS_static']) > -1: - # print "static_nslookup OK" + if params['DNS_static'] in results['nslookup-static']: score += 2 else: hints += ['static nslookup incorrect'] - if re.search(r'e(th0|np0s3|ns3) +ethernet +connected', results['NM_nmcli']): - # print "NM_nmcli OK" - score += 3 + if re.search(r'e(th0|np0s3|ns3) +ethernet +connected', results['nmcli-nm']): + score += 2 else: hints += ['nmcli incorrect'] - if re.search(r'e(th0|np0s3|ns3) +ethernet +unmanaged', results['static_nmcli']): - # print "static_nmcli OK" - score += 3 + if re.search(r'e(th0|np0s3|ns3) +ethernet +unmanaged', results['nmcli-static']): + score += 2 else: hints += ['nmcli on malibrez incorrect'] return score, hints def prepare_disks(templates, task_params, global_params): write_default_config(templates['simpleArbiterDhcpGW'], global_params) - diff --git a/kpov_judge/tasks/set_motd/task.py b/kpov_judge/tasks/set_motd/task.py index eadcca7..f2b65fb 100644 --- a/kpov_judge/tasks/set_motd/task.py +++ b/kpov_judge/tasks/set_motd/task.py @@ -1,9 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# bson.son.SON an -# kpov_random_helpers should be imported by add_assignment.py -# OrderedDict = SON +# kpov_util should be imported by add_assignment.py instructions = { "si":""" @@ -76,35 +71,23 @@ params_meta = { def task(peer_ip, peer_user, peer_passwd, niz): "Check whether ssh works" - from pexpect import pxssh - import pexpect - # return {"hello": 'kitty'} - results = dict() - s = pxssh.pxssh() - #TODO (polz): tole bi utegnilo delovati http://pexpect.sourceforge.net/pxssh.html. Testirajte - s.login (peer_ip, peer_user, peer_passwd, original_prompt=r'{0}@.*:\~\$'.format(peer_user),auto_prompt_reset=False) - # print s.before - # s.prompt() - #Ce na serverju iz datoteke /var/run/motd.dynamic pobrisemo znak '#' bi moralo delovati. - - # temp = s.before # print everything before the prompt. - #TODO (polz): tole ni pravi pristop. Problem je bil v tem, da pxssh ni prav zaznal, kdaj je prijavljen. Glej link zgoraj. - results['motd'] = s.before # print everything before the prompt. - return results - # - + return kpov_util.ssh_test(peer_ip, peer_user, peer_passwd) + def gen_params(user_id, params_meta): - return kpov_random_helpers.default_gen(user_id, params_meta) + return kpov_util.default_gen(user_id, params_meta) def task_check(results, params): - #print task_url - #print params - #print results niz = params['niz'] score = 0 hints = [] - if (results['motd'].find(niz) > -1): - score += 10 + if results['ssh'] is True: + score += 2 + else: + hints += ['ssh failed: ' + results['ssh']] + if niz in results['motd']: + score += 8 + else: + hints += ['wrong motd:\n' + results['motd'] + '\n'] return score, hints def prepare_disks(templates, task_params, global_params): diff --git a/kpov_judge/tasks/smb_nfs/task.py b/kpov_judge/tasks/smb_nfs/task.py index 5ea7695..a94d677 100644 --- a/kpov_judge/tasks/smb_nfs/task.py +++ b/kpov_judge/tasks/smb_nfs/task.py @@ -1,7 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +# kpov_util should be imported by add_assignment.py -# kpov_random_helpers should be imported by add_assignment.py # TODO: dokoncaj! instructions = { 'si':""" @@ -29,10 +27,6 @@ computers = { 'disks': [ { 'name': 'student-fileserver', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -42,12 +36,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcpGW', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -84,8 +73,8 @@ def task(FILESERVER_IP, FILESERVER_NAME, NFS_MOUNT, SMB_SHARENAME, SHARED_FILE_S results['ls_smbmount'] = pexpect.run('ls /mnt/smb') results['ls_nfs'] = pexpect.run('ls /mnt/nfs') r = random.Random(SHARED_FILE_SEED) - testfile = kpov_random_helpers.fname_gen(r) - teststring = kpov_random_helpers.alnum_gen(r, 200) + testfile = kpov_util.fname_gen(r) + teststring = kpov_util.alnum_gen(r, 200) with open('/mnt/nfs/{}'.format(testfile),'w') as f: f.write(teststring) results['filestr'] = pexpect.run( @@ -99,22 +88,22 @@ def task(FILESERVER_IP, FILESERVER_NAME, NFS_MOUNT, SMB_SHARENAME, SHARED_FILE_S return results def gen_params(user_id, params_meta): - d = kpov_random_helpers.default_gen(user_id, params_meta) + d = kpov_util.default_gen(user_id, params_meta) r = random.Random(user_id) - d['FILESERVER_NAME'] = kpov_random_helpers.hostname_gen(r) - d['SMB_SHARENAME'] = kpov_random_helpers.hostname_gen(r) - d['NFS_MOUNT'] = "/srv/nfs/" + kpov_random_helpers.fname_gen(r, False) - d['SHARED_FILENAME'] = kpov_random_helpers.fname_gen(r) - d['SHARED_CONTENT'] = kpov_random_helpers.fortune(r, 4096) - d['SHARED_FILE_SEED'] = kpov_random_helpers.alnum_gen(r, 42) + d['FILESERVER_NAME'] = kpov_util.hostname_gen(r) + d['SMB_SHARENAME'] = kpov_util.hostname_gen(r) + d['NFS_MOUNT'] = "/srv/nfs/" + kpov_util.fname_gen(r, False) + d['SHARED_FILENAME'] = kpov_util.fname_gen(r) + d['SHARED_CONTENT'] = kpov_util.fortune(r, 4096) + d['SHARED_FILE_SEED'] = kpov_util.alnum_gen(r, 42) return d def task_check(results, params): score = 0 hints = [] r = random.Random(params['SHARED_FILE_SEED']) - testfile = kpov_random_helpers.fname_gen(r) - teststring = kpov_random_helpers.alnum_gen(r, 200) + testfile = kpov_util.fname_gen(r) + teststring = kpov_util.alnum_gen(r, 200) # no need to check results['mount'] or results['try_mount_nfs'] # or results['try_mount_smb'] if results['mount_after'].find('//{}/{} on /mnt/smb type cifs'.format( diff --git a/kpov_judge/tasks/snmp_agent_uptime/task.py b/kpov_judge/tasks/snmp_agent_uptime/task.py index c636549..7b3143c 100644 --- a/kpov_judge/tasks/snmp_agent_uptime/task.py +++ b/kpov_judge/tasks/snmp_agent_uptime/task.py @@ -1,7 +1,5 @@ - #!/usr/bin/env python -# -*- coding: utf-8 -*- +# kpov_util should be imported by add_assignment.py -# kpov_random_helpers should be imported by add_assignment.py # TODO: finish this. instructions = { 'si':""" @@ -42,20 +40,14 @@ Set it up on SNMPClient in the home directory of the user test. Make all the data available over SNMP readable by the "studentje" community. """ - } - computers = { 'SNMPClient': { 'disks': [ { 'name': 'student-SNMPClient', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -65,10 +57,6 @@ computers = { 'disks': [ { 'name': 'student-SNMPServer', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -79,12 +67,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcpGWSNMP', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -154,13 +137,13 @@ def gen_params(user_id, params_meta): import random params = dict() r = random.Random(user_id) - # You can also create an OID creation function in kpov_random_helpers. + # You can also create an OID creation function in kpov_util. # this should probably return params_meta #<== Aleksander Fujs 6310020 ==> - params['SNMP_VALUE'] = kpov_random_helpers.alnum_gen(r, 64) + params['SNMP_VALUE'] = kpov_util.alnum_gen(r, 64) params['SNMP_UPTIME_OID'] = 'NET-SNMP-EXTEND-MIB::nsExtendOutLine."{}".1'.format( - kpov_random_helpers.hostname_gen(r)) + kpov_util.hostname_gen(r)) params['SNMP_CLIENT_OID'] = '1.3.6.1.4.1.8072.2.9999.9999.{}'.format( r.randint(0, 255)) #<== Aleksander Fujs 6310020 ==> diff --git a/kpov_judge/tasks/snmp_alarms_interfaces/task.py b/kpov_judge/tasks/snmp_alarms_interfaces/task.py index 516cc69..f1e8d62 100644 --- a/kpov_judge/tasks/snmp_alarms_interfaces/task.py +++ b/kpov_judge/tasks/snmp_alarms_interfaces/task.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# kpov_random_helpers should be imported by add_assignment.py +# kpov_util should be imported by add_assignment.py instructions = { 'si':""" @@ -22,10 +19,6 @@ computers = { 'disks': [ { 'name': 'maliNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -36,10 +29,6 @@ computers = { 'disks': [ { 'name': 'maliBrezNetworkManager', }, - #{ 'name': 'CDROM', - # 'options':{'readonly': True}, - # 'parts': [],# no parts, no mounting. - #} ], 'network_interfaces': [{'network': 'net1'}], 'flavor': 'm1.tiny', @@ -49,12 +38,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiterDhcp', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'net1'}, {'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -98,9 +82,9 @@ def gen_params(user_id, params_meta): r = random.Random(user_id) # IP_NM, DNS_NM, IP_static, DNS_static) dns_servers = ['193.2.1.66', '193.2.1.72', '8.8.8.8', '8.8.4.4', '208.67.222.222', '208.67.220.220'] - net = kpov_random_helpers.IPv4_subnet_gen(r, '172.23.128.0/18', 24) + net = kpov_util.IPv4_subnet_gen(r, '172.23.128.0/18', 24) params['DNS_NM'] = r.choice(dns_servers) - params['IP_NM'], params['IP_static'] = kpov_random_helpers.IPv4_addr_gen(r, net, 2) + params['IP_NM'], params['IP_static'] = kpov_util.IPv4_addr_gen(r, net, 2) params['DNS_static'] = r.choice(dns_servers) return params @@ -121,4 +105,3 @@ def task_check(results, params): def prepare_disks(templates, task_params, global_params): write_default_config(templates['simpleArbiterDhcp'], global_params) - diff --git a/kpov_judge/tasks/vlc_stream_rtp/task.py b/kpov_judge/tasks/vlc_stream_rtp/task.py index 5c8011b..bfdfb4f 100644 --- a/kpov_judge/tasks/vlc_stream_rtp/task.py +++ b/kpov_judge/tasks/vlc_stream_rtp/task.py @@ -1,7 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +# kpov_util should be imported by add_assignment.py -# kpov_random_helpers should be imported by add_assignment.py # Postavi nek film na Internet tako, da ga bodo lahko ostali videli. # TODO: finish this @@ -37,12 +35,7 @@ computers = { 'SimpleArbiter': { 'disks': [ { 'name': 'simpleArbiter', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -51,12 +44,7 @@ computers = { 'StudentVLC': { 'disks': [ { 'name': 'student-VLC', - # attempt automount }, - #{ 'name': 'CDROM', - # 'options': {'readonly': True}, - # 'parts': [{'dev': 'b1', 'path': '/cdrom'}], - #}, ], 'network_interfaces': [{'network': 'test-net'}], 'flavor': 'm1.tiny', @@ -79,17 +67,16 @@ def task(NASLOV, TOK): results['ps'] = pexpect.run('ps xa') results['tcpdump_hex'] = pexpect.run('sudo /usr/sbin/tcpdump -x -c 2 dst host 239.255.255.255 and port 9875'.format(NASLOV)) results['tcpdump'] = pexpect.run('sudo /usr/sbin/tcpdump -c 8 dst host {}'.format(NASLOV)) - # print("HAHA") return results def gen_params(user_id, params_meta): params = dict() r = random.Random(user_id) - net = kpov_random_helpers.IPv4_net_gen(r, min_hosts = 16, + net = kpov_util.IPv4_net_gen(r, min_hosts = 16, local=True, multicast=True) - params['NASLOV'] = kpov_random_helpers.IPv4_addr_gen(r, net, 1)[0] + params['NASLOV'] = kpov_util.IPv4_addr_gen(r, net, 1)[0] params['PORT'] = str(r.randint(5000, 6000)) - params['TOK'] = kpov_random_helpers.hostname_gen(r) + params['TOK'] = kpov_util.hostname_gen(r) return params def task_check(results, params): diff --git a/kpov_judge/test_prepare_disks.py b/kpov_judge/test_prepare_disks.py index 7564d6d..33f2479 100755 --- a/kpov_judge/test_prepare_disks.py +++ b/kpov_judge/test_prepare_disks.py @@ -1,9 +1,8 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +#!/usr/bin/env python3 import sys import inspect -import kpov_random_helpers +import kpov_util import guestfs import os import glob diff --git a/kpov_judge/test_task.py b/kpov_judge/test_task.py index ad33b15..63df973 100755 --- a/kpov_judge/test_task.py +++ b/kpov_judge/test_task.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +#!/usr/bin/env python3 +import collections import getpass import io import yaml @@ -10,7 +10,7 @@ import os import inspect import sys from bson.son import SON -import kpov_random_helpers +import kpov_util import random import argparse import locale @@ -95,9 +95,9 @@ def locate_task(params, argparser, quiet=False): if not quiet: params = get_params(params, url_meta) # then the student's ID (and password if neccessarry) - fetch_params_meta = { + fetch_params_meta = collections.OrderedDict({ 'username': {'descriptions': {'si': 'Uporabniško ime', 'en': 'Username'}}, - } + }) if params['task_url'] is not None and ( params['task_url'].startswith('http')): fetch_params_meta['password'] = {'descriptions': {'si': 'Geslo', 'en': 'Password'}, } diff --git a/kpov_judge/web/kpov_judge/kpov_judge.py b/kpov_judge/web/kpov_judge/kpov_judge.py index 64fa235..6e94f05 100755 --- a/kpov_judge/web/kpov_judge/kpov_judge.py +++ b/kpov_judge/web/kpov_judge/kpov_judge.py @@ -7,7 +7,7 @@ import json import random import settings import datetime -import kpov_random_helpers +import kpov_util from kpov_draw_setup import draw_setup import traceback |