File: swan-prep

package info (click to toggle)
libreswan 5.2-2.4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 81,656 kB
  • sloc: ansic: 129,988; sh: 32,018; xml: 20,646; python: 10,303; makefile: 3,022; javascript: 1,506; sed: 574; yacc: 511; perl: 264; awk: 52
file content (727 lines) | stat: -rwxr-xr-x 28,637 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
#!/usr/bin/python3
#
# This script is run by a VM host (eg "west") to prepare itself for testing

import os
import sys
import socket
import shutil
import subprocess
import pexpect
import glob
from pathlib import Path
import re
import argparse
from enum import Enum

test_hosts = ["east", "west", "road", "north", "nic"]

def path_touch(dst, mode=None):
    if mode: #it is seems unhappy with mode=None
        Path(dst).touch(mode)
    else:
        Path(dst).touch()

def rsync_ap(src, dst, timer=20):

    cmd = "/usr/bin/rsync --delete -q -aP"
    cmd += " %s %s" % (src, dst)

    try:
        output = subprocess.check_output(cmd, shell=True, timeout=timer, stderr=subprocess.STDOUT)
    except subprocess.TimeoutExpired:
        print( "EXCEPTION TIMEOUT ? cmd %s , cwd %s" % (os.getcwd(), cmd))
    except subprocess.CalledProcessError as e:
         print ("EXCEPTION ? cwd %s , %s %s" % (os.getcwd(), cmd, e.output))

def mount_bind(src, dst, mode=None, touch_src_file=False, mkdir_src=False, wipe_old_dst=False, fatal=True):

    if touch_src_file and mkdir_src:
        print("conflicting options touch_src_file and mkdir_src");

    if mkdir_src and not os.path.isdir(src) and not touch_src_file:
        os.makedirs(src)

    if touch_src_file :
        path_touch(src, mode)

    if wipe_old_dst:
        wipe_old(dst)

    if os.path.isdir(src):
        if not os.path.isdir(dst) and not os.path.islink(dst):
            os.makedirs(dst)
    elif os.path.isfile(src):
        if not os.path.isfile(dst) and not os.path.islink(dst):
            path_touch(dst, mode)
    else:
        mode_str = ''
        if mode:
            mode_str = "mode 0o%o" % mode
        print("mount_bind unknown action src=%s dst=%s %s"
                 % (src, dst, mode_str))
        if fatal:
            sys.exit(1)
        return True

    cmd = ['/bin/mount', '--bind',  src, dst]
    o = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
                        encoding='utf-8')
    if o.returncode:
        print("mount_bind failed %s" % cmd)
        if fatal:
            sys.exit(1)

    return o.returncode

def lsw_init_dir(src, dst):
    if args.namespace:
        return mount_bind(src, dst, mkdir_src=True,  wipe_old_dst=True, fatal=True)
    else:
        os.makedirs(dst, exist_ok=True)
    return

def lsw_cp_file(src, dst, mode=None, nsbasepath=''):

    if args.namespace:
        ns_dst="%s/%s" %(nsbasepath, dst) #copy to local NS/hostname/<path> then mount
        shutil.copy(src, ns_dst)
        if mode:
            os.chmod(ns_dst, mode)
        mount_bind(ns_dst, dst)
    else:
        shutil.copy(src, dst)
        if mode:
            os.chmod(dst, mode)
    return

def umount(dst):
   if os.path.islink(dst):
        os.unlink(dst)
   else:
        cmd = "umount %s" % dst
        subprocess.run(cmd, shell=True, capture_output=True, encoding="ascii",
                        check=True)

def umount_all(dst):
    o = subprocess.run("mount", shell=True, capture_output=True, encoding="ascii", check=True)
    for line in o.stdout.splitlines():
        mdst = line.split(' ')[2]
        if mdst == dst:
            umount(dst)

def wipe_old(dst):
    if args.namespace:
        umount_all(dst)
    elif os.path.islink(dst) or os.path.isfile(dst):
        os.unlink(dst)
    elif os.path.isdir(dst):
        shutil.rmtree(dst)
    # else: #no existing file
    #   print("cannot wipe unknown type %s" % dst)

def shell(command, out=False):
    """Run command as a sub-process and report failures"""
    if args.verbose:
        print(command)
    status, output = subprocess.getstatusoutput(command)
    if status:
        print(("command '%s' failed with status %d: %s" %
               (command, status, output)))
    elif (args.verbose or out) and output:
        print(output)
    return output

def choose_config_file(hostname, testpath, config_path, strict):
    (config_absdir, config_file) = os.path.split(config_path)
    if os.path.isabs(config_absdir):
        config_dir = config_absdir[1:] # drop slash; better?
    else:
        config_dir = config_absdir
    # extension contains the dot
    (config_base, extension) = os.path.splitext(config_file)

    # pass 1: look in the test directory, reject ambiguous files.
    # When exact, don't match HOSTNAME.EXTENSION.
    paths = []
    paths.append((False, os.path.join(testpath, hostname + "." + config_file)))
    paths.append((True, os.path.join(testpath, hostname + extension)))
    paths.append((None, os.path.join(testpath, config_file)))
    path = None
    for fuzzy, p in paths:
        if os.path.isfile(p):
            if strict is True and fuzzy is True:
                # strict so ignore fuzzy match
                continue
            if strict is False and fuzzy is False:
                # non-strict should not match HOSTNAME.CONFIG_FILE
                sys.exit("config file %s conflicts with %s" % (p, hostname + extension))
            if path:
                sys.exit("conflicting files %s %s in test directory" % (p, path))
            path = p
    if path:
        return path

    # pass 2: look in base configs
    if userland in ("libreswan", "openswan",  "strongswan"):
        # what about BSD?
        paths = []
        paths.append(os.path.join("/testing/baseconfigs", hostname, config_dir, config_file))
        paths.append(os.path.join("/testing/baseconfigs/all/", config_dir, config_file))
        for path in paths:
            if os.path.isfile(path):
                return path

    # dump all the paths?
    return None

def get_configsetup(key=None):
    # without --config /dev/null most tests would pass.
    # However, the test that follows a test with broken config will fail
    # And during a testrun the worker that hit error may not recover.
    cmd = '$(ipsec addconn --configsetup --config /dev/null | grep ' + key + ') && echo $' + key
    o = subprocess.run(cmd, shell=True, capture_output=True, encoding="ascii", check=True,)
    return o.stdout.strip().replace("'", '')

def copy_config_file(hostname, testpath, config_path, strict=False, optional=False, nsprefix=""):
    src = choose_config_file(hostname, testpath, config_path, strict)
    if src:
        # config_absdir has a leading / so below is always valid
        dst = nsprefix + config_path
        dstdir = os.path.dirname(dst)
        if not os.path.isdir(dstdir):
            os.mkdir(dstdir)
        # When NS DST=<host>/NS/<test>/CONFIG_PATH
        shutil.copy(src, dst)
        # Now mount DST=<host>/NS/<test>/CONFIG_PATH over CONFIGI_PATH
        if nsprefix: # non-None and non-Empty
            mount_bind(dst, config_path);
    elif not optional:
        print("ERROR: %s's %s not found" % (hostname, config_path))

# prevent double installs from going unnoticed
if os.path.isfile("/usr/libexec/ipsec/pluto"):
    if os.path.isfile("/usr/local/libexec/ipsec/pluto"):
        sys.exit("\n\n---------------------------------------------------------------------\n"
                 "ABORT: found a swan userland in the base system as well as /usr/local\n"
                 "---------------------------------------------------------------------\n")

parser = argparse.ArgumentParser(description='swan-prep arguments')
exclusive_grp_dnsserver = parser.add_mutually_exclusive_group()

parser.add_argument('--testpath', '-t', action='store',
                    default=os.getcwd(), help="Test directory full path %s " % os.getcwd())
parser.add_argument('--hostname', '-H', action='store',
                    default='', help='The name of the host to prepare as')
# we should get this from the testparams.sh file?
parser.add_argument('--userland', '-u', action='store',
                    default='libreswan', help='which userland to prepare')
parser.add_argument('--strongswan-version', action='store',
                    default='', help='strongswan version expect')

class Keys(Enum):
    X509 = 'x509'
    HOST = 'host'
    NONE = 'none'
parser.add_argument('--keys',
                    choices=[Keys.X509, Keys.HOST, Keys.NONE], default=None,
                    help='create an NSS database containing X.509, host, or no keys')
parser.add_argument('--nokeys',
                    action='store_const', dest='keys', const=Keys.NONE,
                    help='create an empty NSS database')
parser.add_argument('--hostkeys',
                    action='store_const', dest='keys', const=Keys.HOST,
                    help="create an NSS database containing the host keys")
parser.add_argument('--x509keys', '-x', '--x509',
                    action='store_const', dest='keys', const=Keys.X509,
                    help='create an NSS database containing X.509 certificates and private keys')

nsspassword="s3cret"
parser.add_argument('--nsspw', action='store_true',
                    help='set the security password on the NSS database to '+nsspassword)

parser.add_argument('--x509name', '-X', action='store', default="",
                    help='create X509 NSS file by importing test certs')
parser.add_argument('--certchain', '-c', action='store_true',
                    help='import the ca-chain test certificates into the NSS database')

parser.add_argument('--fips', '-f', action='store_true',
                    help='prepare /etc/ipsec.d for running in FIPS mode')

exclusive_grp_dnsserver.add_argument('--dnssec', '-d', action='store_true',
                    help='start nsd and unbound for DNSSEC - meant only for nic')

parser.add_argument('--46', '--64', action='store_true',
                    help='Do not disable IPv6. Default is disable IPv6 ', dest='ipv46', default=False)
parser.add_argument('--verbose', '-v', action='store_true',
                    help='more verbose')
parser.add_argument('--namespace', action='store_true',
        default='', help='Running inside name sapace')

args = parser.parse_args()

if args.hostname:
    hostname = args.hostname
else:
    hostname = socket.gethostname()

if "." in hostname:
    hostname = hostname.split(".")[0]

# Validate this is sane?
testpath = args.testpath
if not os.path.isdir(testpath):
    sys.exit("Unknown or bad testpath '%s'" % args.testname)

testname = os.path.basename(testpath)

# dnssec is only run on nic, but nic isn't supposed to run swan-prep
# ever :/ when using namespaces, nic has no eth0
if not args.dnssec:
    o = subprocess.run(['ip' , '-o', 'link' , 'show', 'dev', 'eth0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="ascii")
    ifname = o.stdout.split(' ')[1]
    if o.returncode:
        print("cannot find eht0. test guest expect eth0. --no-eth0 to disable this check\n%s\n%s" % i (o.output, o.stderr))
        sys.exit(1)

# nsrun set magic string SWAN_PLUTOTEST=YES in the environment
# to identify namespace
# echo $SWAN_PLUTOTEST
if "SWAN_PLUTOTEST" in os.environ:
    args.namespace = True
elif not args.namespace:
    o = subprocess.run('ip netns identify', shell=True, capture_output=True, encoding="ascii", check=True,)
    namespace = o.stdout
    namespace_expect = hostname + '-' + testname
    if re.search(hostname, namespace):
        args.namespace = True

resolve_conf = "/etc/resolv.conf"
etc_hosts = "/etc/hosts"

if hostname != "nic":
    nssdir = get_configsetup("nssdir")
    ipsecdir = get_configsetup("ipsecdir")
    configfile = get_configsetup("configfile")
    secretsfile = get_configsetup("secretsfile")

if args.namespace:
    nsbasepath ="%s/NS/%s" % (testpath, hostname) #will create testpath/NS/hostname/*
    if not os.path.isdir(nsbasepath):
        os.makedirs(nsbasepath)
else:
    nsbasepath = ''

# Setup pluto.log softlink and bindmount in namespace
if hostname != "nic":
    subprocess.run(["ipsec", "stop"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="ascii") # gentle try before wiping files and killall

    outputdir = "%s/OUTPUT/" % testpath
    if not os.path.isdir(outputdir):
        os.mkdir(outputdir)
        os.chmod(outputdir, 0o777)

    if args.userland in ("libreswan", "openswan"):
        dname = "pluto"
    elif args.userland == "strongswan":
        dname = "charon"
    else:
        dname = "iked"

    daemonlogfile = "%s/%s.%s.log" % (outputdir, hostname, dname)
    tmplink = "/tmp/%s.log" % dname
    wipe_old(tmplink)

    Path(daemonlogfile).touch(mode=0o777)

    if args.namespace :
        mount_bind(daemonlogfile, tmplink, touch_src_file=True)
    else :
        os.symlink(daemonlogfile, tmplink)

if args.userland:
    if not args.userland in ("libreswan", "strongswan", "openswan"):
        sys.exit("swan-prep: unknown userland type '%s'" % args.userland)
    userland = args.userland
else:
    userland = "libreswan"

# print "swan-prep running on %s for test %s with userland
# %s"%(hostname,testname,userland)

if hostname != "nic":
    # wipe or unmount any old configs
    # do not clean pid files or files opened by pluto, charon .. yet.
    wipe_old(configfile)
    wipe_old(secretsfile)
    wipe_old(nssdir)
    if nssdir != ipsecdir:
        wipe_old(ipsecdir)
    wipe_old("/etc/strongswan")

if args.namespace:
    wipe_old(resolve_conf)
    wipe_old(etc_hosts)

# if using systemd, ensure we don't restart pluto on crash
if os.path.isfile("/lib/systemd/system/ipsec.service") and not args.namespace:
    service = "".join(open("/lib/systemd/system/ipsec.service").readlines())
    if "Restart=always" in service:
        fp = open("/lib/systemd/system/ipsec.service", "w")
        fp.write("".join(service).replace("Restart=always", "Restart=no"))
    # always reload to avoid "service is masked" errors
    subprocess.getoutput("/bin/systemctl daemon-reload")

# AA_201902 what happens to audit log namespace
# we have to cleanup the audit log or we could get entries from previous test
if os.path.isfile("/var/log/audit/audit.log"):
    fp = open("/var/log/audit/audit.log", "w")
    fp.close()
    if os.path.isfile("/lib/systemd/system/auditd.service"):
        subprocess.getoutput("/bin/systemctl restart auditd.service")

# disable some daemons that could cause noise packets getting encrypted
if not args.namespace :
    subprocess.getoutput("/bin/systemctl stop chronyd")
    subprocess.getoutput("/bin/systemctl stop sssd")

# work around for ACQUIRE losing sub-type, causing false positive test results
subprocess.getoutput('sysctl net.ipv4.ping_group_range="1 0"')

# ensure cores are just dropped, not sent to aobrt-hook-ccpp or systemd.
# setting /proc/sys/kernel/core_pattern to "core" or a pattern does not
# work. And you cannot use shell redirection ">". So we hack it with "tee"
pattern = "|/usr/bin/tee /tmp/core.%h.%e.%p"
fp = open("/proc/sys/kernel/core_pattern", "w")
fp.write(pattern)
fp.close()

if hostname != "nic":
    dst = "/etc/strongswan/" if userland == "strongswan" else ipsecdir
    src = "%s%s" % (nsbasepath, dst)
    lsw_init_dir(src, dst)

    if args.userland in ("libreswan", "openswan"):
        dst = "/run/pluto"
        if nssdir and ipsecdir != nssdir:
            src = "%s%s" % (nsbasepath, nssdir)
            lsw_init_dir(src, nssdir)
    elif args.userland in ("strongswan"):
        dst="/run/strongswan"
    elif args.namespace:
        print("Unknown run directory fatal in namespace")
        sys.exit(1)
    src = "%s%s" % (nsbasepath, dst)
    lsw_init_dir(src, dst)

    if args.userland in ("libreswan", "openswan"):

        # fill in any missing dirs
        for dir in ("/etc/ipsec.d/policies", "/etc/ipsec.d/cacerts", "/etc/ipsec.d/crls", "/etc/ipsec.d/certs", "/etc/ipsec.d/private"):
            if not os.path.isdir(dir):
                os.mkdir(dir)
                if "private" in dir:
                    os.chmod(dir, 0o700)
            else:
                oldfiles = glob.glob("%s/*.der"%dir) + glob.glob("%s/*.crt"%dir) + glob.glob("%s/*.pem"%dir) + glob.glob("%s/*.key"%dir)
                for oldfile in oldfiles:
                    os.unlink(oldfile)

        copy_config_file(hostname, testpath, "/etc/ipsec.conf", nsprefix=nsbasepath)
        copy_config_file(hostname, testpath, "/etc/ipsec.secrets", nsprefix=nsbasepath)

    elif args.userland == "strongswan":

        # check version and spew all over test output
        output = subprocess.getoutput("strongswan version")
        strongswan_version = "U5.9.14"
        if args.strongswan_version:
            strongswan_version = args.strongswan_version
        if not strongswan_version in output:
            print("strongswan %s must be installed" % (strongswan_version))
            print("")
            print(output)

        # required to write log file in /tmp
        subprocess.getoutput("setenforce 0")

        for directory in ("ipsec.d/", "ipsec.d/aacerts/", "ipsec.d/ocspcerts/", "ipsec.d/cacerts/", "ipsec.d/private/", "ipsec.d/certs/"):
            dst = os.path.join("/etc/strongswan", directory)
            if os.path.isdir(dst):
                shutil.rmtree(dst)
            os.mkdir(dst)
        copy_config_file(hostname, testpath, "/etc/strongswan/strongswan.conf", strict=True)
        copy_config_file(hostname, testpath, "/etc/strongswan/ipsec.conf")
        copy_config_file(hostname, testpath, "/etc/strongswan/ipsec.secrets")
        copy_config_file(hostname, testpath, "/etc/strongswan/swanctl/swanctl.conf", strict=True, optional=True)

    # test specific files
    xl2tpdconf = "%s/%s.xl2tpd.conf" % (testpath, hostname)
    pppoptions = "%s/%s.ppp-options.xl2tpd" % (testpath, hostname)
    chapfile = "%s/chap-secrets" % testpath
    xauthpasswd = "%s/%s.passwd" % (testpath, hostname)

    if os.path.isfile(xl2tpdconf):
        lsw_cp_file(xl2tpdconf, "/etc/xl2tpd/xl2tpd.conf", nsbasepath=nsbasepath)
    if os.path.isfile(pppoptions):
       lsw_cp_file(pppoptions, "/etc/ppp/options.xl2tpd", nsbasepath=nsbasepath)
    if os.path.isfile(chapfile):
        lsw_cp_file(chapfile, "/etc/ppp/chap-secrets", nsbasepath=nsbasepath)
    if os.path.isfile(xauthpasswd):
        lsw_cp_file(xauthpasswd, "/etc/ipsec.d/passwd", nsbasepath=nsbasepath)

    # restore /etc/hosts to original - some tests make changes
    lsw_cp_file("/testing/baseconfigs/all/etc/hosts", "/etc/hosts", nsbasepath=nsbasepath)
    resolv = "/testing/baseconfigs/all/etc/resolv.conf"
    if os.path.isfile("/testing/baseconfigs/%s/etc/resolv.conf" % hostname):
        resolv = "/testing/baseconfigs/%s/etc/resolv.conf" % hostname
    else:
        resolv = "/testing/baseconfigs/all/etc/resolv.conf"
    dst = resolve_conf
    if not args.namespace and os.path.islink(dst): # on fedora 22 it is link first remove the link
        os.unlink(dst)
    lsw_cp_file(resolv, "/etc/resolv.conf", nsbasepath=nsbasepath)

sysconfigd = "%s/etc/sysconfig" % (nsbasepath)
if not os.path.isdir(sysconfigd):
    os.makedirs(sysconfigd)

if args.userland in ("libreswan", "openswan") and hostname != "nic" and not args.namespace:
    if args.fips and args.userland in ("libreswan", "openswan"):
        # the test also requires using a modutil cmd which we cannot run here
        shutil.copyfile("/testing/baseconfigs/all/etc/sysconfig/pluto.fips", "/etc/sysconfig/pluto")
    else:
        lsw_cp_file("/testing/baseconfigs/all/etc/sysconfig/pluto", "/etc/sysconfig/pluto",
                nsbasepath=nsbasepath)
    if os.path.isfile("/etc/system-fips"):
        wipe_old("/etc/system-fips") # would work? would remove file from real system? AA_201902

# Set up NSS DB
#
# Stuff above will have emptied and re-created the directory.

if args.userland in ("libreswan", "openswan") and hostname != "nic":

    # Determine the NSS password and save
    if args.nsspw or args.fips:
        # Save the raw password so it can be passed to NSS commands.
        util_pw = " -f /run/pluto/nsspw"
        p12cmd_pw = " -k /run/pluto/nsspw"
        with open("/run/pluto/nsspw", "w") as f:
            f.write(nsspassword)
            f.write("\n")
        # Store the password in "$NSSDIR/nsspassword" so that pluto
        # can use it to open the the NSS DB
        if args.nsspw or args.fips:
            with open(ipsecdir + "/nsspassword", "w") as f:
                if args.nsspw:
                    f.write("NSS Certificate DB:" + nsspassword + "\n")
                if args.fips:
                    f.write("NSS FIPS 140-2 Certificate DB:" + nsspassword + "\n")
    else:
        util_pw = ""
        p12cmd_pw = " -K ''"

    match args.keys:
        case Keys.HOST:
            # This brings in the pre-generated nss *.db files that contain
            # raw host keys.  Basic testing tends to use pre-shared keys
            # and not these files.
            print("Creating NSS database containing host keys")
            for dbfile in ("cert9.db", "key4.db"):
                src = os.path.join("/testing/baseconfigs", hostname, "etc/ipsec.d", dbfile)
                dst = os.path.join(nssdir, dbfile)
                shutil.copyfile(src, dst)
                if not args.namespace:
                    os.chown(dst, 0, 0)
        case Keys.X509:
            print("Preparing X.509 files")
            #print("Creating NSS database containing X.509 keys and certificates")
            shell("/usr/bin/certutil -N --empty-password -d sql:" + nssdir)
        case Keys.NONE:
            print("Creating empty NSS database")
            shell("/usr/bin/certutil -N --empty-password -d sql:" + nssdir)

    # If needed set a password (this will upgrade any existing
    # database)

    if args.nsspw or args.fips:
        with open("/tmp/pw", "w") as f:
            f.write("\n")
        shell("/usr/bin/certutil -W -f /tmp/pw -@ /run/pluto/nsspw -d sql:" + nssdir, out=True)

    # Switch on fips in the NSS db
    if args.fips:
        shell("/usr/bin/modutil -dbdir sql:" + nssdir + " -fips true -force", out=True)

    # this section is getting rough. could use a nice refactoring
    if args.keys == Keys.X509:

        if not os.path.isfile("/testing/x509/real/mainca/root.p12"):
            print("\n\n---------------------------------------------------------------------\n"
                  "WARNING: no root.p12 file, did you run './kvm keys'?\n"
                  "---------------------------------------------------------------------\n")

        pw = "-w /testing/x509/nss-pw"

        if args.certchain:
            icanum = 2
            ica_p = hostname + "_chain_int_"
            ee = hostname + "_chain_endcert"

            # a note about DB trusts
            # 'CT,,' is our root's trust. T is important!! it is for verifying "SSLClient" x509 KU
            # ',,' is an intermediate's trust
            # 'P,,' (trusted peer) is nic's for OCSP
            # 'u,u,u' will be end cert trusts that are p12 imported (with privkey)

            # mainca and nic import
            shell("/testing/x509/import.sh real/mainca/root.cert")
            shell("/testing/x509/import.sh real/mainca/nic.end.cert")

            # install ee
            shell("/usr/bin/pk12util -i /testing/x509/pkcs12/%s.p12 -d sql:%s %s%s" %
                (ee, nssdir, pw, p12cmd_pw))

            # install intermediates
            for i in range(1, icanum + 1):
                acrt = ica_p + str(i)
                shell("/usr/bin/certutil -A -n %s -t ',,' -d sql:%s -a -i /testing/x509/certs/%s.crt%s" %
                    (acrt, nssdir, acrt, util_pw))

        elif args.x509name:

            # is pw needed? Perhaps when FIPS, but has it been set?

            # import then fix trust
            shell("/usr/bin/pk12util -i /testing/x509/pkcs12/mainca/%s.p12 -d sql:%s %s%s" %
                  (args.x509name, nssdir, pw, p12cmd_pw))
            shell("/usr/bin/certutil -M -n 'Libreswan test CA for mainca - Libreswan' -d sql:%s -t 'CT,,'%s" % (nssdir, util_pw))

            # pre-import certs for all other hosts
            for certname in ("west", "east", "road", "north", "nic"):
                if not hostname in certname:
                    shell("/testing/x509/import.sh real/mainca/%s.end.cert" % (certname))

        else:

            # is pw needed? Perahps when FIPS, but has it been set?

            # import then fix trust
            shell("/testing/x509/import.sh real/mainca/%s.all.p12" % (hostname))

            # pre-import certs for all other hosts
            for certname in ("west", "east", "road", "north", "nic"):
                if not hostname in certname:
                    shell("/testing/x509/import.sh real/mainca/%s.end.cert" % (certname))

# Don't enable FIPS mode until after NSS DBS are created.  See:
# https://bugzilla.mozilla.org/show_bug.cgi?id=1531267
if args.fips:
    fp = open("/etc/system-fips", "w")
    fp.close()
    shell("/testing/guestbin/fipson")

if args.namespace:
    # good idea for namespace. KVM sysctl.conf get copid.
    subprocess.getoutput("sysctl -p /testing/baseconfigs/all/etc/sysctl.conf")

if hostname != "nic" and not args.ipv46:
    subprocess.getoutput("sysctl net.ipv6.conf.all.disable_ipv6=1")
    subprocess.getoutput("sysctl net.ipv6.conf.default.disable_ipv6=1")

if args.dnssec:
    if args.namespace:
        dst = "/etc/nsd"
        src = "%s%s" % (nsbasepath, dst)
        lsw_init_dir(src, dst)

        dst ="/run/nsd"
        src = "%s%s" % (nsbasepath, dst)
        lsw_init_dir(src, dst)

        src = '/testing/baseconfigs/all/etc/nsd'
        dst = '/etc/'
        rsync_ap(src, dst);
    else:
        rsync_ap('/testing/baseconfigs/all/etc/nsd/conf.d', '/etc/nsd')
        rsync_ap('/testing/baseconfigs/all/etc/nsd/server.d', '/etc/nsd')

    if args.dnssec:
        # nsd listen on port 5353 and unbound listen on port 53
        subprocess.getoutput("sed -i 's/port: 53$/port: 5353/' /etc/nsd/server.d/nsd-server-libreswan.conf")
    else:
        #nsd listen on port 53
        subprocess.getoutput("sed -i 's/port: 5353$/port: 53/' /etc/nsd/server.d/nsd-server-libreswan.conf")

    if args.namespace:
        cmd = "../../guestbin/nsd-start.sh start"
        output = subprocess.check_output(cmd, shell=True, timeout=20, stderr=subprocess.STDOUT)
    else:
        subprocess.getoutput("systemctl start nsd")

    # now unbound
    if args.dnssec:
        if args.namespace:
            dst = "/etc/unbound"
            src = "%s%s" % (nsbasepath, dst)

            if mount_bind(src, dst, mkdir_src=True, wipe_old_dst=True):
                sys.exit(1)

            dst ="/run/unbound"
            src = "%s%s" % (nsbasepath, dst)
            if mount_bind(src, dst, mkdir_src=True, wipe_old_dst=True):
                sys.exit(1)

            if mount_bind(src, dst, mkdir_src=True, wipe_old_dst=True):
                print("failed to mount_bind src=%s dst %s" % (src, dst))
                sys.exit(1)

        src = '/testing/baseconfigs/all/etc/unbound'
        dst = '/etc/'
        rsync_ap(src, dst);

        if args.namespace:
            cmd = "../../guestbin/unbound-start.sh restart"
            subprocess.check_output(cmd, shell=True, timeout=120, stderr=subprocess.STDOUT)
        else:
            subprocess.getoutput("systemctl start unbound")

if not os.path.isfile("/root/.gdbinit"):
    fp = open("/root/.gdbinit", "w")
    fp.write("set auto-load safe-path /")
    fp.close()

subprocess.getoutput("iptables -F");
subprocess.getoutput("iptables -X");

if not args.namespace and hostname != "nic": # inside namespace this would kill pluto from other ns
    # shouldn't happen early on? now wiped run time files pid etc.
    # this is probably a last resort? may be a more gentle attempt at the beginning.
    #
    # final prep - this kills any running userland
    subprocess.call(["systemctl", "stop", "ipsec"])
    # for some reason this fails to stop strongswan?
    subprocess.call(["systemctl", "stop", "strongswan"])
    # python has no pidof - just outsource to the shell, thanks python!
    for dname in ( "pluto", "charon", "starter", "iked" ):
        try:
            if args.verbose:
                print ("INFO found daemon running stop it %s" % dname)
            subprocess.check_output(["killall", "-9", dname], stderr=subprocess.STDOUT)
        except:
            pass

    if os.path.isfile("/usr/sbin/getenforce"):
        selinux = subprocess.getoutput("/usr/sbin/getenforce")
        if os.path.isfile("/usr/sbin/restorecon") and selinux == 'Enforcing':
            subprocess.getoutput("restorecon -Rv /etc/ipsec.* /var/lib/ipsec /usr/local/libexec/ipsec /usr/local/sbin/ipsec")

for pidfile in ("/run/pluto/pluto.pid", "/run/strongswan/charon.pid", "/run/spmd.pid", ):
    if os.path.isfile(pidfile):
        os.unlink(pidfile)

if not args.namespace:
    # remove stacks so test can start the stack it needs.
    subprocess.getoutput("ipsec _stackmanager stop")