James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 1 | #!/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 | |
| 15 | import argparse |
Tobias Henkel | 39d6dcd | 2017-06-24 21:26:57 +0200 | [diff] [blame] | 16 | import base64 |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 17 | import math |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 18 | import os |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 19 | import re |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 20 | import subprocess |
| 21 | import sys |
| 22 | import tempfile |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 23 | import textwrap |
Tobias Henkel | 39d6dcd | 2017-06-24 21:26:57 +0200 | [diff] [blame] | 24 | |
| 25 | # we to import Request and urlopen differently for python 2 and 3 |
| 26 | try: |
| 27 | from urllib.request import Request |
| 28 | from urllib.request import urlopen |
| 29 | except ImportError: |
| 30 | from urllib2 import Request |
| 31 | from urllib2 import urlopen |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 32 | |
| 33 | DESCRIPTION = """Encrypt a secret for Zuul. |
| 34 | |
| 35 | This program fetches a project-specific public key from a Zuul server and |
| 36 | uses that to encrypt a secret. The only pre-requisite is an installed |
| 37 | OpenSSL binary. |
| 38 | """ |
| 39 | |
| 40 | |
| 41 | def 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. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 46 | # TODO(jeblair): Throw a fit if SSL is not used. |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 47 | parser.add_argument('project', |
| 48 | help="The name of the project.") |
Clint Byrum | 04bcbe1 | 2017-12-30 06:20:39 -0800 | [diff] [blame] | 49 | parser.add_argument('--strip', action='store_true', default=False, |
| 50 | help="Strip whitespace from beginning/end of input.") |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 51 | parser.add_argument('--infile', |
| 52 | default=None, |
| 53 | help="A filename whose contents will be encrypted. " |
| 54 | "If not supplied, the value will be read from " |
| 55 | "standard input.") |
| 56 | parser.add_argument('--outfile', |
| 57 | default=None, |
| 58 | help="A filename to which the encrypted value will be " |
| 59 | "written. If not supplied, the value will be written " |
| 60 | "to standard output.") |
| 61 | args = parser.parse_args() |
| 62 | |
Fabien Boucher | bf331d4 | 2017-09-21 17:40:26 +0200 | [diff] [blame] | 63 | req = Request("%s/%s.pub" % (args.url.rstrip('/'), args.project)) |
Tobias Henkel | 39d6dcd | 2017-06-24 21:26:57 +0200 | [diff] [blame] | 64 | pubkey = urlopen(req) |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 65 | |
| 66 | if args.infile: |
| 67 | with open(args.infile) as f: |
| 68 | plaintext = f.read() |
| 69 | else: |
| 70 | plaintext = sys.stdin.read() |
| 71 | |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 72 | plaintext = plaintext.encode("utf-8") |
Clint Byrum | 04bcbe1 | 2017-12-30 06:20:39 -0800 | [diff] [blame] | 73 | if args.strip: |
| 74 | plaintext = plaintext.strip() |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 75 | |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 76 | pubkey_file = tempfile.NamedTemporaryFile(delete=False) |
| 77 | try: |
| 78 | pubkey_file.write(pubkey.read()) |
| 79 | pubkey_file.close() |
| 80 | |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 81 | p = subprocess.Popen(['openssl', 'rsa', '-text', |
| 82 | '-pubin', '-in', |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 83 | pubkey_file.name], |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 84 | stdout=subprocess.PIPE) |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 85 | (stdout, stderr) = p.communicate() |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 86 | if p.returncode != 0: |
| 87 | raise Exception("Return code %s from openssl" % p.returncode) |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 88 | output = stdout.decode('utf-8') |
Clint Byrum | 2dc31dd | 2017-11-01 16:49:28 -0700 | [diff] [blame] | 89 | openssl_version = subprocess.check_output( |
| 90 | ['openssl', 'version']).split()[1] |
| 91 | if openssl_version.startswith(b'0.'): |
| 92 | m = re.match(r'^Modulus \((\d+) bit\):$', output, re.MULTILINE) |
| 93 | else: |
| 94 | m = re.match(r'^Public-Key: \((\d+) bit\)$', output, re.MULTILINE) |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 95 | nbits = int(m.group(1)) |
| 96 | nbytes = int(nbits / 8) |
| 97 | max_bytes = nbytes - 42 # PKCS1-OAEP overhead |
| 98 | chunks = int(math.ceil(float(len(plaintext)) / max_bytes)) |
| 99 | |
| 100 | ciphertext_chunks = [] |
| 101 | |
| 102 | print("Public key length: {} bits ({} bytes)".format(nbits, nbytes)) |
| 103 | print("Max plaintext length per chunk: {} bytes".format(max_bytes)) |
| 104 | print("Input plaintext length: {} bytes".format(len(plaintext))) |
| 105 | print("Number of chunks: {}".format(chunks)) |
| 106 | |
| 107 | for count in range(chunks): |
| 108 | chunk = plaintext[int(count * max_bytes): |
| 109 | int((count + 1) * max_bytes)] |
| 110 | p = subprocess.Popen(['openssl', 'rsautl', '-encrypt', |
| 111 | '-oaep', '-pubin', '-inkey', |
| 112 | pubkey_file.name], |
| 113 | stdin=subprocess.PIPE, |
| 114 | stdout=subprocess.PIPE) |
| 115 | (stdout, stderr) = p.communicate(chunk) |
| 116 | if p.returncode != 0: |
| 117 | raise Exception("Return code %s from openssl" % p.returncode) |
| 118 | ciphertext_chunks.append(base64.b64encode(stdout).decode('utf-8')) |
| 119 | |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 120 | finally: |
| 121 | os.unlink(pubkey_file.name) |
| 122 | |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 123 | output = textwrap.dedent( |
| 124 | ''' |
| 125 | - secret: |
| 126 | name: <name> |
| 127 | data: |
| 128 | <fieldname>: !encrypted/pkcs1-oaep |
| 129 | ''') |
| 130 | |
| 131 | twrap = textwrap.TextWrapper(width=79, |
| 132 | initial_indent=' ' * 8, |
| 133 | subsequent_indent=' ' * 10) |
| 134 | for chunk in ciphertext_chunks: |
| 135 | chunk = twrap.fill('- ' + chunk) |
| 136 | output += chunk + '\n' |
| 137 | |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 138 | if args.outfile: |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 139 | with open(args.outfile, "w") as f: |
| 140 | f.write(output) |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 141 | else: |
James E. Blair | 9118c01 | 2017-08-03 11:19:16 -0700 | [diff] [blame] | 142 | print(output) |
James E. Blair | c49e5e7 | 2017-03-16 14:56:32 -0700 | [diff] [blame] | 143 | |
| 144 | |
| 145 | if __name__ == '__main__': |
| 146 | main() |