~justin-fathomdb/nova/justinsb-openstack-api-volumes

« back to all changes in this revision

Viewing changes to nova/crypto.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
 
2
# Copyright [2010] [Anso Labs, LLC]
 
3
#
 
4
#    Licensed under the Apache License, Version 2.0 (the "License");
 
5
#    you may not use this file except in compliance with the License.
 
6
#    You may obtain a copy of the License at
 
7
#
 
8
#        http://www.apache.org/licenses/LICENSE-2.0
 
9
#
 
10
#    Unless required by applicable law or agreed to in writing, software
 
11
#    distributed under the License is distributed on an "AS IS" BASIS,
 
12
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
#    See the License for the specific language governing permissions and
 
14
#    limitations under the License.
 
15
 
 
16
"""
 
17
Wrappers around standard crypto, including root and intermediate CAs,
 
18
SSH keypairs and x509 certificates.
 
19
"""
 
20
 
 
21
import hashlib
 
22
import logging
 
23
import os
 
24
import shutil
 
25
import tempfile
 
26
import time
 
27
import utils
 
28
 
 
29
from nova import vendor
 
30
import M2Crypto
 
31
 
 
32
from nova import exception
 
33
from nova import flags
 
34
 
 
35
 
 
36
FLAGS = flags.FLAGS
 
37
flags.DEFINE_string('ca_file', 'cacert.pem', 'Filename of root CA')
 
38
flags.DEFINE_string('keys_path', utils.abspath('../keys'), 'Where we keep our keys')
 
39
flags.DEFINE_string('ca_path', utils.abspath('../CA'), 'Where we keep our root CA')
 
40
flags.DEFINE_boolean('use_intermediate_ca', False, 'Should we use intermediate CAs for each project?')
 
41
 
 
42
 
 
43
def ca_path(username):
 
44
    if username:
 
45
        return "%s/INTER/%s/cacert.pem" % (FLAGS.ca_path, username)
 
46
    return "%s/cacert.pem" % (FLAGS.ca_path)
 
47
 
 
48
def fetch_ca(username=None, chain=True):
 
49
    if not FLAGS.use_intermediate_ca:
 
50
        username = None
 
51
    buffer = ""
 
52
    if username:
 
53
        with open(ca_path(username),"r") as cafile:
 
54
            buffer += cafile.read()
 
55
    if username and not chain:
 
56
        return buffer
 
57
    with open(ca_path(None),"r") as cafile:
 
58
        buffer += cafile.read()
 
59
    return buffer
 
60
 
 
61
def generate_key_pair(bits=1024):
 
62
    # what is the magic 65537?
 
63
 
 
64
    tmpdir = tempfile.mkdtemp()
 
65
    keyfile = os.path.join(tmpdir, 'temp')
 
66
    utils.execute('ssh-keygen -q -b %d -N "" -f %s' % (bits, keyfile))
 
67
    (out, err) = utils.execute('ssh-keygen -q -l -f %s.pub' % (keyfile))
 
68
    fingerprint = out.split(' ')[1]
 
69
    private_key = open(keyfile).read()
 
70
    public_key = open(keyfile + '.pub').read()
 
71
 
 
72
    shutil.rmtree(tmpdir)
 
73
    # code below returns public key in pem format
 
74
    # key = M2Crypto.RSA.gen_key(bits, 65537, callback=lambda: None)
 
75
    # private_key = key.as_pem(cipher=None)
 
76
    # bio = M2Crypto.BIO.MemoryBuffer()
 
77
    # key.save_pub_key_bio(bio)
 
78
    # public_key = bio.read()
 
79
    # public_key, err = execute('ssh-keygen -y -f /dev/stdin', private_key)
 
80
 
 
81
    return (private_key, public_key, fingerprint)
 
82
 
 
83
 
 
84
def ssl_pub_to_ssh_pub(ssl_public_key, name='root', suffix='nova'):
 
85
    """requires lsh-utils"""
 
86
    convert="sed -e'1d' -e'$d' |  pkcs1-conv --public-key-info --base-64 |" \
 
87
    + " sexp-conv |  sed -e'1s/(rsa-pkcs1/(rsa-pkcs1-sha1/' |  sexp-conv -s" \
 
88
    + " transport | lsh-export-key --openssh"
 
89
    (out, err) = utils.execute(convert, ssl_public_key)
 
90
    if err:
 
91
        raise exception.Error("Failed to generate key: %s", err)
 
92
    return '%s %s@%s\n' %(out.strip(), name, suffix)
 
93
 
 
94
 
 
95
def generate_x509_cert(subject="/C=US/ST=California/L=The Mission/O=CloudFed/OU=NOVA/CN=foo", bits=1024):
 
96
    tmpdir = tempfile.mkdtemp()
 
97
    keyfile = os.path.abspath(os.path.join(tmpdir, 'temp.key'))
 
98
    csrfile = os.path.join(tmpdir, 'temp.csr')
 
99
    logging.debug("openssl genrsa -out %s %s" % (keyfile, bits))
 
100
    utils.runthis("Generating private key: %s", "openssl genrsa -out %s %s" % (keyfile, bits))
 
101
    utils.runthis("Generating CSR: %s", "openssl req -new -key %s -out %s -batch -subj %s" % (keyfile, csrfile, subject))
 
102
    private_key = open(keyfile).read()
 
103
    csr = open(csrfile).read()
 
104
    shutil.rmtree(tmpdir)
 
105
    return (private_key, csr)
 
106
 
 
107
 
 
108
def sign_csr(csr_text, intermediate=None):
 
109
    if not FLAGS.use_intermediate_ca:
 
110
        intermediate = None
 
111
    if not intermediate:
 
112
        return _sign_csr(csr_text, FLAGS.ca_path)
 
113
    user_ca = "%s/INTER/%s" % (FLAGS.ca_path, intermediate)
 
114
    if not os.path.exists(user_ca):
 
115
        start = os.getcwd()
 
116
        os.chdir(FLAGS.ca_path)
 
117
        utils.runthis("Generating intermediate CA: %s", "sh geninter.sh %s" % (intermediate))
 
118
        os.chdir(start)
 
119
    return _sign_csr(csr_text, user_ca)
 
120
 
 
121
 
 
122
def _sign_csr(csr_text, ca_folder):
 
123
    tmpfolder = tempfile.mkdtemp()
 
124
    csrfile = open("%s/inbound.csr" % (tmpfolder), "w")
 
125
    csrfile.write(csr_text)
 
126
    csrfile.close()
 
127
    logging.debug("Flags path: %s" % ca_folder)
 
128
    start = os.getcwd()
 
129
    # Change working dir to CA
 
130
    os.chdir(ca_folder)
 
131
    utils.runthis("Signing cert: %s", "openssl ca -batch -out %s/outbound.crt -config ./openssl.cnf -infiles %s/inbound.csr" % (tmpfolder, tmpfolder))
 
132
    os.chdir(start)
 
133
    with open("%s/outbound.crt" % (tmpfolder), "r") as crtfile:
 
134
        return crtfile.read()
 
135
 
 
136
 
 
137
def mkreq(bits, subject="foo", ca=0):
 
138
    pk = M2Crypto.EVP.PKey()
 
139
    req = M2Crypto.X509.Request()
 
140
    rsa = M2Crypto.RSA.gen_key(bits, 65537, callback=lambda: None)
 
141
    pk.assign_rsa(rsa)
 
142
    rsa = None # should not be freed here
 
143
    req.set_pubkey(pk)
 
144
    req.set_subject(subject)
 
145
    req.sign(pk,'sha512')
 
146
    assert req.verify(pk)
 
147
    pk2 = req.get_pubkey()
 
148
    assert req.verify(pk2)
 
149
    return req, pk
 
150
 
 
151
 
 
152
def mkcacert(subject='nova', years=1):
 
153
    req, pk = mkreq(2048, subject, ca=1)
 
154
    pkey = req.get_pubkey()
 
155
    sub = req.get_subject()
 
156
    cert = M2Crypto.X509.X509()
 
157
    cert.set_serial_number(1)
 
158
    cert.set_version(2)
 
159
    cert.set_subject(sub) # FIXME subject is not set in mkreq yet
 
160
    t = long(time.time()) + time.timezone
 
161
    now = M2Crypto.ASN1.ASN1_UTCTIME()
 
162
    now.set_time(t)
 
163
    nowPlusYear = M2Crypto.ASN1.ASN1_UTCTIME()
 
164
    nowPlusYear.set_time(t + (years * 60 * 60 * 24 * 365))
 
165
    cert.set_not_before(now)
 
166
    cert.set_not_after(nowPlusYear)
 
167
    issuer = M2Crypto.X509.X509_Name()
 
168
    issuer.C = "US"
 
169
    issuer.CN = subject
 
170
    cert.set_issuer(issuer)
 
171
    cert.set_pubkey(pkey)
 
172
    ext = M2Crypto.X509.new_extension('basicConstraints', 'CA:TRUE')
 
173
    cert.add_ext(ext)
 
174
    cert.sign(pk, 'sha512')
 
175
 
 
176
    # print 'cert', dir(cert)
 
177
    print cert.as_pem()
 
178
    print pk.get_rsa().as_pem()
 
179
 
 
180
    return cert, pk, pkey
 
181
 
 
182
 
 
183
 
 
184
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
 
185
#
 
186
# Permission is hereby granted, free of charge, to any person obtaining a
 
187
# copy of this software and associated documentation files (the
 
188
# "Software"), to deal in the Software without restriction, including
 
189
# without limitation the rights to use, copy, modify, merge, publish, dis-
 
190
# tribute, sublicense, and/or sell copies of the Software, and to permit
 
191
# persons to whom the Software is furnished to do so, subject to the fol-
 
192
# lowing conditions:
 
193
#
 
194
# The above copyright notice and this permission notice shall be included
 
195
# in all copies or substantial portions of the Software.
 
196
#
 
197
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 
198
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
 
199
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
 
200
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
 
201
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 
202
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 
203
# IN THE SOFTWARE.
 
204
# http://code.google.com/p/boto
 
205
 
 
206
def compute_md5(fp):
 
207
    """
 
208
    @type fp: file
 
209
    @param fp: File pointer to the file to MD5 hash.  The file pointer will be
 
210
               reset to the beginning of the file before the method returns.
 
211
 
 
212
    @rtype: tuple
 
213
    @return: the hex digest version of the MD5 hash
 
214
    """
 
215
    m = hashlib.md5()
 
216
    fp.seek(0)
 
217
    s = fp.read(8192)
 
218
    while s:
 
219
        m.update(s)
 
220
        s = fp.read(8192)
 
221
    hex_md5 = m.hexdigest()
 
222
    # size = fp.tell()
 
223
    fp.seek(0)
 
224
    return hex_md5