Example #1
0
 def test_3_simple(self):
     """
     verify that we can establish an ssh link with ourselves across the
     loopback sockets.  this is hardly "simple" but it's simpler than the
     later tests. :)
     """
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assert_(not event.isSet())
     self.assertEquals(None, self.tc.get_username())
     self.assertEquals(None, self.ts.get_username())
     self.assertEquals(False, self.tc.is_authenticated())
     self.assertEquals(False, self.ts.is_authenticated())
     self.ts.start_server(event, server)
     self.tc.connect(hostkey=public_host_key,
                     username='******',
                     password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
     self.assertEquals('slowdive', self.tc.get_username())
     self.assertEquals('slowdive', self.ts.get_username())
     self.assertEquals(True, self.tc.is_authenticated())
     self.assertEquals(True, self.ts.is_authenticated())
Example #2
0
 def start_server(self):
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     self.public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     self.event = threading.Event()
     self.server = NullServer()
     self.assert_(not self.event.isSet())
     self.ts.start_server(self.event, self.server)
Example #3
0
 def test_6_compare_rsa(self):
     # verify that the private & public keys compare equal
     key = RSAKey.from_private_key_file("tests/test_rsa.key")
     self.assertEquals(key, key)
     pub = RSAKey(data=bytes(key))
     self.assert_(key.can_sign())
     self.assert_(not pub.can_sign())
     self.assertEquals(key, pub)
Example #4
0
 def test_6_compare_rsa(self):
     # verify that the private & public keys compare equal
     key = RSAKey.from_private_key_file('tests/test_rsa.key')
     self.assertEquals(key, key)
     pub = RSAKey(data=str(key))
     self.assert_(key.can_sign())
     self.assert_(not pub.can_sign())
     self.assertEquals(key, pub)
Example #5
0
 def getIdentityKey(self):
     keyfile = self.identityfile
     if not os.path.exists(keyfile):
         key = RSAKey.generate(1024)
         key.write_private_key_file(keyfile)
     else:
         try:
             key = DSAKey.from_private_key_file(keyfile)
         except:
             key = RSAKey.from_private_key_file(keyfile)
     return keyfile, "ssh-rsa %s hostout@hostout" % key.get_base64()
Example #6
0
 def getIdentityKey(self):
     keyfile = os.path.abspath(os.path.join(self.getLocalBuildoutPath(),'hostout_rsa'))
     keyfile = self.options.get('identity-file', keyfile)
     if not os.path.exists(keyfile):
         key = RSAKey.generate(1024)
         key.write_private_key_file(keyfile)
     else:
         try:
             key = DSAKey.from_private_key_file(keyfile)
         except:
             key = RSAKey.from_private_key_file(keyfile)
     return keyfile, "ssh-rsa %s hostout@hostout" % key.get_base64()
Example #7
0
 def test_8_sign_rsa(self):
     # verify that the rsa private key can sign and verify
     key = RSAKey.from_private_key_file('tests/test_rsa.key')
     msg = key.sign_ssh_data(rng, 'ice weasels')
     self.assert_(type(msg) is Message)
     msg.rewind()
     self.assertEquals('ssh-rsa', msg.get_string())
     sig = ''.join([chr(int(x, 16)) for x in SIGNED_RSA.split(':')])
     self.assertEquals(sig, msg.get_string())
     msg.rewind()
     pub = RSAKey(data=str(key))
     self.assert_(pub.verify_ssh_sig('ice weasels', msg))
Example #8
0
 def test_8_sign_rsa(self):
     # verify that the rsa private key can sign and verify
     key = RSAKey.from_private_key_file("tests/test_rsa.key")
     msg = key.sign_ssh_data(rng, b"ice weasels")
     self.assert_(type(msg) is Message)
     msg.rewind()
     self.assertEquals(b"ssh-rsa", msg.get_string())
     sig = b"".join([chr(int(x, 16)).encode("latin-1") for x in SIGNED_RSA.split(b":")])
     self.assertEquals(sig, msg.get_string())
     msg.rewind()
     pub = RSAKey(data=bytes(key))
     self.assert_(pub.verify_ssh_sig(b"ice weasels", msg))
Example #9
0
    def test_2_load_rsa(self):
        key = RSAKey.from_private_key_file('tests/test_rsa.key')
        self.assertEquals('ssh-rsa', key.get_name())
        exp_rsa = FINGER_RSA.split()[1].replace(':', '')
        my_rsa = hexlify(key.get_fingerprint())
        self.assertEquals(exp_rsa, my_rsa)
        self.assertEquals(PUB_RSA.split()[1], key.get_base64())
        self.assertEquals(1024, key.get_bits())

        s = StringIO.StringIO()
        key.write_private_key(s)
        self.assertEquals(RSA_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = RSAKey.from_private_key(s)
        self.assertEquals(key, key2)
Example #10
0
    def test_2_load_rsa(self):
        key = RSAKey.from_private_key_file("tests/test_rsa.key")
        self.assertEquals(b"ssh-rsa", key.get_name())
        exp_rsa = FINGER_RSA.split()[1].replace(b":", b"")
        my_rsa = hexlify(key.get_fingerprint())
        self.assertEquals(exp_rsa, my_rsa)
        self.assertEquals(PUB_RSA.split()[1], key.get_base64())
        self.assertEquals(1024, key.get_bits())

        s = io.BytesIO()
        key.write_private_key(s)
        self.assertEquals(RSA_PRIVATE_OUT, s.getvalue())
        s.seek(0)
        key2 = RSAKey.from_private_key(s)
        self.assertEquals(key, key2)
Example #11
0
 def test_3_simple(self):
     """
     verify that we can establish an ssh link with ourselves across the
     loopback sockets.  this is hardly "simple" but it's simpler than the
     later tests. :)
     """
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assert_(not event.isSet())
     self.assertEquals(None, self.tc.get_username())
     self.assertEquals(None, self.ts.get_username())
     self.assertEquals(False, self.tc.is_authenticated())
     self.assertEquals(False, self.ts.is_authenticated())
     self.ts.start_server(event, server)
     self.tc.connect(hostkey=public_host_key,
                     username='******', password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
     self.assertEquals('slowdive', self.tc.get_username())
     self.assertEquals('slowdive', self.ts.get_username())
     self.assertEquals(True, self.tc.is_authenticated())
     self.assertEquals(True, self.ts.is_authenticated())
Example #12
0
def get_public_rsa_fingerprint(pubkey_location):
    try:
        k = RSAKey.from_private_key_file(pubkey_location)
    except ssh.SSHException:
        raise exception.SSHError("Invalid RSA private key file: %s" %
                                 pubkey_location)
    md5digest = hashlib.md5(str(k)).hexdigest()
    return insert_char_every_n_chars(md5digest, ':', 2)
Example #13
0
def get_public_rsa_fingerprint(pubkey_location):
    try:
        k = RSAKey.from_private_key_file(pubkey_location)
    except ssh.SSHException:
        raise exception.SSHError("Invalid RSA private key file: %s" %
                                 pubkey_location)
    md5digest = hashlib.md5(str(k)).hexdigest()
    return insert_char_every_n_chars(md5digest, ':', 2)
Example #14
0
 def test_3_load_rsa_password(self):
     key = RSAKey.from_private_key_file("tests/test_rsa_password.key", b"television")
     self.assertEquals(b"ssh-rsa", key.get_name())
     exp_rsa = FINGER_RSA.split()[1].replace(b":", b"")
     my_rsa = hexlify(key.get_fingerprint())
     self.assertEquals(exp_rsa, my_rsa)
     self.assertEquals(PUB_RSA.split()[1], key.get_base64())
     self.assertEquals(1024, key.get_bits())
Example #15
0
 def start_server(self):
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     self.public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     self.event = threading.Event()
     self.server = NullServer()
     self.assert_(not self.event.isSet())
     self.ts.start_server(self.event, self.server)
Example #16
0
 def test_3_load_rsa_password(self):
     key = RSAKey.from_private_key_file('tests/test_rsa_password.key',
                                        'television')
     self.assertEquals('ssh-rsa', key.get_name())
     exp_rsa = FINGER_RSA.split()[1].replace(':', '')
     my_rsa = hexlify(key.get_fingerprint())
     self.assertEquals(exp_rsa, my_rsa)
     self.assertEquals(PUB_RSA.split()[1], key.get_base64())
     self.assertEquals(1024, key.get_bits())
Example #17
0
 def test_3a_long_banner(self):
     """
     verify that a long banner doesn't mess up the handshake.
     """
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assert_(not event.isSet())
     self.socks.send(LONG_BANNER)
     self.ts.start_server(event, server)
     self.tc.connect(hostkey=public_host_key,
                     username='******',
                     password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
Example #18
0
    def setup_test_server(self, client_options=None, server_options=None):
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=str(host_key))
        self.ts.add_server_key(host_key)

        if client_options is not None:
            client_options(self.tc.get_security_options())
        if server_options is not None:
            server_options(self.ts.get_security_options())

        event = threading.Event()
        self.server = NullServer()
        self.assert_(not event.isSet())
        self.ts.start_server(event, self.server)
        self.tc.connect(hostkey=public_host_key,
                        username='******',
                        password='******')
        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())
Example #19
0
 def test_3a_long_banner(self):
     """
     verify that a long banner doesn't mess up the handshake.
     """
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assert_(not event.isSet())
     self.socks.send(LONG_BANNER)
     self.ts.start_server(event, server)
     self.tc.connect(hostkey=public_host_key,
                     username='******', password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
Example #20
0
def get_private_rsa_fingerprint(key_location):
    """
    Returns the fingerprint of a private RSA key as a 59-character string (40
    characters separated every 2 characters by a ':'). The fingerprint is
    computed using a SHA1 digest of the DER encoded RSA private key.
    """
    try:
        k = RSAKey.from_private_key_file(key_location)
    except ssh.SSHException:
        raise exception.SSHError("Invalid RSA private key file: %s" %
                                 key_location)
    params = dict(invq=util.mod_inverse(k.q, k.p), dp=k.d % (k.p - 1),
                  dq=k.d % (k.q - 1), d=k.d, n=k.n, p=k.p, q=k.q, e=k.e)
    assert len(params) == 8
    # must convert from pkcs1 to pkcs8 and then DER encode
    pkcs8der = export_rsa_to_pkcs8(params)
    sha1digest = hashlib.sha1(pkcs8der).hexdigest()
    return insert_char_every_n_chars(sha1digest, ':', 2)
Example #21
0
 def setup_test_server(self, client_options=None, server_options=None):
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     
     if client_options is not None:
         client_options(self.tc.get_security_options())
     if server_options is not None:
         server_options(self.ts.get_security_options())
     
     event = threading.Event()
     self.server = NullServer()
     self.assert_(not event.isSet())
     self.ts.start_server(event, self.server)
     self.tc.connect(hostkey=public_host_key,
                     username='******', password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
Example #22
0
def get_private_rsa_fingerprint(key_location):
    """
    Returns the fingerprint of a private RSA key as a 59-character string (40
    characters separated every 2 characters by a ':'). The fingerprint is
    computed using a SHA1 digest of the DER encoded RSA private key.
    """
    try:
        k = RSAKey.from_private_key_file(key_location)
    except ssh.SSHException:
        raise exception.SSHError("Invalid RSA private key file: %s" %
                                 key_location)
    params = dict(invq=util.mod_inverse(k.q, k.p),
                  dp=k.d % (k.p - 1),
                  dq=k.d % (k.q - 1),
                  d=k.d,
                  n=k.n,
                  p=k.p,
                  q=k.q,
                  e=k.e)
    assert len(params) == 8
    # must convert from pkcs1 to pkcs8 and then DER encode
    pkcs8der = export_rsa_to_pkcs8(params)
    sha1digest = hashlib.sha1(pkcs8der).hexdigest()
    return insert_char_every_n_chars(sha1digest, ':', 2)
Example #23
0
def agent():

    ca.log("Starting!", '', 1)

    keystone = keystoneclient.v2_0.client.Client(
        token=ca.creds['token'],
        tenant_id=ca.creds['tenantId'],
        auth_url=ca.creds['identity_url'])

    compute_catalog = keystone.service_catalog.get_endpoints()['compute']

    cluster_endpoint = None

    for endpoint in compute_catalog:
        if endpoint['region'] == ca.conf['region']:
            cluster_endpoint = endpoint

    if not cluster_endpoint:
        ca.log_fail("Failing, region not found in endpoint list.")
        exit()

    nova = novaclient.v1_1.client.Client(None, None, None, auth_url="")
    nova.set_management_url(cluster_endpoint['publicURL'])
    nova.client.auth_token = ca.creds['token']

    # Get the keypair we're supposed to insert.

    final_keypair = None

    for keypair in nova.keypairs.list():
        if keypair.name == ca.conf['keypair']:
            final_keypair = keypair

    if not final_keypair:
        ca.log_fail("Failing, keypair " + ca.conf['keypair'] + " not found.")
        exit()

    ca.log("Found keypair.", '', 2)

    # Get the flavor we're supposed to use.

    requested_flavor = None

    for flavor in nova.flavors.list():
        if flavor.name == ca.conf['flavor']:
            requested_flavor = flavor

    if not requested_flavor:
        ca.log_fail("Failing, flavor " + ca.conf['flavor'] + " not found.")
        exit()

    ca.log("Found flavor.", '', 3)

    # Get the image we're supposed to use.

    image_name = 'Ubuntu Precise 12.04 LTS Server 64-bit 20121026 (b)'

    for image in nova.images.list():
        if image.name == image_name:
            requested_image = image

    if not requested_image:
        ca.log_fail("Failing, image " + image_name + " not found.")
        exit()

    ca.log(
        "Found image: " + requested_image.name + " (" +
        str(requested_image.id) + ")", '', 4)

    # Get the security group we're supposed to use.

    requested_group = None

    for group in nova.security_groups.list():
        if group.name == ca.conf['secgroup']:
            requested_group = group

    if not requested_group:
        ca.log_fail("Failing, group " + ca.conf['secgroup'] + " not found.")
        exit()

    ca.log("Found group: " + requested_group.name + ".", '', 5)

    ca.log("Creating our temporary keypair.", '', 6)

    my_keypair_name = ca.conf['keypair'] + "-tempagent" + str(
        random.randint(0, 999999999))
    my_keypair = nova.keypairs.create(my_keypair_name)

    ca.log("Starting server.", '', 10)

    my_server = nova.servers.create(ca.conf['name'],
                                    requested_image,
                                    requested_flavor,
                                    security_groups=[requested_group.name],
                                    key_name=my_keypair_name)

    time.sleep(5)
    status = "working"
    c = 5
    server = nova.servers.get(my_server)
    while server.status != 'ACTIVE' or c > 120:
        server = nova.servers.get(my_server)
        time.sleep(1)
        c += 1

    if server.status != 'ACTIVE':
        ca.log_fail("Server didn't boot in 2 minutes.")
        nova.servers.delete(my_server)

    ca.log("Server created.", '', 20)

    server_address = None
    for address in server.addresses['private']:
        if address['version'] == 4 and address['addr'][0:3] != '10.':
            server_address = address['addr']

    if not server_address:
        ca.log("Couldn't determine server address.")
        nova.keypairs.delete(my_keypair_name)
        nova.servers.delete(my_server)
        exit()

    try:

        private_key_file = StringIO.StringIO(my_keypair.private_key)

        key = RSAKey.from_private_key(private_key_file)

        ssh = SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy())

    except:
        print "Unexpected error:", sys.exc_info()[0], sys.exc_info()[1]

    ca.log("SSHing to server at " + server_address, '', 30)

    time.sleep(5)
    c = 5

    while c < 180:
        try:
            ssh.connect(server_address,
                        pkey=key,
                        username='******',
                        look_for_keys=False)

        except:
            time.sleep(5)
            c += 5
            continue

        break

    if c >= 180:
        ca.log_fail("Couldn't ssh in to server in 3 minutes.")
        nova.keypairs.delete(my_keypair_name)
        nova.servers.delete(my_server)
        exit()

    if ca.conf.get("software") == "none":

        ca.log("Connected to server, updating apt.", '', 40)
        output = run_command("sudo apt-get update", None, ssh)
        ca.log("Connected to server, installing apache2.", output, 50)
        output = run_command("sudo apt-get -y install apache2", None, ssh)
        ca.log("Installed apache2.", output, 80)
        ca.log("Resetting temporary server keypair.", '', 90)
        output = run_command(
            "echo '" + final_keypair.public_key + "' > .ssh/authorized_keys",
            None, ssh)
        ca.log("Deleting temporary keypair.", '', 95)
        nova.keypairs.delete(my_keypair_name)

        try:
            body = urllib2.urlopen("http://" + server_address + "/").read()
        except:
            ca.log("Server not found, something went wrong.")
            exit()

        ca.log("Server up at http://" + server_address + "/", "Got:\n" + body,
               100)

    elif ca.conf.get("software") == "wordpress":

        ca.log("Connected to server, resetting temporary server keypair...",
               '', 40)
        output = run_command(
            "echo '" + final_keypair.public_key + "' > .ssh/authorized_keys",
            None, ssh)
        ca.log("Deleting temporary keypair.", '', 45)
        nova.keypairs.delete(my_keypair_name)

        ca.log("Updating apt.", '', 47)
        output = run_command("sudo apt-get update", None, ssh)
        ca.log("Installing apache 2 and php 5...", '', 50)
        output = run_command(
            "sudo apt-get install -y apache2 libapache2-mod-php5 php5-cli  php5-gd libssh2-php php5-curl",
            None, ssh)
        ca.log("Installed apache2.", output, 60)
        ca.log("Installing mysql...", '', 61)
        mysql_root_pass = ''.join(
            random.choice('0123456789abcdef') for i in range(8))
        mysql_wordpress_pass = ''.join(
            random.choice('0123456789abcdef') for i in range(8))
        output = run_command(
            "sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password password "
            + mysql_root_pass + "'", None, ssh)
        output += run_command(
            "sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password_again password "
            + mysql_root_pass + "'", None, ssh)
        output += run_command(
            "sudo apt-get -y install mysql-server php5-mysql", None, ssh)
        ca.log("Installed mysql.", output, 70)
        ca.log("Reconfiguring and reinstalling apache...", '', 71)
        output = run_command(
            "sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/",
            None, ssh)
        output += run_command(
            "sudo sed -i 11's/None/All/' /etc/apache2/sites-enabled/000-default",
            None, ssh)
        output += run_command("sudo apachectl restart", None, ssh)
        ca.log("Restarted apache2.", output, 75)
        ca.log("Creating mysql wordpress database...", '', 76)
        output = run_command(
            "mysqladmin -u root --password="******" create wordpress", None, ssh)
        output += run_command(
            """mysql -u root --password='******' wordpress -e 'GRANT ALL PRIVILEGES ON wordpress.* TO "wordpress"@"localhost" IDENTIFIED BY "%s";FLUSH PRIVILEGES;'"""
            % (mysql_root_pass, mysql_wordpress_pass), None, ssh)
        ca.log("Created mysql user.", output, 80)
        ca.log("Downloading and installing wordpress...", '', 81)
        output = run_command("wget http://wordpress.org/latest.tar.gz", None,
                             ssh)
        ca.log("Downloaded wordpress.", output, 85)
        ca.log("Expanding and configuring wordpress...", '', 86)
        output = run_command("sudo rm -f /var/www/index.html", None, ssh)
        output += run_command(
            "sudo tar fxvz latest.tar.gz -C /var/www/ --strip-components=1",
            None, ssh)
        output += run_command("sudo mkdir /var/www/wp-content/uploads", None,
                              ssh)
        output += run_command("sudo chown -R ubuntu:www-data /var/www", None,
                              ssh)
        output += run_command("sudo chmod g+w /var/www/wp-content/uploads",
                              None, ssh)
        output += run_command("sudo touch /var/www/.htaccess", None, ssh)
        output += run_command("sudo chown ubuntu:www-data /var/www/.htaccess",
                              None, ssh)
        output += run_command("sudo chmod g+w /var/www/.htaccess", None, ssh)
        output += run_command(
            "cp /var/www/wp-config-sample.php /var/www/wp-config.php", None,
            ssh)
        output += run_command(
            "sed -i 's/database_name_here/wordpress/g' /var/www/wp-config.php",
            None, ssh)
        output += run_command(
            "sed -i 's/username_here/wordpress/g' /var/www/wp-config.php",
            None, ssh)
        output += run_command(
            "sed -i 's/password_here/" + mysql_wordpress_pass +
            "/g' /var/www/wp-config.php", None, ssh)
        ca.log("Configured wordpress.", output, 90)

        try:
            body = urllib2.urlopen("http://" + server_address +
                                   "/wp-admin/install.php").read()
        except:
            ca.log("Server not found, something went wrong.")
            exit()

        ca.log(
            "Wordpress up at http://" + server_address +
            "/wp-admin/install.php, sending email.", '', 95)

        ca.email(
            "Apache 2 & Wordpress Setup on " + ca.conf['name'] + " Complete",
            """
		Server setup complete.  Continue to web-based wordpress setup at:
		
		http://%s/wp-admin/install.php
		
		""" % (server_address))

        ca.log("Server up, activation email sent.", '', 100)

    elif ca.conf.get("software") == "drupal":

        ca.log("Connected to server, resetting temporary server keypair...",
               '', 40)
        output = run_command(
            "echo '" + final_keypair.public_key + "' > .ssh/authorized_keys",
            None, ssh)
        ca.log("Deleting temporary keypair.", '', 45)
        nova.keypairs.delete(my_keypair_name)

        ca.log("Updating apt.", '', 47)
        output = run_command("sudo apt-get update", None, ssh)
        ca.log("Installing apache 2 and php 5...", '', 50)
        output = run_command(
            "sudo apt-get install -y apache2 libapache2-mod-php5 php5-cli  php5-gd libssh2-php php5-curl",
            None, ssh)
        ca.log("Installed apache2.", output, 60)
        ca.log("Installing mysql...", '', 61)
        mysql_root_pass = ''.join(
            random.choice('0123456789abcdef') for i in range(8))
        mysql_drupal_pass = ''.join(
            random.choice('0123456789abcdef') for i in range(8))
        drupal_admin_pass = ''.join(
            random.choice('0123456789abcdef') for i in range(8))
        output = run_command(
            "sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password password "
            + mysql_root_pass + "'", None, ssh)
        output += run_command(
            "sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password_again password "
            + mysql_root_pass + "'", None, ssh)
        output += run_command(
            "sudo apt-get -y install mysql-server php5-mysql", None, ssh)
        ca.log("Installed mysql.", output, 70)
        ca.log("Reconfiguring and reinstalling apache...", '', 71)
        output = run_command(
            "sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/",
            None, ssh)
        output += run_command(
            "sudo sed -i 11's/None/All/' /etc/apache2/sites-enabled/000-default",
            None, ssh)
        output += run_command("sudo apachectl restart", None, ssh)
        ca.log("Restarted apache2.", output, 75)
        ca.log("Creating mysql drupal database...", '', 76)
        output = run_command(
            "mysqladmin -u root --password="******" create drupal", None, ssh)
        output += run_command(
            """mysql -u root --password='******' drupal -e 'GRANT ALL PRIVILEGES ON drupal.* TO "drupal"@"localhost" IDENTIFIED BY "%s";FLUSH PRIVILEGES;'"""
            % (mysql_root_pass, mysql_drupal_pass), None, ssh)
        ca.log("Created mysql user.", output, 80)
        ca.log("Downloading drush and drupal...", '', 81)
        output = run_command("sudo apt-get install -y drush", None, ssh)
        output += run_command(
            "wget http://ftp.drupal.org/files/projects/drupal-7.22.tar.gz",
            None, ssh)
        ca.log("Downloaded drush and drupal.", output, 85)
        ca.log("Configuring drupal...", '', 86)
        output = run_command("sudo rm -f /var/www/index.html", None, ssh)
        output += run_command(
            "sudo tar fxvz drupal-7.22.tar.gz -C /var/www/ --strip-components=1",
            None, ssh)
        output += run_command("sudo chown -R ubuntu:www-data /var/www", None,
                              ssh)
        output += run_command(
            "sudo sh -c 'cd /var/www ; drush site-install standard -y --db-url=mysql://drupal:"
            + mysql_drupal_pass + "@localhost/drupal --site-name=\"" +
            ca.conf['name'] + "\" --account-pass="******"'",
            None, ssh)
        output += run_command("sudo mkdir /var/www/sites/default/private",
                              None, ssh)
        output += run_command(
            "sudo mkdir /var/www/sites/default/private/files", None, ssh)
        output += run_command(
            "sudo chown -R ubuntu:www-data /var/www/sites/default", None, ssh)
        output += run_command("sudo chmod 777 /var/www/sites/default/files",
                              None, ssh)
        output += run_command("sudo chmod 777 /var/www/sites/default/private",
                              None, ssh)
        output += run_command(
            "sudo chmod 777 /var/www/sites/default/private/files", None, ssh)

        ca.log("Configured drupal, admin password: "******"http://" + server_address + "/").read()
        except:
            ca.log("Server not found, something went wrong.")
            exit()

        ca.log("Drupal up at http://" + server_address + "/, sending email.",
               '', 95)

        ca.email(
            "Apache 2 & Drupal Setup on " + ca.conf['name'] + " Complete", """
Server setup complete.  Login to your new drupal server at:
		
username: admin
password: %s
url:      http://%s/
		
		""" % (drupal_admin_pass, server_address))

        ca.log(
            "Server up at http://" + server_address +
            "/ and activation email sent.", '', 100)
Example #24
0
 def test_A_generate_rsa(self):
     key = RSAKey.generate(1024)
     msg = key.sign_ssh_data(rng, b"jerri blank")
     msg.rewind()
     self.assert_(key.verify_ssh_sig(b"jerri blank", msg))
Example #25
0
 def test_A_generate_rsa(self):
     key = RSAKey.generate(1024)
     msg = key.sign_ssh_data(rng, 'jerri blank')
     msg.rewind()
     self.assert_(key.verify_ssh_sig('jerri blank', msg))
Example #26
0
def agent():
	
	ca.log("Starting!",'',1)
	
	keystone = keystoneclient.v2_0.client.Client(token=ca.creds['token'], tenant_id=ca.creds['tenantId'],
							auth_url=ca.creds['identity_url'])
	
	compute_catalog = keystone.service_catalog.get_endpoints()['compute']
	
	cluster_endpoint = None
	
	for endpoint in compute_catalog:
		if endpoint['region'] == ca.conf['region']:
			cluster_endpoint = endpoint
	
	if not cluster_endpoint:
		ca.log_fail("Failing, region not found in endpoint list.")
		exit()
	
	nova = novaclient.v1_1.client.Client(None,None,None,auth_url="")
	nova.set_management_url(cluster_endpoint['publicURL'])
	nova.client.auth_token = ca.creds['token']
	
	# Get the keypair we're supposed to insert.
	
	final_keypair = None
	
	for keypair in nova.keypairs.list():
		if keypair.name == ca.conf['keypair']:
			final_keypair = keypair
	
	if not final_keypair:
		ca.log_fail("Failing, keypair "+ca.conf['keypair']+" not found.")
		exit()
		
	ca.log("Found keypair.",'',2)
	
	# Get the flavor we're supposed to use.
	
	requested_flavor = None
	
	for flavor in nova.flavors.list():
		if flavor.name == ca.conf['flavor']:
			requested_flavor = flavor
	
	if not requested_flavor:
		ca.log_fail("Failing, flavor "+ca.conf['flavor']+" not found.")
		exit()
	
	ca.log("Found flavor.",'',3)
	

	# Get the image we're supposed to use.
	
	image_name = 'Ubuntu Precise 12.04 LTS Server 64-bit 20121026 (b)'
	
	for image in nova.images.list():
		if image.name == image_name:
			requested_image = image
	
	if not requested_image:
		ca.log_fail("Failing, image "+image_name+" not found.")
		exit()
	
	ca.log("Found image: "+requested_image.name+" ("+str(requested_image.id)+")",'',4)

	# Get the security group we're supposed to use.
	
	requested_group = None
	
	for group in nova.security_groups.list():
		if group.name == ca.conf['secgroup']:
			requested_group = group
	
	if not requested_group:
		ca.log_fail("Failing, group "+ca.conf['secgroup']+" not found.")
		exit()
	
	ca.log("Found group: "+requested_group.name+".",'',5)
		
	ca.log("Creating our temporary keypair.",'',6)
	
	my_keypair_name = ca.conf['keypair']+"-tempagent"+str(random.randint(0,999999999))
	my_keypair = nova.keypairs.create(my_keypair_name)


	ca.log("Starting server.",'',10)

	my_server = nova.servers.create(ca.conf['name'],
									requested_image,
									requested_flavor,
									security_groups=[requested_group.name],
									key_name=my_keypair_name)
	
	time.sleep(5)
	status = "working"
	c = 5
	server = nova.servers.get(my_server)
	while server.status != 'ACTIVE' or c > 120:
		server = nova.servers.get(my_server)
		time.sleep(1)
		c += 1
		
	if server.status != 'ACTIVE':
		ca.log_fail("Server didn't boot in 2 minutes.")
		nova.servers.delete(my_server)

	ca.log("Server created.",'',20)
	
	server_address = None
	for address in server.addresses['private']:
		if address['version'] == 4 and address['addr'][0:3] != '10.':
			server_address = address['addr']
	
	if not server_address:
		ca.log("Couldn't determine server address.")
		nova.keypairs.delete(my_keypair_name)
		nova.servers.delete(my_server)
		exit()

	try:

		private_key_file = StringIO.StringIO(my_keypair.private_key)
		
		key = RSAKey.from_private_key(private_key_file)
		
		
		ssh = SSHClient()
		ssh.set_missing_host_key_policy(AutoAddPolicy())
		
	except:
		print "Unexpected error:", sys.exc_info()[0], sys.exc_info()[1]

		
	ca.log("SSHing to server at "+server_address,'',30)

	time.sleep(5)
	c = 5
	
	while c < 180:
		try:
			ssh.connect(server_address, pkey=key, username='******', look_for_keys=False)
		
		except:
			time.sleep(5)
			c += 5
			continue
		
		break

	
	if c >= 180:
		ca.log_fail("Couldn't ssh in to server in 3 minutes.")
		nova.keypairs.delete(my_keypair_name)
		nova.servers.delete(my_server)
		exit()
	
	
	if ca.conf.get("software") == "none":
		
		
		ca.log("Connected to server, updating apt.",'',40)
		output = run_command("sudo apt-get update",None,ssh)
		ca.log("Connected to server, installing apache2.",output,50)
		output = run_command("sudo apt-get -y install apache2",None,ssh)
		ca.log("Installed apache2.",output,80)
		ca.log("Resetting temporary server keypair.",'',90)
		output = run_command("echo '"+final_keypair.public_key+"' > .ssh/authorized_keys",None,ssh)
		ca.log("Deleting temporary keypair.",'',95)
		nova.keypairs.delete(my_keypair_name)
	
	
		try:
			body = urllib2.urlopen("http://"+server_address+"/").read()
		except:
			ca.log("Server not found, something went wrong.")
			exit()
		
		ca.log("Server up at http://"+server_address+"/","Got:\n"+body,100)
		
	elif ca.conf.get("software") == "wordpress":
		
		ca.log("Connected to server, resetting temporary server keypair...",'',40)
		output = run_command("echo '"+final_keypair.public_key+"' > .ssh/authorized_keys",None,ssh)
		ca.log("Deleting temporary keypair.",'',45)
		nova.keypairs.delete(my_keypair_name)

		ca.log("Updating apt.",'',47)
		output = run_command("sudo apt-get update",None,ssh)
		ca.log("Installing apache 2 and php 5...",'',50)
		output = run_command("sudo apt-get install -y apache2 libapache2-mod-php5 php5-cli  php5-gd libssh2-php php5-curl",None,ssh)
		ca.log("Installed apache2.",output,60)
		ca.log("Installing mysql...",'',61)
		mysql_root_pass = ''.join(random.choice('0123456789abcdef') for i in range(8))
		mysql_wordpress_pass = ''.join(random.choice('0123456789abcdef') for i in range(8))
		output = run_command("sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password password "+mysql_root_pass+"'",None,ssh)
		output += run_command("sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password_again password "+mysql_root_pass+"'",None,ssh)
		output += run_command("sudo apt-get -y install mysql-server php5-mysql",None,ssh)
		ca.log("Installed mysql.",output,70)
		ca.log("Reconfiguring and reinstalling apache...",'',71)
		output = run_command("sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/",None,ssh)
		output += run_command("sudo sed -i 11's/None/All/' /etc/apache2/sites-enabled/000-default",None,ssh)
		output += run_command("sudo apachectl restart",None,ssh)
		ca.log("Restarted apache2.",output,75)
		ca.log("Creating mysql wordpress database...",'',76)
		output = run_command("mysqladmin -u root --password="******" create wordpress",None,ssh)
		output += run_command("""mysql -u root --password='******' wordpress -e 'GRANT ALL PRIVILEGES ON wordpress.* TO "wordpress"@"localhost" IDENTIFIED BY "%s";FLUSH PRIVILEGES;'""" % (mysql_root_pass, mysql_wordpress_pass),None,ssh)
		ca.log("Created mysql user.",output,80)
		ca.log("Downloading and installing wordpress...",'',81)
		output = run_command("wget http://wordpress.org/latest.tar.gz",None,ssh)
		ca.log("Downloaded wordpress.",output,85)
		ca.log("Expanding and configuring wordpress...",'',86)
		output = run_command("sudo rm -f /var/www/index.html",None,ssh)
		output += run_command("sudo tar fxvz latest.tar.gz -C /var/www/ --strip-components=1",None,ssh)
		output += run_command("sudo mkdir /var/www/wp-content/uploads",None,ssh)
		output += run_command("sudo chown -R ubuntu:www-data /var/www",None,ssh)
		output += run_command("sudo chmod g+w /var/www/wp-content/uploads",None,ssh)
		output += run_command("sudo touch /var/www/.htaccess",None,ssh)
		output += run_command("sudo chown ubuntu:www-data /var/www/.htaccess",None,ssh)
		output += run_command("sudo chmod g+w /var/www/.htaccess",None,ssh)
		output += run_command("cp /var/www/wp-config-sample.php /var/www/wp-config.php",None,ssh)
		output += run_command("sed -i 's/database_name_here/wordpress/g' /var/www/wp-config.php",None,ssh)
		output += run_command("sed -i 's/username_here/wordpress/g' /var/www/wp-config.php",None,ssh)
		output += run_command("sed -i 's/password_here/"+mysql_wordpress_pass+"/g' /var/www/wp-config.php",None,ssh)
		ca.log("Configured wordpress.",output,90)

		try:
			body = urllib2.urlopen("http://"+server_address+"/wp-admin/install.php").read()
		except:
			ca.log("Server not found, something went wrong.")
			exit()

		ca.log("Wordpress up at http://"+server_address+"/wp-admin/install.php, sending email.",'',95)

		ca.email("Apache 2 & Wordpress Setup on "+ca.conf['name']+" Complete","""
		Server setup complete.  Continue to web-based wordpress setup at:
		
		http://%s/wp-admin/install.php
		
		""" % (server_address))
		

		ca.log("Server up, activation email sent.",'',100)
		
	elif ca.conf.get("software") == "drupal":
		
		ca.log("Connected to server, resetting temporary server keypair...",'',40)
		output = run_command("echo '"+final_keypair.public_key+"' > .ssh/authorized_keys",None,ssh)
		ca.log("Deleting temporary keypair.",'',45)
		nova.keypairs.delete(my_keypair_name)

		ca.log("Updating apt.",'',47)
		output = run_command("sudo apt-get update",None,ssh)
		ca.log("Installing apache 2 and php 5...",'',50)
		output = run_command("sudo apt-get install -y apache2 libapache2-mod-php5 php5-cli  php5-gd libssh2-php php5-curl",None,ssh)
		ca.log("Installed apache2.",output,60)
		ca.log("Installing mysql...",'',61)
		mysql_root_pass = ''.join(random.choice('0123456789abcdef') for i in range(8))
		mysql_drupal_pass = ''.join(random.choice('0123456789abcdef') for i in range(8))
		drupal_admin_pass = ''.join(random.choice('0123456789abcdef') for i in range(8))
		output = run_command("sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password password "+mysql_root_pass+"'",None,ssh)
		output += run_command("sudo debconf-set-selections <<< 'mysql-server-5.5 mysql-server/root_password_again password "+mysql_root_pass+"'",None,ssh)
		output += run_command("sudo apt-get -y install mysql-server php5-mysql",None,ssh)
		ca.log("Installed mysql.",output,70)
		ca.log("Reconfiguring and reinstalling apache...",'',71)
		output = run_command("sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/",None,ssh)
		output += run_command("sudo sed -i 11's/None/All/' /etc/apache2/sites-enabled/000-default",None,ssh)
		output += run_command("sudo apachectl restart",None,ssh)
		ca.log("Restarted apache2.",output,75)
		ca.log("Creating mysql drupal database...",'',76)
		output = run_command("mysqladmin -u root --password="******" create drupal",None,ssh)
		output += run_command("""mysql -u root --password='******' drupal -e 'GRANT ALL PRIVILEGES ON drupal.* TO "drupal"@"localhost" IDENTIFIED BY "%s";FLUSH PRIVILEGES;'""" % (mysql_root_pass, mysql_drupal_pass),None,ssh)
		ca.log("Created mysql user.",output,80)
		ca.log("Downloading drush and drupal...",'',81)
		output = run_command("sudo apt-get install -y drush",None,ssh)		
		output += run_command("wget http://ftp.drupal.org/files/projects/drupal-7.22.tar.gz",None,ssh)
		ca.log("Downloaded drush and drupal.",output,85)
		ca.log("Configuring drupal...",'',86)
		output = run_command("sudo rm -f /var/www/index.html",None,ssh)
		output += run_command("sudo tar fxvz drupal-7.22.tar.gz -C /var/www/ --strip-components=1",None,ssh)
		output += run_command("sudo chown -R ubuntu:www-data /var/www",None,ssh)
		output += run_command("sudo sh -c 'cd /var/www ; drush site-install standard -y --db-url=mysql://drupal:"+mysql_drupal_pass+"@localhost/drupal --site-name=\""+ca.conf['name']+"\" --account-pass="******"'",None,ssh)
		output += run_command("sudo mkdir /var/www/sites/default/private",None,ssh)
		output += run_command("sudo mkdir /var/www/sites/default/private/files",None,ssh)
		output += run_command("sudo chown -R ubuntu:www-data /var/www/sites/default",None,ssh)
		output += run_command("sudo chmod 777 /var/www/sites/default/files",None,ssh)
		output += run_command("sudo chmod 777 /var/www/sites/default/private",None,ssh)
		output += run_command("sudo chmod 777 /var/www/sites/default/private/files",None,ssh)
		
		ca.log("Configured drupal, admin password: "******"http://"+server_address+"/").read()
		except:
			ca.log("Server not found, something went wrong.")
			exit()

		ca.log("Drupal up at http://"+server_address+"/, sending email.",'',95)

		ca.email("Apache 2 & Drupal Setup on "+ca.conf['name']+" Complete","""
Server setup complete.  Login to your new drupal server at:
		
username: admin
password: %s
url:      http://%s/
		
		""" % (drupal_admin_pass,server_address))
		

		ca.log("Server up at http://"+server_address+"/ and activation email sent.",'',100)