~openstack-charmers/+junk/hardening-ssh-tests-layer

« back to all changes in this revision

Viewing changes to reactive/hardening-ssh-tests.py

  • Committer: Edward Hope-Morley
  • Date: 2016-03-16 15:35:57 UTC
  • Revision ID: edward.hope-morley@canonical.com-20160316153557-i5luokk0ou852to1
* Import from https://github.com/CanonicalLTD/hardening-ssh-tests
* Additions and ammendments to fix pep8 and test runner.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
import stat
 
3
import pwd
 
4
import subprocess
 
5
 
 
6
from rubylib import bundle
 
7
 
 
8
from charms.reactive import when
 
9
from charmhelpers.core.hookenv import config, status_set
 
10
from charmhelpers.fetch import apt_install, apt_update
 
11
 
 
12
try:
 
13
    from Crypto.PublicKey import RSA
 
14
except ImportError:
 
15
    apt_update()
 
16
    apt_install('python3-crypto')
 
17
    from Crypto.PublicKey import RSA
 
18
 
 
19
 
 
20
@when('ruby.available')
 
21
def setup_tests():
 
22
    apt_install(['git'])
 
23
    if not os.path.exists(config('app-path')):
 
24
        clone()
 
25
 
 
26
    bundle('install')
 
27
    gen_sshkey()
 
28
 
 
29
 
 
30
def clone():
 
31
    cmd = ['git', 'clone',
 
32
           'https://github.com/hardening-io/tests-ssh-hardening.git',
 
33
           config('app-path')]
 
34
    try:
 
35
        subprocess.check_call(cmd)
 
36
    except subprocess.CalledProcessError:
 
37
        status_set('error', 'has a problem with git, try `resolved --retry')
 
38
        raise Exception("Error cloning git repo: %s" % ' '.join(cmd))
 
39
 
 
40
 
 
41
def gen_sshkey():
 
42
    key = RSA.generate(2048)
 
43
    priv_key_file = '/home/ubuntu/.ssh/id_rsa'
 
44
    pub_key_file = '/home/ubuntu/.ssh/id_rsa.pub'
 
45
    uid = pwd.getpwnam("ubuntu").pw_uid
 
46
    if os.path.exists(priv_key_file):
 
47
        return
 
48
 
 
49
    with open(priv_key_file, 'w') as content_file:
 
50
        os.chmod(priv_key_file, stat.S_IREAD)
 
51
        os.chown(priv_key_file, uid, -1)
 
52
        content_file.write(key.exportKey('PEM').decode('utf-8'))
 
53
 
 
54
    pubkey = key.publickey()
 
55
    with open(pub_key_file, 'w') as content_file:
 
56
        os.chown(pub_key_file, uid, -1)
 
57
        content_file.write(pubkey.exportKey('OpenSSH').decode('utf-8'))