1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
# Copyright [2010] [Anso Labs, LLC]
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
8
# http://www.apache.org/licenses/LICENSE-2.0
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.
17
Wrappers around standard crypto, including root and intermediate CAs,
18
SSH keypairs and x509 certificates.
29
from nova import vendor
32
from nova import exception
33
from nova import 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?')
43
def ca_path(username):
45
return "%s/INTER/%s/cacert.pem" % (FLAGS.ca_path, username)
46
return "%s/cacert.pem" % (FLAGS.ca_path)
48
def fetch_ca(username=None, chain=True):
49
if not FLAGS.use_intermediate_ca:
53
with open(ca_path(username),"r") as cafile:
54
buffer += cafile.read()
55
if username and not chain:
57
with open(ca_path(None),"r") as cafile:
58
buffer += cafile.read()
61
def generate_key_pair(bits=1024):
62
# what is the magic 65537?
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()
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)
81
return (private_key, public_key, fingerprint)
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)
91
raise exception.Error("Failed to generate key: %s", err)
92
return '%s %s@%s\n' %(out.strip(), name, suffix)
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)
108
def sign_csr(csr_text, intermediate=None):
109
if not FLAGS.use_intermediate_ca:
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):
116
os.chdir(FLAGS.ca_path)
117
utils.runthis("Generating intermediate CA: %s", "sh geninter.sh %s" % (intermediate))
119
return _sign_csr(csr_text, user_ca)
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)
127
logging.debug("Flags path: %s" % ca_folder)
129
# Change working dir to CA
131
utils.runthis("Signing cert: %s", "openssl ca -batch -out %s/outbound.crt -config ./openssl.cnf -infiles %s/inbound.csr" % (tmpfolder, tmpfolder))
133
with open("%s/outbound.crt" % (tmpfolder), "r") as crtfile:
134
return crtfile.read()
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)
142
rsa = None # should not be freed here
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)
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)
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()
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()
170
cert.set_issuer(issuer)
171
cert.set_pubkey(pkey)
172
ext = M2Crypto.X509.new_extension('basicConstraints', 'CA:TRUE')
174
cert.sign(pk, 'sha512')
176
# print 'cert', dir(cert)
178
print pk.get_rsa().as_pem()
180
return cert, pk, pkey
184
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
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-
194
# The above copyright notice and this permission notice shall be included
195
# in all copies or substantial portions of the Software.
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
204
# http://code.google.com/p/boto
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.
213
@return: the hex digest version of the MD5 hash
221
hex_md5 = m.hexdigest()