├── .gitignore ├── LICENSE ├── README.md ├── config.go ├── dev.go ├── iam └── policy.json ├── key.go ├── main.go ├── systemd ├── awskmsluks.service └── mnt-data.mount └── testenv ├── .gitignore ├── README.md ├── Vagrantfile ├── bootstrap.sh └── config.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS KMS LUKS 2 | 3 | Use AWS KMS to encrypt Linux block devices with LUKS. 4 | 5 | Encryption keys are not stored anywhere in an unencrypted form. 6 | 7 | ## Setup 8 | ### AWS 9 | In the same AWS region create: 10 | * S3 bucket - this is the backup archive of encrypted keys. 11 | * KMS CMK - this is the CMK that data keys will be created off and encrypted by. 12 | * IAM user - this will be used by the tool to access the AWS APIs. 13 | 14 | #### AWS IAM Permissions 15 | Apply the policy found in iam/policy.json to the IAM user. The values of the CMK ARN and bucket name need to be replaced in the policy document. 16 | 17 | Create an AWS key pair for this user. 18 | 19 | ### Host 20 | 21 | #### Prerequisites 22 | There is a dependency on installing the ``cryptsetup`` package. 23 | 24 | #### AWS Credentials 25 | On the host that will have the encrypted volume configure the AWS credentials under the root user. 26 | This is described at (https://docs.aws.amazon.com/cli/latest/userguide/cli-config-files.html). 27 | The default region is also needs to be set to the region in which the backup archive bucket and KMS CMK has been created. 28 | 29 | #### awskmsluks 30 | Create the directory: ``mkdir /etc/awskmsluks/bin`` 31 | 32 | Build and copy the ``awskmsluks`` binary to this directory 33 | 34 | #### awskmsluks Configuration 35 | Copy the ``config.json`` file to ``/etc/awskmsluks/config.json`` and set the following values: 36 | 37 | * CMKARN: This is the full ARN of the CMK you want to create data keys from for encrypting devices on this host. 38 | * Production: This is a boolean to indicate if this host is considered a production host. 39 | * KeyArchiveBucket: This is the bucket name (not the full ARN) of the bucket to use for keeping an off host backup archive of encrypted data keys. 40 | 41 | #### Systemd Unit Files 42 | Copy the``systemd/awskmsluks.service`` file to ``/etc/systemd/system`` 43 | 44 | Enable this with ``systemctl enable awskmsluks.service`` 45 | 46 | ## Creating an Encrypted Volume 47 | Ecrypt the block device with LUKS using an AWS KMS data key: 48 | 49 | ```/etc/awskmsluks/bin/awskmsluks -encrypt=/dev/sdb``` 50 | 51 | Open the device: 52 | 53 | ```/etc/awskmsluks/bin/awskmsluks -open``` 54 | 55 | Format the device with the filesystem of your choice. 56 | The open device will be in ``/dev/mapper`` with the name of the device appended with ``_crypt`` 57 | For example: 58 | 59 | ```mkfs.ext4 /dev/mapper/sdb_crypt``` 60 | 61 | Create a systemd mount. Set the values in the ``[Mount]`` section of the example below as required. 62 | It is important to have the ``After=awskmsluks.service`` configuration 63 | 64 | ``` 65 | [Unit] 66 | After=awskmsluks.service 67 | 68 | [Mount] 69 | What=/dev/mapper/sdb_crypt 70 | Where=/mnt/data 71 | Type=ext4 72 | Options=defaults 73 | 74 | [Install] 75 | WantedBy=multi-user.target 76 | ``` 77 | 78 | ## Building 79 | ``` 80 | go build -ldflags "-X main.version=v1.0.0 -X main.buildtime=`date -u '+%FT%TZ'` -X main.buildhash=`git rev-parse HEAD`" 81 | ``` 82 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | ) 8 | 9 | type config struct { 10 | CMKARN string 11 | Production bool 12 | KeyArchiveBucket string 13 | } 14 | 15 | func loadConfig(path string) (config, error) { 16 | var c config 17 | b, err := ioutil.ReadFile(path) 18 | if err != nil { 19 | return c, fmt.Errorf("cannot read config file (%s): %v", path, err) 20 | } 21 | err = json.Unmarshal(b, &c) 22 | if err != nil { 23 | return c, fmt.Errorf("configuration file (%s) could not be parsed: %v", path, err) 24 | } 25 | return c, nil 26 | } 27 | -------------------------------------------------------------------------------- /dev.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | ) 7 | 8 | const ( 9 | devByUUIDPath = "/dev/disk/by-uuid/" 10 | ) 11 | 12 | func devFromUUID(uuid string) (string, error) { 13 | dev, err := os.Readlink(devByUUIDPath + uuid) 14 | if !filepath.IsAbs(dev) { 15 | return filepath.Abs(devByUUIDPath + dev) 16 | } 17 | return dev, err 18 | } 19 | -------------------------------------------------------------------------------- /iam/policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "Decrypt", 6 | "Effect": "Allow", 7 | "Action": [ 8 | "kms:Decrypt" 9 | ], 10 | "Resource": [ 11 | "arn:aws:kms:::key/" 12 | ] 13 | }, 14 | { 15 | "Sid": "Archive", 16 | "Effect": "Allow", 17 | "Action": [ 18 | "s3:PutObject" 19 | ], 20 | "Resource": [ 21 | "arn:aws:s3:::mybucket/", 22 | "arn:aws:s3:::mybucket/*" 23 | ] 24 | }, 25 | { 26 | "Sid": "GenerateKey", 27 | "Effect": "Allow", 28 | "Action": "kms:GenerateDataKey", 29 | "Resource": "*" 30 | } 31 | ] 32 | } -------------------------------------------------------------------------------- /key.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "encoding/json" 7 | "fmt" 8 | "github.com/aws/aws-sdk-go-v2/aws" 9 | "github.com/aws/aws-sdk-go-v2/aws/external" 10 | "github.com/aws/aws-sdk-go-v2/service/kms" 11 | "github.com/aws/aws-sdk-go-v2/service/s3/s3manager" 12 | "github.com/hashicorp/go-uuid" 13 | "github.com/jcmturner/awsarn" 14 | "io/ioutil" 15 | "os" 16 | "strconv" 17 | "strings" 18 | "time" 19 | ) 20 | 21 | const ( 22 | passPhraseByteSize = 1024 23 | ) 24 | 25 | type key struct { 26 | EncryptionContext encryptionContext `json:"EncryptionContext"` 27 | CMKARN string `json:"CMKARN"` 28 | DataKey dataKey `json:"DataKey"` 29 | } 30 | 31 | type encryptionContext struct { 32 | FQDN string `json:"FQDN"` 33 | Production bool `json:"Production"` 34 | UUID string `json:"UUID"` 35 | } 36 | 37 | type dataKey struct { 38 | Plain string `json:"Plain,omitempty"` 39 | Encrypted string `json:"Encrypted"` 40 | Created time.Time `json:"Created"` 41 | } 42 | 43 | func newEncryptionContext(fqdn, uuid string, production bool) encryptionContext { 44 | return encryptionContext{ 45 | FQDN: fqdn, 46 | Production: production, 47 | UUID: uuid, 48 | } 49 | } 50 | 51 | func (e encryptionContext) toMap() map[string]string { 52 | return map[string]string{ 53 | "fqdn": e.FQDN, 54 | "production": strconv.FormatBool(e.Production), 55 | "uuid": e.UUID, 56 | } 57 | } 58 | 59 | func newDataKey(cmkARNStr, fqdn string, production bool) (key, error) { 60 | cmkARN, err := awsarn.Parse(cmkARNStr, nil) 61 | if err != nil { 62 | return key{}, fmt.Errorf("invalid CMK ARN: %v", err) 63 | } 64 | 65 | cfg, err := external.LoadDefaultAWSConfig() 66 | if err != nil { 67 | return key{}, fmt.Errorf("unable to load AWS SDK config: %v", err) 68 | } 69 | cfg.Region = cmkARN.Region 70 | 71 | kmsSrv := kms.New(cfg) 72 | 73 | devUUID, err := uuid.GenerateUUID() 74 | if err != nil { 75 | return key{}, err 76 | } 77 | ec := newEncryptionContext(fqdn, devUUID, production) 78 | bs := int64(passPhraseByteSize) 79 | input := kms.GenerateDataKeyInput{ 80 | EncryptionContext: ec.toMap(), 81 | KeyId: &cmkARNStr, 82 | NumberOfBytes: &bs, 83 | } 84 | request := kmsSrv.GenerateDataKeyRequest(&input) 85 | output, err := request.Send() 86 | if err != nil { 87 | return key{}, err 88 | } 89 | 90 | k := key{ 91 | EncryptionContext: ec, 92 | CMKARN: cmkARNStr, 93 | DataKey: dataKey{ 94 | Plain: base64.StdEncoding.EncodeToString(output.Plaintext), 95 | Encrypted: base64.StdEncoding.EncodeToString(output.CiphertextBlob), 96 | Created: time.Now().UTC(), 97 | }, 98 | } 99 | return k, nil 100 | } 101 | 102 | func (k key) archive(bucket string) error { 103 | //Blank the plaintext form of the key before storing 104 | k.DataKey.Plain = "" 105 | // The config the S3 Uploader will use 106 | cfg, err := external.LoadDefaultAWSConfig() 107 | 108 | // Create an uploader with the config and default options 109 | uploader := s3manager.NewUploader(cfg) 110 | 111 | // Marshal the key to json 112 | keyBytes, err := json.MarshalIndent(k, "", " ") 113 | if err != nil { 114 | return fmt.Errorf("failed to marshal key: %v", err) 115 | } 116 | 117 | // Upload the file to S3. 118 | _, err = uploader.Upload(&s3manager.UploadInput{ 119 | Bucket: aws.String(bucket), 120 | Key: aws.String(fmt.Sprintf("%s/%s.json", k.EncryptionContext.FQDN, k.EncryptionContext.UUID)), 121 | Body: bytes.NewBuffer(keyBytes), 122 | }) 123 | if err != nil { 124 | return fmt.Errorf("failed to upload file, %v", err) 125 | } 126 | return nil 127 | } 128 | 129 | func (k key) store(path string) error { 130 | k.DataKey.Plain = "" 131 | err := os.MkdirAll(path+k.EncryptionContext.FQDN, 0600) 132 | if err != nil { 133 | return fmt.Errorf("could not create local key store directory: " + err.Error()) 134 | } 135 | kjson, err := json.MarshalIndent(k, "", " ") 136 | if err != nil { 137 | return fmt.Errorf("could not marshal key to JSON: " + err.Error()) 138 | } 139 | kf, err := os.OpenFile(path+k.EncryptionContext.FQDN+"/"+k.EncryptionContext.UUID+".json", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) 140 | if err != nil { 141 | return fmt.Errorf("could not open key file: " + err.Error()) 142 | } 143 | defer kf.Close() 144 | _, err = kf.Write(kjson) 145 | if err != nil { 146 | return fmt.Errorf("could not write to local key store: %v", err) 147 | } 148 | return nil 149 | } 150 | 151 | func (k *key) decrypt() error { 152 | cmkARN, err := awsarn.Parse(k.CMKARN, nil) 153 | if err != nil { 154 | return fmt.Errorf("invalid CMK ARN: %v", err) 155 | } 156 | 157 | cfg, err := external.LoadDefaultAWSConfig() 158 | if err != nil { 159 | return fmt.Errorf("unable to load AWS SDK config: %v", err) 160 | } 161 | cfg.Region = cmkARN.Region 162 | 163 | kmsSrv := kms.New(cfg) 164 | 165 | b, err := base64.StdEncoding.DecodeString(k.DataKey.Encrypted) 166 | if err != nil { 167 | return fmt.Errorf("cannot base64 decode encrypted key: %v", err) 168 | } 169 | 170 | input := kms.DecryptInput{ 171 | CiphertextBlob: b, 172 | EncryptionContext: k.EncryptionContext.toMap(), 173 | } 174 | request := kmsSrv.DecryptRequest(&input) 175 | output, err := request.Send() 176 | if err != nil { 177 | return err 178 | } 179 | k.DataKey.Plain = base64.StdEncoding.EncodeToString(output.Plaintext) 180 | return nil 181 | } 182 | 183 | func (k *key) Load(path string) error { 184 | b, err := ioutil.ReadFile(path) 185 | if err != nil { 186 | return fmt.Errorf("error reading device's key from local store (%s): %v", path, err) 187 | } 188 | err = json.Unmarshal(b, k) 189 | if err != nil { 190 | return fmt.Errorf("error parsing device's key from local store (%s): %v", path, err) 191 | } 192 | return nil 193 | } 194 | 195 | func keys() ([]key, error) { 196 | var ks []key 197 | // Get host's FQDN 198 | fqdn, err := os.Hostname() 199 | if err != nil { 200 | return ks, fmt.Errorf("could not get host's FQDN: " + err.Error()) 201 | } 202 | sp := dirRoot + keyStore + fqdn + "/" 203 | kl, err := ioutil.ReadDir(sp) 204 | if err != nil { 205 | return ks, fmt.Errorf("could not read local key store (%s): %v", sp, err) 206 | } 207 | for _, kp := range kl { 208 | if kp.IsDir() { 209 | continue 210 | } 211 | if !strings.HasSuffix(kp.Name(), ".json") { 212 | continue 213 | } 214 | _, err := uuid.ParseUUID(strings.SplitN(kp.Name(), ".json", 2)[0]) 215 | if err != nil { 216 | continue 217 | } 218 | var k key 219 | err = k.Load(sp + kp.Name()) 220 | if err != nil { 221 | fmt.Fprintf(os.Stderr, "error loading key %s: %v", sp+kp.Name(), err) 222 | continue 223 | } 224 | ks = append(ks, k) 225 | } 226 | return ks, nil 227 | } 228 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "io" 7 | "os" 8 | "os/exec" 9 | "path" 10 | "strings" 11 | "time" 12 | ) 13 | 14 | const ( 15 | dirRoot = "/etc/awskmsluks/" 16 | configPath = "config.json" 17 | keyStore = "keys/" 18 | cryptsetup = "/sbin/cryptsetup" 19 | ) 20 | 21 | var buildhash = "Not set" 22 | var buildtime = "Not set" 23 | var version = "Not set" 24 | 25 | func getVersion() (string, string, time.Time) { 26 | bt, _ := time.Parse(time.RFC3339, buildtime) 27 | return version, buildhash, bt 28 | } 29 | 30 | func main() { 31 | encrypt := flag.String("encrypt", "", "Generate passphrase for LUKS and encrypt the device") 32 | open := flag.Bool("open", false, "Open all encrypted devices") 33 | //clse := flag.Bool("close", false, "Close all encrypted devices") 34 | uuid := flag.String("uuid", "", "Return the passphrase to open the LUKS device. Value must be the UUID of the device") 35 | v := flag.Bool("version", false, "Print version information") 36 | flag.Parse() 37 | 38 | // Print version information and exit. 39 | if *v { 40 | v, bh, bt := getVersion() 41 | fmt.Fprintf(os.Stderr, "AWS KMS LUKS Version Information:\nVersion:\t%s\nBuild hash:\t%s\nBuild time:\t%v\n", v, bh, bt) 42 | os.Exit(0) 43 | } 44 | 45 | if *encrypt == "" && !*open && *uuid == "" { 46 | flag.PrintDefaults() 47 | os.Exit(1) 48 | } 49 | 50 | if *encrypt != "" { 51 | err := formatDev(*encrypt) 52 | if err != nil { 53 | panic(err.Error()) 54 | } 55 | } 56 | if *open { 57 | openAll() 58 | } 59 | if *uuid != "" { 60 | err := passPhrase(*uuid) 61 | if err != nil { 62 | panic(err.Error()) 63 | } 64 | } 65 | } 66 | 67 | func formatDev(dev string) error { 68 | if !strings.HasPrefix(dev, "/dev/") { 69 | return fmt.Errorf("device %s is not vaid", dev) 70 | } 71 | // Check device exists 72 | if _, err := os.Stat(dev); os.IsNotExist(err) { 73 | return fmt.Errorf("device %s does not exist", dev) 74 | } 75 | // Get host's FQDN 76 | fqdn, err := os.Hostname() 77 | if err != nil { 78 | return fmt.Errorf("could not get host's FQDN: " + err.Error()) 79 | } 80 | // Load configuration 81 | c, err := loadConfig(dirRoot + configPath) 82 | if err != nil { 83 | return err 84 | } 85 | // Generate a new data key 86 | key, err := newDataKey(c.CMKARN, fqdn, c.Production) 87 | if err != nil { 88 | return fmt.Errorf("could not generate the data key: " + err.Error()) 89 | } 90 | // Archive the key to S3 91 | err = key.archive(c.KeyArchiveBucket) 92 | if err != nil { 93 | return fmt.Errorf("could not archive the data key: " + err.Error()) 94 | } 95 | // Store the key locally 96 | err = key.store(dirRoot + keyStore) 97 | if err != nil { 98 | return err 99 | } 100 | 101 | // Perform the cryptosetup format 102 | cmd := exec.Command(cryptsetup, "--key-file=-", "luksFormat", dev, "-") 103 | stdin, err := cmd.StdinPipe() 104 | if err != nil { 105 | return fmt.Errorf("could not open stdin to cryptsetup command: %v", err) 106 | } 107 | err = cmd.Start() 108 | if err != nil { 109 | return fmt.Errorf("could not start cryptsetup command: %v", err) 110 | } 111 | go func() { 112 | defer stdin.Close() 113 | io.WriteString(stdin, key.DataKey.Plain) 114 | }() 115 | err = cmd.Wait() 116 | if err != nil { 117 | return fmt.Errorf("cyrptsetup did not run successfully to format device %s: %v", dev, err) 118 | } 119 | 120 | // Set the UUID on the device 121 | cmd = exec.Command(cryptsetup, "luksUUID", dev, "--uuid", key.EncryptionContext.UUID) 122 | stdin, err = cmd.StdinPipe() 123 | if err != nil { 124 | return fmt.Errorf("could not open stdin to cryptsetup command: %v", err) 125 | } 126 | err = cmd.Start() 127 | if err != nil { 128 | return fmt.Errorf("could not start cryptsetup command: %v", err) 129 | } 130 | go func() { 131 | defer stdin.Close() 132 | io.WriteString(stdin, "YES\n") 133 | }() 134 | err = cmd.Wait() 135 | if err != nil { 136 | return fmt.Errorf("cyrptsetup did not run successfully to set the UUID of device %s: %v. Suggest running manually:\ncryptsetup luksUUID --uuid %s", dev, err, key.EncryptionContext.UUID) 137 | } 138 | fmt.Printf("Successfully encrypted device %s\n", dev) 139 | fmt.Println("Device now needs to be formated with a filesystem as usual") 140 | 141 | return nil 142 | } 143 | 144 | func passPhrase(uuid string) error { 145 | // Get host's FQDN 146 | fqdn, err := os.Hostname() 147 | if err != nil { 148 | return fmt.Errorf("could not get host's FQDN: " + err.Error()) 149 | } 150 | 151 | kpath := dirRoot + keyStore + fqdn + "/" + uuid + ".json" 152 | var k key 153 | err = k.Load(kpath) 154 | if err != nil { 155 | return fmt.Errorf("error loading key: %v", err) 156 | } 157 | err = k.decrypt() 158 | if err != nil { 159 | return fmt.Errorf("could not decrypt key: %v", err) 160 | } 161 | fmt.Print(k.DataKey.Plain) 162 | return nil 163 | } 164 | 165 | func openDev(k key) error { 166 | dev, err := devFromUUID(k.EncryptionContext.UUID) 167 | if err != nil { 168 | return fmt.Errorf("could not get device name for UUID %s: %v", k.EncryptionContext.UUID, err) 169 | } 170 | err = k.decrypt() 171 | if err != nil { 172 | return fmt.Errorf("could not decrypt key for UUID %s: %v", k.EncryptionContext.UUID, err) 173 | } 174 | name := path.Base(dev) + "_crypt" 175 | cmd := exec.Command(cryptsetup, "--key-file=-", "luksOpen", dev, name) 176 | stdin, err := cmd.StdinPipe() 177 | if err != nil { 178 | return fmt.Errorf("could not open stdin to cryptsetup command: %v", err) 179 | } 180 | 181 | fmt.Printf("openning UUID %s, device %s to %s\n", k.EncryptionContext.UUID, dev, name) 182 | err = cmd.Start() 183 | if err != nil { 184 | return fmt.Errorf("could not start cryptsetup command: %v", err) 185 | } 186 | go func() { 187 | defer stdin.Close() 188 | io.WriteString(stdin, k.DataKey.Plain) 189 | }() 190 | err = cmd.Wait() 191 | if err != nil { 192 | return fmt.Errorf("cyrptsetup did not run successfully for UUID %s device %s: %v", k.EncryptionContext.UUID, dev, err) 193 | } 194 | statusCmd := exec.Command(cryptsetup, "status", name) 195 | stdout, _ := statusCmd.StdoutPipe() 196 | stderr, _ := statusCmd.StderrPipe() 197 | go func() { 198 | defer stdout.Close() 199 | io.Copy(os.Stdout, stdout) 200 | }() 201 | go func() { 202 | defer stderr.Close() 203 | io.Copy(os.Stderr, stderr) 204 | }() 205 | statusCmd.Run() 206 | return nil 207 | } 208 | 209 | func openAll() { 210 | ks, err := keys() 211 | if err != nil { 212 | fmt.Fprintf(os.Stderr, "error getting device keys: %v\n", err) 213 | } 214 | for _, k := range ks { 215 | err = openDev(k) 216 | if err != nil { 217 | fmt.Fprintf(os.Stderr, "error openning device: %v\n", err) 218 | } 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /systemd/awskmsluks.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=AWS KMS LUKS Open Device 3 | After=network.target 4 | 5 | [Service] 6 | #HOME environment variable needed to get AWS credentials 7 | Environment=HOME=/root 8 | Type=oneshot 9 | ExecStart=/etc/awskmsluks/bin/awskmsluks -open 10 | RemainAfterExit=true 11 | 12 | [Install] 13 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /systemd/mnt-data.mount: -------------------------------------------------------------------------------- 1 | [Unit] 2 | After=awskmsluks.service 3 | 4 | [Mount] 5 | What=/dev/mapper/sdb_crypt 6 | Where=/mnt/data 7 | Type=ext4 8 | Options=defaults 9 | 10 | [Install] 11 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /testenv/.gitignore: -------------------------------------------------------------------------------- 1 | *.vdi 2 | .vagrant 3 | awskmsluks 4 | awskmsluks.service 5 | mnt-data.mount -------------------------------------------------------------------------------- /testenv/README.md: -------------------------------------------------------------------------------- 1 | 2 | * Build binary called awskmsluks in the testenv directory 3 | * Configure the config.json file for: 4 | * CMK ARN 5 | * Archive bucket name 6 | * Copy the ../systemd files into the testenv directory 7 | * Once the vagrant image is up log in switch to root and run "aws configure". 8 | Set the access key and secret key and the region of the archive bucket as the default region. -------------------------------------------------------------------------------- /testenv/Vagrantfile: -------------------------------------------------------------------------------- 1 | dataDisk1 = './dataDisk1.vdi' 2 | dataDisk2 = './dataDisk2.vdi' 3 | Vagrant.configure("2") do |config| 4 | config.vm.provider "virtualbox" do |v| 5 | v.memory = 2048 6 | v.cpus = 2 7 | # Adding a SATA controller that allows 2 hard drives 8 | v.customize ['storagectl', :id, '--name', 'SATA Controller', '--add', 'sata', '--portcount', 2] 9 | unless File.exists?(dataDisk1) 10 | v.customize ['createhd', '--filename', dataDisk1, '--variant', 'Fixed', '--size', 100] 11 | end 12 | #if not File.exists?(dataDisk2) 13 | # v.customize ['createhd', '--filename', dataDisk2, '--variant', 'Fixed', '--size', 100] 14 | #end 15 | v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', dataDisk1] 16 | #v.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 2, '--device', 0, '--type', 'hdd', '--medium', dataDisk2] 17 | end 18 | 19 | config.vm.define "centos", primary: true do |centos| 20 | centos.vm.hostname = "centos.awskmsluks.com" 21 | centos.vm.box = "centos/7" 22 | centos.vm.network "private_network", ip: "10.80.10.146", netmask: "255.255.0.0" 23 | centos.vm.provision :shell, path: "bootstrap.sh" 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /testenv/bootstrap.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm /etc/localtime 4 | ln -s /usr/share/zoneinfo/Europe/London /etc/localtime 5 | 6 | yum upgrade -y 7 | yum install -y \ 8 | cryptsetup \ 9 | git \ 10 | ntp \ 11 | epel-release \ 12 | net-tools 13 | 14 | yum install -y python2-pip 15 | 16 | systemctl stop firewalld 17 | systemctl disable firewalld 18 | 19 | pip install awscli 20 | 21 | mkdir -p /etc/awskmsluks/bin 22 | cp /vagrant/config.json /etc/awskmsluks/ 23 | cp /vagrant/awskmsluks /etc/awskmsluks/bin/ 24 | 25 | mkdir /mnt/data 26 | 27 | cp /vagrant/awskmsluks.service /etc/systemd/system/ 28 | cp /vagrant/mnt-data.mount /etc/systemd/system/ 29 | 30 | systemctl enable awskmsluks.service mnt-data.mount 31 | 32 | cat <> /etc/sysctl.conf 33 | net.ipv6.conf.all.disable_ipv6 = 1 34 | net.ipv6.conf.default.disable_ipv6 = 1 35 | net.ipv6.conf.lo.disable_ipv6 = 1 36 | EOF 37 | 38 | #Turning off selinux 39 | sed -i "s/SELINUX=.*/SELINUX=permissive/g" /etc/sysconfig/selinux 40 | sed -i "s/SELINUX=.*/SELINUX=permissive/g" /etc/selinux/config 41 | 42 | echo 'Set up AWS credentials as root by running "aws configure"' 1>&2 43 | 44 | reboot 45 | -------------------------------------------------------------------------------- /testenv/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "CMKARN": "arn:aws:kms:::key/", 3 | "Production": false, 4 | "KeyArchiveBucket": "mybucket" 5 | } 6 | --------------------------------------------------------------------------------