blob: 2a4ea1d13f24e827012377dcb316a194ba87ed66 [file] [log] [blame]
James E. Blairc49e5e72017-03-16 14:56:32 -07001#!/usr/bin/env python
2
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15import argparse
Tobias Henkel39d6dcd2017-06-24 21:26:57 +020016import base64
James E. Blair9118c012017-08-03 11:19:16 -070017import math
James E. Blairc49e5e72017-03-16 14:56:32 -070018import os
James E. Blair9118c012017-08-03 11:19:16 -070019import re
James E. Blairc49e5e72017-03-16 14:56:32 -070020import subprocess
21import sys
22import tempfile
James E. Blair9118c012017-08-03 11:19:16 -070023import textwrap
Tobias Henkel39d6dcd2017-06-24 21:26:57 +020024
25# we to import Request and urlopen differently for python 2 and 3
26try:
27 from urllib.request import Request
28 from urllib.request import urlopen
29except ImportError:
30 from urllib2 import Request
31 from urllib2 import urlopen
James E. Blairc49e5e72017-03-16 14:56:32 -070032
33DESCRIPTION = """Encrypt a secret for Zuul.
34
35This program fetches a project-specific public key from a Zuul server and
36uses that to encrypt a secret. The only pre-requisite is an installed
37OpenSSL binary.
38"""
39
40
41def main():
42 parser = argparse.ArgumentParser(description=DESCRIPTION)
43 parser.add_argument('url',
44 help="The base URL of the zuul server and tenant. "
45 "E.g., https://zuul.example.com/tenant-name")
James E. Blairc49e5e72017-03-16 14:56:32 -070046 # TODO(jeblair): Throw a fit if SSL is not used.
James E. Blairc49e5e72017-03-16 14:56:32 -070047 parser.add_argument('project',
48 help="The name of the project.")
49 parser.add_argument('--infile',
50 default=None,
51 help="A filename whose contents will be encrypted. "
52 "If not supplied, the value will be read from "
53 "standard input.")
54 parser.add_argument('--outfile',
55 default=None,
56 help="A filename to which the encrypted value will be "
57 "written. If not supplied, the value will be written "
58 "to standard output.")
59 args = parser.parse_args()
60
James E. Blair3f42c532017-09-15 20:12:30 -060061 req = Request("%s/%s.pub" % (args.url, args.project))
Tobias Henkel39d6dcd2017-06-24 21:26:57 +020062 pubkey = urlopen(req)
James E. Blairc49e5e72017-03-16 14:56:32 -070063
64 if args.infile:
65 with open(args.infile) as f:
66 plaintext = f.read()
67 else:
68 plaintext = sys.stdin.read()
69
James E. Blair9118c012017-08-03 11:19:16 -070070 plaintext = plaintext.encode("utf-8")
71
James E. Blairc49e5e72017-03-16 14:56:32 -070072 pubkey_file = tempfile.NamedTemporaryFile(delete=False)
73 try:
74 pubkey_file.write(pubkey.read())
75 pubkey_file.close()
76
James E. Blair9118c012017-08-03 11:19:16 -070077 p = subprocess.Popen(['openssl', 'rsa', '-text',
78 '-pubin', '-in',
James E. Blairc49e5e72017-03-16 14:56:32 -070079 pubkey_file.name],
James E. Blairc49e5e72017-03-16 14:56:32 -070080 stdout=subprocess.PIPE)
James E. Blair9118c012017-08-03 11:19:16 -070081 (stdout, stderr) = p.communicate()
James E. Blairc49e5e72017-03-16 14:56:32 -070082 if p.returncode != 0:
83 raise Exception("Return code %s from openssl" % p.returncode)
James E. Blair9118c012017-08-03 11:19:16 -070084 output = stdout.decode('utf-8')
Clint Byrum2dc31dd2017-11-01 16:49:28 -070085 openssl_version = subprocess.check_output(
86 ['openssl', 'version']).split()[1]
87 if openssl_version.startswith(b'0.'):
88 m = re.match(r'^Modulus \((\d+) bit\):$', output, re.MULTILINE)
89 else:
90 m = re.match(r'^Public-Key: \((\d+) bit\)$', output, re.MULTILINE)
James E. Blair9118c012017-08-03 11:19:16 -070091 nbits = int(m.group(1))
92 nbytes = int(nbits / 8)
93 max_bytes = nbytes - 42 # PKCS1-OAEP overhead
94 chunks = int(math.ceil(float(len(plaintext)) / max_bytes))
95
96 ciphertext_chunks = []
97
98 print("Public key length: {} bits ({} bytes)".format(nbits, nbytes))
99 print("Max plaintext length per chunk: {} bytes".format(max_bytes))
100 print("Input plaintext length: {} bytes".format(len(plaintext)))
101 print("Number of chunks: {}".format(chunks))
102
103 for count in range(chunks):
104 chunk = plaintext[int(count * max_bytes):
105 int((count + 1) * max_bytes)]
106 p = subprocess.Popen(['openssl', 'rsautl', '-encrypt',
107 '-oaep', '-pubin', '-inkey',
108 pubkey_file.name],
109 stdin=subprocess.PIPE,
110 stdout=subprocess.PIPE)
111 (stdout, stderr) = p.communicate(chunk)
112 if p.returncode != 0:
113 raise Exception("Return code %s from openssl" % p.returncode)
114 ciphertext_chunks.append(base64.b64encode(stdout).decode('utf-8'))
115
James E. Blairc49e5e72017-03-16 14:56:32 -0700116 finally:
117 os.unlink(pubkey_file.name)
118
James E. Blair9118c012017-08-03 11:19:16 -0700119 output = textwrap.dedent(
120 '''
121 - secret:
122 name: <name>
123 data:
124 <fieldname>: !encrypted/pkcs1-oaep
125 ''')
126
127 twrap = textwrap.TextWrapper(width=79,
128 initial_indent=' ' * 8,
129 subsequent_indent=' ' * 10)
130 for chunk in ciphertext_chunks:
131 chunk = twrap.fill('- ' + chunk)
132 output += chunk + '\n'
133
James E. Blairc49e5e72017-03-16 14:56:32 -0700134 if args.outfile:
James E. Blair9118c012017-08-03 11:19:16 -0700135 with open(args.outfile, "w") as f:
136 f.write(output)
James E. Blairc49e5e72017-03-16 14:56:32 -0700137 else:
James E. Blair9118c012017-08-03 11:19:16 -0700138 print(output)
James E. Blairc49e5e72017-03-16 14:56:32 -0700139
140
141if __name__ == '__main__':
142 main()