Exemplo n.º 1
0
def   _kms(options):
        if options['profile'] != '':
             conn = kms.connect_to_region(options['region'], profile_name=options['profile'])
        else:
            conn = kms.connect_to_region(options['region'], aws_access_key_id=options['AWS_ACCESS_KEY_ID'], aws_secret_access_key=options['AWS_SECRET_ACCESS_KEY'])
        if options['action'] == 'list':
            (key_id, key_arn) = _kms_find(conn, options)
            if key_id != None:
                print key_arn
        elif options['action'] == 'create':
            _kms_create(conn, options)
        elif options['action'] == 'disable':
            _kms_disable(conn, options)
Exemplo n.º 2
0
def main():

    if 'KMS_KEY_ID' not in os.environ:
        print("ERROR: The KMS_KEY_ID environment variable is required. It \
            is a unique identifier of the customer master. This can be an \
            ARN, an alias, or the Key ID.", file=sys.stderr)
        return
    else:
        key_id = os.environ['KMS_KEY_ID']

    if 'KMS_EC2_REGION' in os.environ:
        region = os.environ['KMS_EC2_REGION']
    elif 'EC2_REGION' in os.environ:
        region = os.environ['EC2_REGION']
    else:
        region = 'us-east-1'

    try:
        kms = connect_to_region(region)

        plaintext_password = ''.join(random.SystemRandom().choice(string.digits
            + string.letters + string.punctuation) for _ in xrange(PASSWORD_LENGTH))
        encryption_dict = kms.encrypt(key_id, plaintext_password)
        encrypted_password = b64encode(encryption_dict['CiphertextBlob'])

        print(plaintext_password)
        print("Encrypted password:\n" + encrypted_password, file=sys.stderr)

    except NotFoundException, e:
        print("ERROR: Key not found. Is it in {0}?".format(region), file=sys.stderr)
Exemplo n.º 3
0
def main():

    if 'KMS_ENCRYPTED_PASSWORD' not in os.environ:
        print(
            "ERROR: The KMS_ENCRYPTED_PASSWORD environment variable is required.",
            file=sys.stderr)
        return
    else:
        encrypted_password = os.environ['KMS_ENCRYPTED_PASSWORD']

    if 'KMS_EC2_REGION' in os.environ:
        region = os.environ['KMS_EC2_REGION']
    elif 'EC2_REGION' in os.environ:
        region = os.environ['EC2_REGION']
    else:
        region = 'us-east-1'

    try:
        kms = connect_to_region(region)
        password = kms.decrypt(b64decode(encrypted_password))
        print(password['Plaintext'])

    except Exception, e:
        print("ERROR: Decryption failed. Do you have permission to decrypt?",
              file=sys.stderr)
Exemplo n.º 4
0
 def decrypt(value):
     kms_obj = kms.connect_to_region(
         os.environ.get('AWS_DEFAULT_REGION'))
     try:
         plaintext = kms_obj.decrypt(unhexlify(value))['Plaintext']
     except Exception, e:
         raise Exception('Unable to decrypt value: {}'.format(e))
Exemplo n.º 5
0
    def _connect_kms(self):
        """
        Attempts to get a KMSConnection first from sts. If sts is not configured, then it will obtain a connection using
        the configured profile (if profile is not configured default is used)
        """
        boto.connect_kms()
        if self.sts:
            self.kms = kms.connect_to_region(self.config.region,
                                             aws_access_key_id=self.sts["access_key"],
                                             aws_secret_access_key=self.sts["secret_key"],
                                             security_token=self.sts["session_token"])

        elif self.config.aws_profile:
            self.kms = kms.connect_to_region(self.config.region, profile_name=self.config.aws_profile)
        else:
            self.kms = kms.connect_to_region(self.config.region)
Exemplo n.º 6
0
def kms_decrypt_data(aws_data, encrypted_data, ciphertext_blob):
    """Decrypt data"""
    conn = kms.connect_to_region(aws_data['region'])

    decrypted_key = conn.decrypt(ciphertext_blob).get('Plaintext')
    crypter = AES.new(decrypted_key)

    return crypter.decrypt(base64.b64decode(encrypted_data)).rstrip()
Exemplo n.º 7
0
def kms_encrypt_data(aws_data, plaintext_message):
    """Encrypt plaintext"""
    conn = kms.connect_to_region(aws_data['region'])
    arn = get_arn(aws_data)

    data_key = conn.generate_data_key(arn, key_spec='AES_128')
    ciphertext_blob = data_key.get('CiphertextBlob')
    plaintext_key = data_key.get('Plaintext')

    # Note, does not use IV or specify mode... for demo purposes only.
    crypter = AES.new(plaintext_key)
    encrypted_data = base64.b64encode(crypter.encrypt(pad(plaintext_message)))

    # Need to preserve both of these data elements
    return encrypted_data, ciphertext_blob
def main():

    if 'KMS_ENCRYPTED_PASSWORD' not in os.environ:
        print("ERROR: The KMS_ENCRYPTED_PASSWORD environment variable is required.", file=sys.stderr)
        return
    else:
        encrypted_password = os.environ['KMS_ENCRYPTED_PASSWORD']

    if 'KMS_EC2_REGION' in os.environ:
        region = os.environ['KMS_EC2_REGION']
    elif 'EC2_REGION' in os.environ:
        region = os.environ['EC2_REGION']
    else:
        region = 'us-east-1'

    try:
        kms = connect_to_region(region)
        password = kms.decrypt(b64decode(encrypted_password))
        print(password['Plaintext'])

    except Exception, e:
        print("ERROR: Decryption failed. Do you have permission to decrypt?", file=sys.stderr)
Exemplo n.º 9
0
def main():
    global VERSION
    parser = argparse.ArgumentParser(prog="kms-client")
    parser.add_argument('-v', '--version', action='version',
        version="%(prog)s %(VERSION)s" %
            { 'prog': sys.argv[0], 'VERSION': VERSION }
    )
    ek_group = parser.add_mutually_exclusive_group()
    ek_group.add_argument('-e', '--encrypt', action='store_true',
        help="Encrypt the data")
    ek_group.add_argument('-d', '--decrypt', action='store_true',
        help="Decrypt the data")
    parser.add_argument('-k', '--key', action="store",
        help="The key alias, id, or arn to use for encryption")
    parser.add_argument('-r', '--region', action='store',
        default="us-east-1", help="Region to connect to")
    parser.add_argument("infile", action="store", default="-",
        type=argparse.FileType('r+b'),
        help="File to encrypt or decrypt, - for stdin/out")
    parser.add_argument("outfile", action="store", default="-",
        type=argparse.FileType('wb'),
        help="File to encrypt or decrypt, - for stdin/out")
    args = vars(parser.parse_args())

    if args['encrypt'] and args['key'] is None:
        logging.error("Must provide a key for encryption")
        sys.exit(1)

    con = kms.connect_to_region(args['region'])
    
    with args['outfile'] as out:
        indata = args['infile'].read()
        datalen = len(indata)

        if args['encrypt']:
            if datalen >= 4096:
                keydata = con.generate_data_key(args['key'], key_spec='AES_128')
                iv_seed = con.generate_random(1024)['Plaintext']
                iv = hashlib.md5(iv_seed).digest()
                out.write(struct.pack('!Q', datalen))
                out.write(iv)
                out.write(keydata['CiphertextBlob'])
                enc = AES.new(keydata['Plaintext'], AES.MODE_CBC, iv)
                del keydata
                chunk = 0
                while chunk * 16 < datalen:
                    if datalen - chunk * 16 < 0:
                        indata.append('*' * abs(datalen - chunk * 16))
                    out.write(enc.encrypt(indata[chunk*16:chunk*16+16]))
                    chunk += 1
            else:
                ciphertext = con.encrypt(args['key'], indata)
                out.write(ciphertext['CiphertextBlob'])
        elif args['decrypt']:
            # Encrypted keys are 188 bytes
            qsize = struct.calcsize('Q')
            if datalen - (qsize + 188) >= 4096:
                payloadsize = struct.unpack('!Q', indata[0:qsize])[0]
                iv = indata[qsize:qsize+16]
                keydata = con.decrypt(indata[qsize+16:qsize+16+188]) 
                encdata = bytes(indata[qsize+16+188:])
                enclen = len(encdata)
                data = b''
                chunk = 0
                dec = AES.new(keydata['Plaintext'], AES.MODE_CBC, iv)
                del keydata
                while chunk * 16 <= enclen:
                    data += dec.decrypt(encdata[chunk*16:chunk*16+16])
                    chunk += 1
                out.write(data[:payloadsize])
            else:
                plaintext = con.decrypt(indata)
                out.write(plaintext['Plaintext'])
        else:
            logging.error("Must provide either -e or -d")
            sys.exit(1)
Exemplo n.º 10
0
 def __init__(self, region="eu-west-1"):
     self.conn = kms.connect_to_region(region)
Exemplo n.º 11
0
 def __init__(self, region="eu-west-1"):
     self.conn = kms.connect_to_region(region)
Exemplo n.º 12
0
	def __init__(self, config):	
		self.conn = kms.connect_to_region(config["region"])
Exemplo n.º 13
0
def encrypt(data):
    fileinfo = open(data['path'])
    info = fileinfo.read()
    conn = kms.connect_to_region(data['region'])
    encrypted = conn.encrypt(key_id=data['arn'], plaintext=info)
    return True, encrypted['CiphertextBlob']