├── .gitignore ├── go.mod ├── .github └── workflows │ └── ci.yml ├── .goreleaser.yml ├── LICENSE.txt ├── myssh └── forked.go ├── go.sum ├── README.md └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | /kms-host-key 2 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/glassechidna/kms-host-key 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/aws/aws-sdk-go v1.28.9 7 | github.com/glassechidna/go-kms-signer v0.0.0-20191127235234-5f91bb000d7d 8 | github.com/pkg/errors v0.8.1 9 | github.com/spf13/pflag v1.0.5 10 | golang.org/x/crypto v0.0.0-20191122220453-ac88ee75c92c 11 | ) 12 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | pull_request: 5 | push: 6 | 7 | jobs: 8 | goreleaser: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v2 13 | 14 | - name: Unshallow 15 | run: git fetch --prune --unshallow 16 | 17 | - name: Set up Go 18 | uses: actions/setup-go@v1 19 | with: 20 | go-version: 1.13.x 21 | 22 | - name: build 23 | run: go build 24 | 25 | - name: Run GoReleaser 26 | uses: goreleaser/goreleaser-action@v1 27 | if: startsWith(github.ref, 'refs/tags/') 28 | with: 29 | version: latest 30 | args: release --rm-dist 31 | env: 32 | GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} 33 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | builds: 2 | - goos: 3 | - darwin 4 | - linux 5 | - windows 6 | env: 7 | - CGO_ENABLED=0 8 | goarch: [amd64] 9 | checksum: 10 | name_template: 'checksums.txt' 11 | snapshot: 12 | name_template: "{{ .Tag }}-next" 13 | changelog: 14 | sort: asc 15 | filters: 16 | exclude: 17 | - '^docs:' 18 | - '^test:' 19 | brew: 20 | github: 21 | owner: glassechidna 22 | name: homebrew-taps 23 | commit_author: 24 | name: Aidan Steele 25 | email: aidan.steele@glassechidna.com.au 26 | homepage: https://github.com/glassechidna/kms-host-key 27 | description: kms-host-key is an easy way to give all your EC2 instances SSH host certificates 28 | scoop: 29 | bucket: 30 | owner: glassechidna 31 | name: scoop-bucket 32 | commit_author: 33 | name: Aidan Steele 34 | email: aidan.steele@glassechidna.com.au 35 | homepage: https://github.com/glassechidna/kms-host-key 36 | description: kms-host-key is an easy way to give all your EC2 instances SSH host certificates 37 | license: MIT -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Glass Echidna 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /myssh/forked.go: -------------------------------------------------------------------------------- 1 | package myssh 2 | 3 | import ( 4 | "crypto" 5 | "golang.org/x/crypto/ssh" 6 | "io" 7 | ) 8 | 9 | func NewSignerFromSigner(input crypto.Signer) (ssh.AlgorithmSigner, error) { 10 | signer, err := ssh.NewSignerFromSigner(input) 11 | if err != nil { 12 | return nil, err 13 | } 14 | 15 | return signer.(ssh.AlgorithmSigner), nil 16 | } 17 | 18 | // forked from golang.org/x/crypto/ssh because we want to use AlgorithSigner instead 19 | // of Signer. this is because Signer will default to SHA-1, which is a) bad and b) unsupported 20 | // by AWS KMS. 21 | func SignCert(c *ssh.Certificate, rand io.Reader, authority ssh.AlgorithmSigner) error { 22 | c.Nonce = make([]byte, 32) 23 | if _, err := io.ReadFull(rand, c.Nonce); err != nil { 24 | return err 25 | } 26 | c.SignatureKey = authority.PublicKey() 27 | 28 | sigAlgo := "" 29 | if c.Key.Type() == ssh.KeyAlgoRSA { 30 | sigAlgo = ssh.SigAlgoRSASHA2256 31 | } 32 | 33 | sig, err := authority.SignWithAlgorithm(rand, bytesForSigning(c), sigAlgo) 34 | if err != nil { 35 | return err 36 | } 37 | c.Signature = sig 38 | return nil 39 | } 40 | 41 | // forked from golang.org/x/crypto/ssh because it's used by the above func 42 | func bytesForSigning(cert *ssh.Certificate) []byte { 43 | c2 := *cert 44 | c2.Signature = nil 45 | out := c2.Marshal() 46 | // Drop trailing signature length. 47 | return out[:len(out)-4] 48 | } 49 | 50 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/aws/aws-sdk-go v1.25.43/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= 2 | github.com/aws/aws-sdk-go v1.28.9 h1:grIuBQc+p3dTRXerh5+2OxSuWFi0iXuxbFdTSg0jaW0= 3 | github.com/aws/aws-sdk-go v1.28.9/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/glassechidna/go-kms-signer v0.0.0-20191127235234-5f91bb000d7d h1:+Lu7cjEHESijOVKkaTncYqyqDdh25utB8QYPoI89+WU= 6 | github.com/glassechidna/go-kms-signer v0.0.0-20191127235234-5f91bb000d7d/go.mod h1:kLlPT7rGPbxA3/1nruixN+l7AEbxm0GOL+YZ0wiL5sQ= 7 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= 8 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= 9 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 10 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 11 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 12 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 13 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 14 | golang.org/x/crypto v0.0.0-20191122220453-ac88ee75c92c h1:/nJuwDLoL/zrqY6gf57vxC+Pi+pZ8bfhpPkicO5H7W4= 15 | golang.org/x/crypto v0.0.0-20191122220453-ac88ee75c92c/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 16 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 17 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 18 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 19 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kms-host-key 2 | 3 | [EC2 Instance Connect][eic] filled a much-needed gap for AWS users who wanted a 4 | want to log into EC2 instances over SSH without the hassle of managing SSH keys. 5 | 6 | The missing piece of the puzzle is authenticating the host you are logging into. 7 | Even if you don't care about the possibility of a [MITM][mitm] attack, this message is 8 | a pain. Especially if you are automating your SSH and don't have a TTY present 9 | to type "yes": 10 | 11 | > The authenticity of host '1.2.3.4 (1.2.3.4)' can't be established. 12 | > RSA key fingerprint is SHA256:PMxq13AoZOG2KZ5qPaZCgMpzJx8gyKLxaE/e5Q//4GE. 13 | > Are you sure you want to continue connecting (yes/no)? 14 | 15 | That's where `kms-host-key` comes in. Include it in your EC2 userdata script 16 | and it requests that [AWS KMS][kms] sign the instance's host key. This means that you 17 | and your colleagues can add a single line to your `~/.ssh/known_hosts` and never 18 | seen that pesky warning again. That line would look something like: 19 | 20 | echo '@cert-authority * ssh-rsa AAAAB3NzaC1yc...' >> ~/.ssh/known_hosts 21 | 22 | ## Usage 23 | 24 | First, create an **RSA** KMS key with the following key policy: 25 | 26 | ```json 27 | { 28 | "Version": "2012-10-17", 29 | "Id": "key-default-1", 30 | "Statement": [ 31 | { 32 | "Sid": "Enable IAM User Permissions", 33 | "Effect": "Allow", 34 | "Principal": { 35 | "AWS": "arn:aws:iam::YOUR_ACCOUNT_ID:root" 36 | }, 37 | "Action": "kms:*", 38 | "Resource": "*" 39 | }, 40 | { 41 | "Sid": "AllowAnyoneToPrintPubKey", 42 | "Effect": "Allow", 43 | "Principal": "*", 44 | "Action": "kms:GetPublicKey", 45 | "Resource": "*", 46 | "Condition": { 47 | "StringEquals": { 48 | "aws:PrincipalOrgID": "o-YOUR_ORG_ID" 49 | } 50 | } 51 | }, 52 | { 53 | "Sid": "AllowEC2ToSignPartOne", 54 | "Effect": "Allow", 55 | "Principal": "*", 56 | "Action": "kms:Sign", 57 | "Resource": "*", 58 | "Condition": { 59 | "StringEquals": { 60 | "aws:PrincipalOrgID": "o-YOUR_ORG_ID" 61 | } 62 | } 63 | }, 64 | { 65 | "Sid": "AllowEC2ToSignPartTwo", 66 | "Effect": "Deny", 67 | "Principal": "*", 68 | "Action": "kms:Sign", 69 | "Resource": "*", 70 | "Condition": { 71 | "Null": { 72 | "ec2:SourceInstanceARN": "true" 73 | } 74 | } 75 | } 76 | ] 77 | } 78 | ``` 79 | 80 | It is also recommended to give it an alias of `alias/hostkeysigner` - this is 81 | the default used by `kms-host-key` and will require less configuration on your 82 | behalf. 83 | 84 | Next, add the following to your userdata: 85 | 86 | ```shell script 87 | # download 88 | curl -o kms-host-key.tgz -L https://github.com/glassechidna/kms-host-key/releases/download/0.1.0/kms-host-key_0.1.0_linux_amd64.tar.gz 89 | tar -xvf kms-host-key.tgz 90 | 91 | # run 92 | ./kms-host-key -g >> /etc/ssh/ssh_host_rsa_key-cert.pub 93 | echo 'HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub' >> /etc/ssh/sshd_config 94 | service sshd restart 95 | 96 | # cleanup 97 | rm kms-host-key kms-host-key.tgz 98 | ``` 99 | 100 | Finally, download `kms-host-key` on your laptop and run this: 101 | 102 | kms-host-key -c >> ~/.ssh/known_hosts 103 | 104 | You're ready to get started! 105 | 106 | ## Cross-account/region considerations 107 | 108 | By default, the above KMS key policy is sufficient to grant instances in the same 109 | *account* permission to create signed host keys. If you wish for instances in 110 | other accounts (but still within the same AWS organization) to be able to sign 111 | their host keys, they will need to have `kms:Sign` permissions in their instance 112 | profiles' IAM roles. 113 | 114 | Likewise, by default `kms-host-key` assumes that an unqualified key ID or alias 115 | refers to a key in the same region as the instance. This behaviour can be changed 116 | by specifying a full key ARN, e.g. `arn:aws:kms:us-east-1:0123456789012:alias/hostkeysigner` 117 | which will work across regions. 118 | 119 | [eic]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-methods.html 120 | [mitm]: https://en.wikipedia.org/wiki/Man-in-the-middle_attack 121 | [kms]: https://aws.amazon.com/kms/ 122 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/base64" 6 | "fmt" 7 | "github.com/aws/aws-sdk-go/aws" 8 | "github.com/aws/aws-sdk-go/aws/credentials/stscreds" 9 | "github.com/aws/aws-sdk-go/aws/ec2metadata" 10 | "github.com/aws/aws-sdk-go/aws/request" 11 | "github.com/aws/aws-sdk-go/aws/session" 12 | "github.com/aws/aws-sdk-go/service/kms" 13 | "github.com/aws/aws-sdk-go/service/kms/kmsiface" 14 | "github.com/glassechidna/go-kms-signer/kmssigner" 15 | "github.com/glassechidna/kms-host-key/myssh" 16 | "github.com/pkg/errors" 17 | "github.com/spf13/pflag" 18 | "golang.org/x/crypto/ssh" 19 | "io/ioutil" 20 | "net/http" 21 | "os" 22 | "strings" 23 | "time" 24 | ) 25 | 26 | var version = "unknown" 27 | 28 | func main() { 29 | keyIdPtr := pflag.String("kms-key", "alias/hostkeysigner", "KMS key ID") 30 | sshKeyPathPtr := pflag.String("ssh-key-path", "/etc/ssh/ssh_host_rsa_key.pub", "Path to SSH host key to sign") 31 | printCa := pflag.BoolP("ca", "c", false, "Retrieve and print to stdout SSH CA public key") 32 | generate := pflag.BoolP("generate", "g", false, "Generate and print to stdout SSH host certificate") 33 | pflag.Parse() 34 | 35 | keyId := *keyIdPtr 36 | region, err := awsRegion(keyId) 37 | checkerr(err) 38 | api := kmsApi(err, region) 39 | 40 | if *printCa { 41 | printCertificateAuthority(api, keyId) 42 | } else if *generate { 43 | generateHostCertificate(*sshKeyPathPtr, api, keyId) 44 | } else { 45 | fmt.Fprintln(os.Stderr, "You must provide one of -g or -c") 46 | pflag.PrintDefaults() 47 | } 48 | } 49 | 50 | func kmsApi(err error, region string) kmsiface.KMSAPI { 51 | sess, err := session.NewSessionWithOptions(session.Options{ 52 | Config: *aws.NewConfig().WithRegion(region), 53 | SharedConfigState: session.SharedConfigEnable, 54 | AssumeRoleTokenProvider: stscreds.StdinTokenProvider, 55 | }) 56 | checkerr(err) 57 | sess.Handlers.Build.PushBack(request.MakeAddToUserAgentHandler("kms-host-key", version)) 58 | 59 | return kms.New(sess) 60 | } 61 | 62 | func generateHostCertificate(sshKeyPath string, api kmsiface.KMSAPI, keyId string) { 63 | sshKeyBytes, err := ioutil.ReadFile(sshKeyPath) 64 | checkerr(err) 65 | 66 | pubkey, _, _, _, err := ssh.ParseAuthorizedKey(sshKeyBytes) 67 | checkerr(err) 68 | 69 | var mode kmssigner.Mode 70 | if pubkey.Type() == ssh.KeyAlgoRSA { 71 | mode = kmssigner.ModeRsaPkcs1v15 72 | } else if strings.HasPrefix("ecdsa-sha2-", pubkey.Type()) { 73 | mode = kmssigner.ModeEcdsa 74 | } else { 75 | fmt.Fprintf(os.Stderr, "Unsupported ssh key type: %s\n", pubkey.Type()) 76 | os.Exit(1) 77 | } 78 | 79 | signer := kmssigner.New(api, keyId, mode) 80 | sshsigner, err := myssh.NewSignerFromSigner(signer) 81 | checkerr(err) 82 | 83 | certKeyId, err := hostArn() 84 | checkerr(err) 85 | 86 | cert := &ssh.Certificate{ 87 | Key: pubkey, 88 | KeyId: certKeyId, 89 | CertType: ssh.HostCert, 90 | ValidBefore: ssh.CertTimeInfinity, 91 | ValidAfter: uint64(time.Now().Unix()), 92 | } 93 | 94 | err = myssh.SignCert(cert, rand.Reader, sshsigner) 95 | checkerr(err) 96 | 97 | signed := cert.Marshal() 98 | b64 := base64.StdEncoding.EncodeToString(signed) 99 | formatted := fmt.Sprintf("%s %s", cert.Type(), b64) 100 | fmt.Println(formatted) 101 | } 102 | 103 | func printCertificateAuthority(api kmsiface.KMSAPI, keyId string) { 104 | out, err := api.GetPublicKey(&kms.GetPublicKeyInput{KeyId: &keyId}) 105 | checkerr(err) 106 | 107 | key, err := kmssigner.ParseCryptoKey(out) 108 | checkerr(err) 109 | 110 | sshkey, err := ssh.NewPublicKey(key) 111 | checkerr(err) 112 | 113 | authKey := ssh.MarshalAuthorizedKey(sshkey) 114 | fmt.Printf("@cert-authority * %s\n", string(authKey)) 115 | } 116 | 117 | func hostArn() (string, error) { 118 | meta, err := metadata() 119 | if err != nil { 120 | return "", err 121 | } 122 | 123 | doc, err := meta.GetInstanceIdentityDocument() 124 | if err != nil { 125 | return "", errors.WithStack(err) 126 | } 127 | 128 | return fmt.Sprintf("arn:aws:%s:%s:instance/%s", doc.Region, doc.AccountID, doc.InstanceID), nil 129 | } 130 | 131 | func checkerr(err error) { 132 | if err != nil { 133 | panic(fmt.Sprintf("%+v", err)) 134 | } 135 | } 136 | 137 | func awsRegion(kmsKey string) (string, error) { 138 | parts := strings.Split(kmsKey, ":") 139 | if len(parts) == 5 { 140 | return parts[2], nil 141 | } 142 | 143 | if region, found := os.LookupEnv("AWS_REGION"); found { 144 | return region, nil 145 | } 146 | 147 | if region, found := os.LookupEnv("AWS_DEFAULT_REGION"); found { 148 | return region, nil 149 | } 150 | 151 | meta, err := metadata() 152 | if err == nil { 153 | return meta.Region() 154 | } 155 | 156 | return "", errors.New("Unknown AWS region. Neither AWS_REGION nor AWS_DEFAULT_REGION provided and EC2 metadata service unavailable") 157 | } 158 | 159 | func metadata() (*ec2metadata.EC2Metadata, error) { 160 | config := aws.NewConfig(). 161 | WithHTTPClient(&http.Client{Timeout: 2 * time.Second}). 162 | WithMaxRetries(1) 163 | 164 | sess := session.Must(session.NewSession(config)) 165 | meta := ec2metadata.New(sess) 166 | 167 | if meta.Available() { 168 | return meta, nil 169 | } else { 170 | return nil, errors.New("metadata service unavailable") 171 | } 172 | } 173 | --------------------------------------------------------------------------------