├── LICENSE ├── README.md ├── cmd └── sshcert │ ├── ca.go │ └── sshcert.go ├── sshcert.go ├── sshcert_test.go └── testfiles ├── ed25519_test_key.pub ├── testkeys └── testkeys.pub /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 | # sshcert 2 | sshcert is a package and CLI for handling SSH user certs. Consult the [Getting Started Guide](https://github.com/ejcx/sshcert/wiki/Getting-Started) to get started! 3 | 4 | ## Installation 5 | ``` 6 | go get github.com/ejcx/sshcert 7 | ``` 8 | 9 | ## Usage 10 | ### Creating an SSH certificate authority 11 | Calling `NewCA` will create a new SSH user certificate authority. 12 | ``` 13 | ca, err := NewCA() 14 | ``` 15 | 16 | ### Signing an SSH user certificate 17 | The `SignCert` method is used to sign a new certificate to provide access to a server who is trusting a certificate. 18 | 19 | `SignCert` requires an `ssh.PublicKey` and `SigningArguments` be passed in order to sign a public key. 20 | 21 | `NewSigningArguments` can be used to instantiate a `SigningArgument` struct. Pass `NewSigningArguments` the list of Linux users that you providing the cert to. If you wish to log in as `root` (which is a bad practice) pass `root`. 22 | 23 | ``` 24 | sa := NewSigningArguments([]string{"evan"}) 25 | ca.SignCert(evanPublicKey, sa) 26 | ``` 27 | 28 | ### Marshalling and Unmarshalling a CA 29 | CA cannot be marshalled using the json package. Instead call `Bytes` to convert the SSH key to it's binary format, or call `PrivateString` to convert the CA to a PEM encoded private key, that can then be converted back to a CA using `ParsePrivateString` 30 | 31 | ## Converting to binary format 32 | ``` 33 | buf, err := ca.Bytes() 34 | if err != nil { 35 | log.Fatalf("Could not parse CA: %s", err) 36 | } 37 | ``` 38 | 39 | To unmarshal call `FromBytes`. 40 | 41 | ``` 42 | var ca sshcert.CA 43 | err := ca.FromBytes(buf) 44 | if err != nil { 45 | log.Fatalf("Could not parse CA: %s", err) 46 | } 47 | ``` 48 | 49 | ## Converting to PEM encoded format 50 | ``` 51 | pemKey, err := ca.PrivateString() 52 | if err != nil { 53 | log.Fatalf("Could not convert CA to PEM encoded key: %s", err) 54 | } 55 | 56 | var newCA sshcert.CA 57 | err = newCA.ParsePrivateString(pemKey) 58 | if err != nil { 59 | log.Fatalf("Could not convert the PEM encoded key into CA: %s", err) 60 | } 61 | ``` -------------------------------------------------------------------------------- /cmd/sshcert/ca.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/x509" 6 | "encoding/hex" 7 | "encoding/pem" 8 | "fmt" 9 | "io/ioutil" 10 | "log" 11 | "strings" 12 | "time" 13 | 14 | "github.com/ejcx/sshcert" 15 | "github.com/spf13/cobra" 16 | ) 17 | 18 | var ( 19 | caName string 20 | privateKeyFile string 21 | publicKeyFile string 22 | principals string 23 | duration string 24 | ) 25 | 26 | var caCmd = &cobra.Command{ 27 | Use: "ca-create", 28 | Short: "Create a new certificate authority", 29 | Run: func(cmd *cobra.Command, args []string) { 30 | CACreate(cmd, args) 31 | }, 32 | } 33 | 34 | var signCmd = &cobra.Command{ 35 | Use: "sign", 36 | Short: "Sign an ssh public key to create a certificate", 37 | Run: func(cmd *cobra.Command, args []string) { 38 | SignCert(cmd, args) 39 | }, 40 | } 41 | 42 | func init() { 43 | signCmd.Flags().StringVar(&privateKeyFile, "private-key", "", "The private key used to sign the public key.") 44 | signCmd.Flags().StringVar(&publicKeyFile, "public-key", "", "The public key that is being signed.") 45 | signCmd.Flags().StringVar(&principals, "principals", "", "Comma delimited list of principals (linux users)") 46 | signCmd.Flags().StringVar(&duration, "duration", "30m", "Duration of certificate validity.") 47 | signCmd.MarkFlagRequired("private-key") 48 | signCmd.MarkFlagRequired("public-key") 49 | signCmd.MarkFlagRequired("principals") 50 | 51 | caCmd.Flags().StringVar(&caName, "name", "", "The name of the certificate authority keys") 52 | 53 | RootCmd.AddCommand(caCmd) 54 | RootCmd.AddCommand(signCmd) 55 | } 56 | 57 | func CACreate(cmd *cobra.Command, args []string) { 58 | ca, err := sshcert.NewCA() 59 | if err != nil { 60 | log.Fatalf("Could not create new ca: %s", err) 61 | } 62 | if caName == "" { 63 | buf := make([]byte, 16) 64 | rand.Read(buf) 65 | caName = hex.EncodeToString(buf) 66 | } 67 | pubFile := fmt.Sprintf("%s.pub", caName) 68 | privDer, err := x509.MarshalECPrivateKey(ca.PrivateKey) 69 | if err != nil { 70 | log.Fatalf("Could not marshal private ssh ca key: %s", err) 71 | } 72 | privBlock := pem.Block{ 73 | Type: "BEGIN SSHCERT PRIVATE KEY", 74 | Headers: nil, 75 | Bytes: privDer, 76 | } 77 | privatePEM := pem.EncodeToMemory(&privBlock) 78 | errPub := ioutil.WriteFile(pubFile, []byte(ca.String()), 0600) 79 | errPriv := ioutil.WriteFile(caName, privatePEM, 0600) 80 | if errPub != nil { 81 | log.Fatalf("Could not write public key file: %s", err) 82 | } 83 | if errPriv != nil { 84 | log.Fatalf("Could not write private key file: %s", err) 85 | } 86 | fmt.Printf("Wrote public key file to %s\n", pubFile) 87 | fmt.Printf("Wrote private key file to %s\n", caName) 88 | } 89 | 90 | func SignCert(cmd *cobra.Command, args []string) { 91 | var ( 92 | ca sshcert.CA 93 | ) 94 | privateKeyBytes, err := ioutil.ReadFile(privateKeyFile) 95 | if err != nil { 96 | log.Fatalf("Could not read private key file: %s", err) 97 | } 98 | publicKeyBytes, err := ioutil.ReadFile(publicKeyFile) 99 | if err != nil { 100 | log.Fatalf("Could not read public key file: %s", err) 101 | } 102 | principalsList := strings.Split(principals, ",") 103 | 104 | err = ca.ParsePrivateString(privateKeyBytes) 105 | if err != nil { 106 | log.Fatalf("Could not parse private key: %s", err) 107 | } 108 | 109 | publicKey, err := sshcert.ParsePublicKey(string(publicKeyBytes)) 110 | if err != nil { 111 | log.Fatalf("Could not parse ssh public key: %s", err) 112 | } 113 | signingArgs := sshcert.NewSigningArguments(principalsList) 114 | d, err := time.ParseDuration(duration) 115 | if err != nil { 116 | log.Fatalf("Could not parse duration: %s", err) 117 | } 118 | signingArgs.Duration = d 119 | certificate, err := ca.SignCert(publicKey, signingArgs) 120 | if err != nil { 121 | log.Fatalf("Could not sign public key: %s", err) 122 | } 123 | certificateFile := fmt.Sprintf("%s.cert", publicKeyFile) 124 | err = ioutil.WriteFile(certificateFile, []byte(certificate.String()), 0644) 125 | if err != nil { 126 | log.Fatalf("Could not write certificate file: %s", err) 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /cmd/sshcert/sshcert.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | var ( 10 | principal string 11 | ) 12 | 13 | var RootCmd = &cobra.Command{ 14 | Use: "sshcert", 15 | Short: "CLI for generating ssh certificates and signing ssh keys", 16 | } 17 | 18 | func Execute() { 19 | if err := RootCmd.Execute(); err != nil { 20 | log.Fatal(err) 21 | } 22 | } 23 | 24 | func main() { 25 | Execute() 26 | } 27 | -------------------------------------------------------------------------------- /sshcert.go: -------------------------------------------------------------------------------- 1 | package sshcert 2 | 3 | // sshcert is a package for creating and signing SSH user certificates. 4 | 5 | import ( 6 | "crypto/ecdsa" 7 | "crypto/elliptic" 8 | "crypto/rand" 9 | "crypto/x509" 10 | "encoding/base64" 11 | "encoding/binary" 12 | "encoding/hex" 13 | "encoding/pem" 14 | "errors" 15 | "fmt" 16 | "strings" 17 | "time" 18 | 19 | "golang.org/x/crypto/ssh" 20 | ) 21 | 22 | const ( 23 | caName = "open-ssh-ca@ejj.io" 24 | hour = time.Second * 3600 25 | allowableDrift = 60 * time.Second 26 | pemHeader = "BEGIN SSHCERT PRIVATE KEY" 27 | ) 28 | 29 | var ( 30 | // DefaultPermissions are the default permissions associated with the 31 | // signing of an ssh user certificate. In this case, we specify three 32 | // extensions. 33 | // - permit-pty: 34 | // Is set because creating a new pty on connection is required for 35 | // the best shell ux. 36 | // - permit-user-rc: 37 | // Allow users to forward their ssh agent to use jumpboxes. 38 | // - permit-agent-forwarding 39 | // Allows your engineers to utilize a jumpbox seamlessly. 40 | DefaultPermissions = ssh.Permissions{ 41 | Extensions: map[string]string{ 42 | "permit-pty": "", 43 | "permit-user-rc": "", 44 | "permit-port-forwarding": "", 45 | "permit-agent-forwarding": "", 46 | }, 47 | } 48 | ) 49 | 50 | // CA represents an SSH certificate authority. 51 | type CA struct { 52 | PrivateKey *ecdsa.PrivateKey 53 | customName string 54 | } 55 | 56 | // Cert represents an SSH public key that has been signed by a 57 | // certificate authority. 58 | type Cert struct { 59 | Certificate *ssh.Certificate 60 | } 61 | 62 | // SigningArguments is the information that the SSH Certificate Authority 63 | // needs in order to sign an SSH public key. All of these fields are required. 64 | // If you would like to read more about how to configure the SigningArguments 65 | // then I found the following to be a good source of information: 66 | // - https://github.com/metacloud/openssh/blob/master/PROTOCOL.certkeys 67 | // If you would like to use default settings then call `NewSigningArguments` 68 | type SigningArguments struct { 69 | Principals []string 70 | Permissions ssh.Permissions 71 | Duration time.Duration 72 | } 73 | 74 | // NewCA will instantiate a new CA and generate a fresh ecdsa Private key. 75 | func NewCA() (CA, error) { 76 | key, err := createPrivateKey() 77 | return CA{ 78 | PrivateKey: key, 79 | customName: caName, 80 | }, err 81 | } 82 | 83 | // SignCert is called to sign an ssh public key and produce an ssh certificate. 84 | // It's required to pass in SigningArguments or the signing will fail. 85 | func (c *CA) SignCert(pub ssh.PublicKey, signArgs *SigningArguments) (*Cert, error) { 86 | cert := &ssh.Certificate{ 87 | Key: pub, 88 | Serial: randomSerial(), 89 | CertType: ssh.UserCert, 90 | KeyId: randomHex(), 91 | // Subtract 60 seconds to allow for some clock drift between the signature signing and the remote servers 92 | ValidAfter: uint64(time.Now().Add(-allowableDrift).Unix()), 93 | ValidBefore: uint64(time.Now().Add(signArgs.Duration).Unix()), 94 | ValidPrincipals: signArgs.Principals, 95 | Permissions: signArgs.Permissions, 96 | } 97 | err := cert.SignCert(rand.Reader, c.Signer()) 98 | if err != nil { 99 | return nil, err 100 | } 101 | return &Cert{Certificate: cert}, nil 102 | } 103 | 104 | // PrivateString converts a CA in to a PEM encoded private key 105 | func (c *CA) PrivateString() (string, error) { 106 | privDer, err := x509.MarshalECPrivateKey(c.PrivateKey) 107 | if err != nil { 108 | return "", err 109 | } 110 | privBlock := pem.Block{ 111 | Type: pemHeader, 112 | Headers: nil, 113 | Bytes: privDer, 114 | } 115 | privatePEM := pem.EncodeToMemory(&privBlock) 116 | return string(privatePEM), nil 117 | } 118 | 119 | // ParsePrivateString hydrates a CA type with a PEM encoded private key. This 120 | // method will modify the CA's private key. 121 | func (c *CA) ParsePrivateString(data []byte) error { 122 | // Decode returns a block and a 'rest'. We don't really care 123 | // about the rest. In this case, the actual key data we need 124 | // is in the block bytes. 125 | block, _ := pem.Decode(data) 126 | return c.FromBytes(block.Bytes) 127 | } 128 | 129 | // Signer returns the signer associated with a private key. 130 | func (c *CA) Signer() ssh.Signer { 131 | // We can ignore this error. NewSignerFromKey supports ecdsa 132 | // PrivateKeys, but it's possible in the future we could 133 | // add support for unsupported crypto primitives. We will 134 | // need to check this error when we support more than ecdsa. 135 | signer, _ := ssh.NewSignerFromKey(c.PrivateKey) 136 | return signer 137 | } 138 | 139 | // String will output the public key of the Certificate Authority that is 140 | // used with the `TrustedUserCAKeys` directive in an sshd config. 141 | func (c *CA) String() string { 142 | return fmt.Sprintf("%s %s %s", c.Signer().PublicKey().Type(), base64.StdEncoding.EncodeToString(c.Signer().PublicKey().Marshal()), c.customName) 143 | } 144 | 145 | // Bytes converts the certificate authority private key to it's SSH key bytes. 146 | func (c *CA) Bytes() ([]byte, error) { 147 | return x509.MarshalECPrivateKey(c.PrivateKey) 148 | } 149 | 150 | // FromBytes hydreates a CA with the private key bytes. 151 | func (c *CA) FromBytes(data []byte) error { 152 | priv, err := x509.ParseECPrivateKey(data) 153 | if err != nil { 154 | return err 155 | } 156 | c.PrivateKey = priv 157 | return nil 158 | } 159 | 160 | func (c *CA) SetName(name string) { 161 | c.customName = name 162 | } 163 | 164 | // String will output the SSH certificate in a format that can be used 165 | // with an ssh client. 166 | func (c *Cert) String() string { 167 | return fmt.Sprintf("%s %s", c.Type(), base64.StdEncoding.EncodeToString(c.Certificate.Marshal())) 168 | } 169 | 170 | // Type returns the certificate's algorithm name. 171 | func (c *Cert) Type() string { 172 | return c.Certificate.Type() 173 | } 174 | 175 | // NewSigningArguments will create a default SigningArguments type with the 176 | // principals passed in. The list of principals passed in to this function 177 | // is the list of linux users that the user will be able to ssh to. 178 | func NewSigningArguments(principals []string) *SigningArguments { 179 | return &SigningArguments{ 180 | Permissions: DefaultPermissions, 181 | Duration: hour, 182 | Principals: principals, 183 | } 184 | } 185 | 186 | // SetPermissions will set the permissions of a SigningArguments type. 187 | func (s *SigningArguments) SetPermissions(permissions ssh.Permissions) { 188 | s.Permissions = permissions 189 | } 190 | 191 | // SetDuration will set the duration of a SigningArguments type. 192 | func (s *SigningArguments) SetDuration(d time.Duration) { 193 | s.Duration = d 194 | } 195 | 196 | // // SetPrincipals will set the principals of a SigningArguments type. 197 | func (s *SigningArguments) SetPrincipals(principals []string) { 198 | s.Principals = principals 199 | } 200 | 201 | // ParsePublicKey will parse and return an SSH public key from it's 202 | // non-wire format. 203 | func ParsePublicKey(pub string) (ssh.PublicKey, error) { 204 | pubParts := strings.Split(pub, " ") 205 | if len(pubParts) != 2 && len(pubParts) != 3 { 206 | return nil, errors.New("Invalid public key format") 207 | } 208 | pubBytes, err := base64.StdEncoding.DecodeString(pubParts[1]) 209 | pubKey, err := ssh.ParsePublicKey(pubBytes) 210 | if err != nil { 211 | return nil, err 212 | } 213 | return pubKey, nil 214 | } 215 | 216 | func createPrivateKey() (*ecdsa.PrivateKey, error) { 217 | privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 218 | if err != nil { 219 | return &ecdsa.PrivateKey{}, err 220 | } 221 | return privateKey, nil 222 | } 223 | 224 | func randomSerial() uint64 { 225 | buf := make([]byte, 8) 226 | rand.Read(buf) 227 | return binary.LittleEndian.Uint64(buf) 228 | } 229 | 230 | func randomHex() string { 231 | buf := make([]byte, 16) 232 | rand.Read(buf) 233 | return hex.EncodeToString(buf) 234 | } 235 | -------------------------------------------------------------------------------- /sshcert_test.go: -------------------------------------------------------------------------------- 1 | package sshcert 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "log" 7 | "strings" 8 | "testing" 9 | ) 10 | 11 | func TestCreatePrivateKey(t *testing.T) { 12 | key, err := createPrivateKey() 13 | if err != nil { 14 | t.Fatalf("Could not generate private key: %s", err) 15 | } 16 | if key == nil { 17 | t.Fatalf("key is nil") 18 | } 19 | } 20 | 21 | func ExampleNewCA() { 22 | // Your CA is has sensitive fields. It contains a PrivateKey 23 | // that is the root of all trust in your infrastructure. 24 | ca, err := NewCA() 25 | if err != nil { 26 | log.Fatalf("Could not create new ca: %s", err) 27 | } 28 | // This will print the public key of your certificate authority 29 | // in a format that can be used by the `TrustedUserCAKeys` sshd 30 | // config directive. 31 | fmt.Println(ca) 32 | } 33 | 34 | func TestNewCA(t *testing.T) { 35 | _, err := NewCA() 36 | if err != nil { 37 | t.Fatalf("Could not create ca: %s", err) 38 | } 39 | } 40 | 41 | func TestPublicKeyString(t *testing.T) { 42 | ca, _ := NewCA() 43 | _, err := ParsePublicKey(ca.String()) 44 | if err != nil { 45 | t.Fatalf("Could not parse public key: %s", err) 46 | } 47 | } 48 | 49 | func TestParsePublicKey(t *testing.T) { 50 | pubBytes, _ := ioutil.ReadFile("testfiles/testkeys.pub") 51 | _, err := ParsePublicKey(string(pubBytes)) 52 | if err != nil { 53 | t.Fatalf("Could not parse public key: %s", err) 54 | } 55 | } 56 | 57 | func ExampleParsePublicKey() { 58 | // To parse ssh public keys 59 | pubBytes, _ := ioutil.ReadFile("example.pub") 60 | pubKey, err := ParsePublicKey(string(pubBytes)) 61 | if err != nil { 62 | log.Fatalf("Could not parse public key: %s", err) 63 | } 64 | fmt.Println(pubKey) 65 | } 66 | 67 | func TestSignCert(t *testing.T) { 68 | tests := []struct { 69 | algo string 70 | fileName string 71 | }{ 72 | {algo: "ecdsa-sha2-nistp256-cert-v01@openssh.com", fileName: "testkeys.pub"}, 73 | {algo: "ssh-ed25519-cert-v01@openssh.com", fileName: "ed25519_test_key.pub"}, 74 | } 75 | 76 | for _, tc := range tests { 77 | ca, _ := NewCA() 78 | pubBytes, _ := ioutil.ReadFile(fmt.Sprintf("testfiles/%s", tc.fileName)) 79 | pub, _ := ParsePublicKey(string(pubBytes)) 80 | signArgs := NewSigningArguments([]string{"root"}) 81 | 82 | c, err := ca.SignCert(pub, signArgs) 83 | if err != nil { 84 | t.Fatalf("Could not sign cert: %s", err) 85 | } 86 | if c.Type() != tc.algo { 87 | t.Fatalf("Certificate and public key type do not match: %s != %s", c.Type(), tc.algo) 88 | } 89 | } 90 | } 91 | 92 | func TestGenerateNonce(t *testing.T) { 93 | r := randomHex() 94 | if len(r) != 32 { 95 | t.Fatalf("Invalid nonce generated: %s", r) 96 | } 97 | } 98 | 99 | func TestToBytesAndBack(t *testing.T) { 100 | ca, _ := NewCA() 101 | buf, err := ca.Bytes() 102 | if err != nil { 103 | t.Fatalf("Could not marshal ca: %s", err) 104 | } 105 | var ca2 CA 106 | err = ca2.FromBytes(buf) 107 | if err != nil { 108 | t.Fatalf("Could not unmarshal ca: %s", err) 109 | } 110 | if ca.PrivateKey.D.Cmp(ca2.PrivateKey.D) != 0 { 111 | t.Fatal("The private keys are different after marshal/unmarshal") 112 | } 113 | } 114 | 115 | func TestSetCAName(t *testing.T) { 116 | ca, _ := NewCA() 117 | ca.SetName("mycahello") 118 | s := ca.String() 119 | if !strings.Contains(s, "mycahello") { 120 | t.Fatal("CA pub key does not contain the proper name") 121 | } 122 | if strings.Contains(s, "ejj.io") { 123 | t.Fatal("CA pub key contains the default name") 124 | } 125 | } 126 | func TestPrivateString(t *testing.T) { 127 | ca, _ := NewCA() 128 | priv, err := ca.PrivateString() 129 | if err != nil { 130 | t.Fatalf("Could not PEM encode private key: %s", err) 131 | } 132 | if !strings.Contains(priv, pemHeader) { 133 | t.Fatal("Could not find SSHCert header in PEM private key") 134 | } 135 | 136 | // Now we need to attempt to parse it. 137 | var ca2 CA 138 | err = ca2.ParsePrivateString([]byte(priv)) 139 | if err != nil { 140 | t.Fatalf("Could not parse PEM encoded syntax: %s", err) 141 | } 142 | if ca.PrivateKey.D.Cmp(ca2.PrivateKey.D) != 0 { 143 | t.Fatal("The private keys are different pem encode decode") 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /testfiles/ed25519_test_key.pub: -------------------------------------------------------------------------------- 1 | ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAf48cHMj3/Vlbq69mHh4vSyRyBnwjWkYlH4BBWegNIa 2 | -------------------------------------------------------------------------------- /testfiles/testkeys: -------------------------------------------------------------------------------- 1 | -----BEGIN OPENSSH PRIVATE KEY----- 2 | b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS 3 | 1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQScSgvOZiPVUfKxArmltqpe8oZewlJf 4 | di7zfGuvF/nb5ADy/u0dwb8SM0NPplXxSIH8Y7QCYh283SqRa3cPhWBlAAAAuMasMdfGrD 5 | HXAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJxKC85mI9VR8rEC 6 | uaW2ql7yhl7CUl92LvN8a68X+dvkAPL+7R3BvxIzQ0+mVfFIgfxjtAJiHbzdKpFrdw+FYG 7 | UAAAAgIV84HrLZMLgIfwaHPM1IhLJxm6ET1uH0RBmnsX04OiMAAAAZZUBFdmFucy1NYWNC 8 | b29rLVByby5sb2NhbAECAwQFBgc= 9 | -----END OPENSSH PRIVATE KEY----- 10 | -------------------------------------------------------------------------------- /testfiles/testkeys.pub: -------------------------------------------------------------------------------- 1 | ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJxKC85mI9VR8rECuaW2ql7yhl7CUl92LvN8a68X+dvkAPL+7R3BvxIzQ0+mVfFIgfxjtAJiHbzdKpFrdw+FYGU= e@Evans-MacBook-Pro.local 2 | --------------------------------------------------------------------------------