summaryrefslogtreecommitdiff
path: root/src/kms/awskms.rs
blob: 39986bc698938752265982f575855fa4c32833d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Copyright 2017-2019 int08h LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[cfg(feature = "awskms")]
pub mod inner {
    use std::collections::HashMap;
    use std::default::Default;
    use std::error::Error;
    use std::fmt;
    use std::fmt::Formatter;
    use std::str::FromStr;

    use rusoto_core::Region;
    use rusoto_kms::{DecryptRequest, EncryptRequest, Kms, KmsClient};
    use crate::kms::{EncryptedDEK, KmsError, KmsProvider, PlaintextDEK, AD, DEK_SIZE_BYTES};

    /// Amazon Web Services Key Management Service
    /// https://aws.amazon.com/kms/
    pub struct AwsKms {
        kms_client: KmsClient,
        key_id: String,
    }

    impl AwsKms {
        /// Create a new instance from the full ARN of a AWS KMS key. The ARN is expected
        /// to be of the form `arn:aws:kms:some-aws-region:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab`
        pub fn from_arn(arn: &str) -> Result<Self, KmsError> {
            let parts: Vec<&str> = arn.split(':').collect();

            if parts.len() != 6 {
                return Err(KmsError::InvalidConfiguration(format!(
                    "invalid KMS arn: too few parts {}",
                    parts.len()
                )));
            }

            let region_part = parts.get(3).expect("region is missing");
            let region = match Region::from_str(region_part) {
                Ok(r) => r,
                Err(e) => return Err(KmsError::InvalidConfiguration(e.description().to_string())),
            };

            Ok(AwsKms {
                kms_client: KmsClient::new(region),
                key_id: arn.to_string(),
            })
        }
    }

    impl KmsProvider for AwsKms {
        fn encrypt_dek(&self, plaintext_dek: &PlaintextDEK) -> Result<EncryptedDEK, KmsError> {
            if plaintext_dek.len() != DEK_SIZE_BYTES {
                return Err(KmsError::InvalidKey(format!(
                    "provided DEK wrong length: {}",
                    plaintext_dek.len()
                )));
            }

            let mut encrypt_req: EncryptRequest = Default::default();
            encrypt_req.key_id = self.key_id.clone();
            encrypt_req.plaintext = plaintext_dek.clone();

            let mut enc_context = HashMap::new();
            enc_context.insert("AD".to_string(), AD.to_string());
            encrypt_req.encryption_context = Some(enc_context);

            match self.kms_client.encrypt(encrypt_req).sync() {
                Ok(result) => {
                    if let Some(ciphertext) = result.ciphertext_blob {
                        Ok(ciphertext)
                    } else {
                        Err(KmsError::OperationFailed(
                            "no ciphertext despite successful response".to_string(),
                        ))
                    }
                }
                Err(e) => Err(KmsError::OperationFailed(e.description().to_string())),
            }
        }

        fn decrypt_dek(&self, encrypted_dek: &EncryptedDEK) -> Result<PlaintextDEK, KmsError> {
            let mut decrypt_req: DecryptRequest = Default::default();
            decrypt_req.ciphertext_blob = encrypted_dek.clone();

            let mut dec_context = HashMap::new();
            dec_context.insert("AD".to_string(), AD.to_string());
            decrypt_req.encryption_context = Some(dec_context);

            match self.kms_client.decrypt(decrypt_req).sync() {
                Ok(result) => {
                    if let Some(plaintext_dek) = result.plaintext {
                        if plaintext_dek.len() == DEK_SIZE_BYTES {
                            Ok(plaintext_dek)
                        } else {
                            Err(KmsError::InvalidKey(format!(
                                "decrypted DEK wrong length: {}",
                                plaintext_dek.len()
                            )))
                        }
                    } else {
                        Err(KmsError::OperationFailed(
                            "decrypted payload is empty".to_string(),
                        ))
                    }
                }
                Err(e) => Err(KmsError::OperationFailed(e.description().to_string())),
            }
        }
    }

    #[cfg(feature = "awskms")]
    impl fmt::Display for AwsKms {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
            write!(f, "{}", self.key_id)
        }
    }
}