├── .gitignore ├── https_server.go ├── https_client.go ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .sw? 2 | .*.sw? 3 | -------------------------------------------------------------------------------- /https_server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | "io/ioutil" 7 | "log" 8 | "net/http" 9 | ) 10 | 11 | func main() { 12 | caCert, err := ioutil.ReadFile("client.crt") 13 | if err != nil { 14 | log.Fatal(err) 15 | } 16 | caCertPool := x509.NewCertPool() 17 | caCertPool.AppendCertsFromPEM(caCert) 18 | cfg := &tls.Config{ 19 | ClientAuth: tls.RequireAndVerifyClientCert, 20 | ClientCAs: caCertPool, 21 | } 22 | srv := &http.Server{ 23 | Addr: ":8443", 24 | Handler: &handler{}, 25 | TLSConfig: cfg, 26 | } 27 | log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key")) 28 | } 29 | 30 | type handler struct{} 31 | 32 | func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { 33 | w.Write([]byte("PONG\n")) 34 | } 35 | -------------------------------------------------------------------------------- /https_client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/tls" 5 | "crypto/x509" 6 | "fmt" 7 | "io/ioutil" 8 | "log" 9 | "net/http" 10 | ) 11 | 12 | func main() { 13 | caCert, err := ioutil.ReadFile("server.crt") 14 | if err != nil { 15 | log.Fatal(err) 16 | } 17 | caCertPool := x509.NewCertPool() 18 | caCertPool.AppendCertsFromPEM(caCert) 19 | 20 | cert, err := tls.LoadX509KeyPair("client.crt", "client.key") 21 | if err != nil { 22 | log.Fatal(err) 23 | } 24 | 25 | client := &http.Client{ 26 | Transport: &http.Transport{ 27 | TLSClientConfig: &tls.Config{ 28 | RootCAs: caCertPool, 29 | Certificates: []tls.Certificate{cert}, 30 | }, 31 | }, 32 | } 33 | 34 | resp, err := client.Get("https://localhost:8443") 35 | if err != nil { 36 | log.Println(err) 37 | return 38 | } 39 | 40 | htmlData, err := ioutil.ReadAll(resp.Body) 41 | if err != nil { 42 | fmt.Println(err) 43 | return 44 | } 45 | defer resp.Body.Close() 46 | fmt.Printf("%v\n", resp.Status) 47 | fmt.Printf(string(htmlData)) 48 | } 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TLS Connection Options in Golang 2 | 3 | This is not an official Google product 4 | 5 | Golang sample code for a minimal HTTPS client and server that demos: 6 | 7 | * a server certificate that satisfies SAN requirements. 8 | * a client that trusts a specific certificate. 9 | * a server that authenticates the client based on the client certificate used 10 | in connection negotiation. 11 | 12 | ## Generating Key and Self Signed Cert 13 | 14 | ```sh 15 | openssl req \ 16 | -x509 \ 17 | -nodes \ 18 | -newkey rsa:2048 \ 19 | -keyout server.key \ 20 | -out server.crt \ 21 | -days 3650 \ 22 | -subj "/C=GB/ST=London/L=London/O=Global Security/OU=IT Department/CN=*" 23 | ``` 24 | 25 | ## Running the Server 26 | 27 | ```sh 28 | go run https_server.go 29 | ``` 30 | 31 | ## Running the Client 32 | 33 | ```sh 34 | go run https_client.go 35 | ``` 36 | 37 | ## Error/Solution 38 | 39 | **Error:** `x509: certificate signed by unknown authority` 40 | 41 | **Solution:** The certificate served by https_server is self signed. This 42 | message means that the Go lang https library can't find a way to trust the 43 | certificate the server is responding with. 44 | 45 | There are two possible solutions. 46 | 47 | 1. Disable the client side certificate verification. This solution has the 48 | advantage of expediency, but the disadvantage of making your client code 49 | susceptible to man in the middle attacks. 50 | 51 | ```diff 52 | @@ -11,7 +11,9 @@ import ( 53 | func main() { 54 | client := &http.Client{ 55 | Transport: &http.Transport{ 56 | - TLSClientConfig: &tls.Config{}, 57 | + TLSClientConfig: &tls.Config{ 58 | + InsecureSkipVerify: true, 59 | + }, 60 | }, 61 | } 62 | ``` 63 | 64 | 2. Add the server certificate to the list of certificate authorities trusted by 65 | the client. 66 | 67 | ```diff 68 | @@ -9,9 +10,18 @@ import ( 69 | ) 70 | 71 | func main() { 72 | + caCert, err := ioutil.ReadFile("server.crt") 73 | + if err != nil { 74 | + log.Fatal(err) 75 | + } 76 | + caCertPool := x509.NewCertPool() 77 | + caCertPool.AppendCertsFromPEM(caCert) 78 | + 79 | client := &http.Client{ 80 | Transport: &http.Transport{ 81 | - TLSClientConfig: &tls.Config{}, 82 | + TLSClientConfig: &tls.Config{ 83 | + RootCAs: caCertPool, 84 | + }, 85 | }, 86 | } 87 | ``` 88 | 89 | **Error:** `x509: invalid signature: parent certificate cannot sign this kind of certificate` 90 | 91 | **Solution:** The wrong kind of server certificate was generated. The property 92 | in the CA that signed the server certificate indicates that the signing 93 | certificate is not a CA. Since this is a self signed server certificate, it 94 | needs the signing permission to sign itself. 95 | 96 | Using `openssl x509 -in server.crt -text -noout` to look at the details of the 97 | server certificate reveals that it is missing the CA flag, which should look 98 | like this: 99 | 100 | ``` 101 | X509v3 Basic Constraints: 102 | CA:TRUE 103 | ``` 104 | 105 | **Error:** `x509: cannot validate certificate for 127.0.0.1 because it doesn't contain any IP SANs` 106 | 107 | **Solution:** A SAN is a Subject Alternative Name, an x509 extension that 108 | allows additional names to be specified as valid domains for the certficate. 109 | 110 | Starting with Go 1.3, when connecting to a server via the IP address rather 111 | than the hostname, the CN field in the server certificate is ignored by the 112 | client golang libraries and names specified as SANs will be used instead. 113 | 114 | Using `openssl x509 -in server.crt -text -noout` to look at the details of the 115 | server certificate reveals that it is missing a SAN section, which should look 116 | like this: 117 | 118 | ``` 119 | X509v3 extensions: 120 | X509v3 Subject Alternative Name: 121 | IP Address:127.0.0.1 122 | ``` 123 | 124 | There are two possible solutions. 125 | 126 | 1. Use a name to connect to the server instead of an IP address. If the client 127 | connects with a name matching the certificate CN, a SAN is not required. 128 | 129 | ```diff 130 | - resp, err := client.Get("https://127.0.0.1:8443") 131 | + resp, err := client.Get("https://localhost:8443") 132 | ``` 133 | 134 | Using `openssl x509 -in server.crt -text -noout` to look at the **Subject** 135 | line should show **CN=** matching the name of the server. `localhost` or 136 | `*` will work. 137 | 138 | ``` 139 | Subject: CN=* 140 | ``` 141 | 142 | 2. Add a SAN to the certificate with the IP address of the server. 143 | 144 | To add a SAN to a certificate, there is multiple steps required, that will 145 | generate a separate CA and use that to sign the server certificate signing 146 | request. 147 | 148 | ```sh 149 | openssl req \ 150 | -newkey rsa:2048 \ 151 | -nodes \ 152 | -days 3650 \ 153 | -x509 \ 154 | -keyout ca.key \ 155 | -out ca.crt \ 156 | -subj "/CN=*" 157 | openssl req \ 158 | -newkey rsa:2048 \ 159 | -nodes \ 160 | -keyout server.key \ 161 | -out server.csr \ 162 | -subj "/C=GB/ST=London/L=London/O=Global Security/OU=IT Department/CN=*" 163 | openssl x509 \ 164 | -req \ 165 | -days 365 \ 166 | -sha256 \ 167 | -in server.csr \ 168 | -CA ca.crt \ 169 | -CAkey ca.key \ 170 | -CAcreateserial \ 171 | -out server.crt \ 172 | -extfile <(echo subjectAltName = IP:127.0.0.1) 173 | ``` 174 | 175 | **Error:** `tls: client didn't provide a certificate` 176 | 177 | **Solution:** When the server code has the option set to authenticate client 178 | connections using the client certificate, like this: 179 | 180 | ```diff 181 | - cfg := &tls.Config{} 182 | + cfg := &tls.Config{ 183 | + ClientAuth: tls.RequireAndVerifyClientCert, 184 | + } 185 | ``` 186 | 187 | the server will drop connections from clients using certs that are untrusted, 188 | where trust is established by a relationship to one of the CAs that the TLS 189 | server knows about. 190 | 191 | In order to establish a connection, the client will have to present a trusted 192 | certificate. To start, generate a client certificate to use: 193 | 194 | ```sh 195 | openssl req \ 196 | -x509 \ 197 | -nodes \ 198 | -newkey rsa:2048 \ 199 | -keyout client.key \ 200 | -out client.crt \ 201 | -days 3650 \ 202 | -subj "/C=GB/ST=London/L=London/O=Global Security/OU=IT Department/CN=*" 203 | ``` 204 | 205 | Next, configure the client to send a certificate with connection attempts: 206 | 207 | ```diff 208 | + cert, err := tls.LoadX509KeyPair("client.crt", "client.key") 209 | + if err != nil { 210 | + log.Fatal(err) 211 | + } 212 | + 213 | client := &http.Client{ 214 | Transport: &http.Transport{ 215 | TLSClientConfig: &tls.Config{ 216 | RootCAs: caCertPool, 217 | + Certificates: []tls.Certificate{cert}, 218 | }, 219 | }, 220 | } 221 | ``` 222 | 223 | Then, configure the server to trust the client certificate: 224 | 225 | ```diff 226 | + caCert, err := ioutil.ReadFile("client.crt") 227 | + if err != nil { 228 | + log.Fatal(err) 229 | + } 230 | + caCertPool := x509.NewCertPool() 231 | + caCertPool.AppendCertsFromPEM(caCert) 232 | cfg := &tls.Config{ 233 | ClientAuth: tls.RequireAndVerifyClientCert, 234 | + ClientCAs: caCertPool, 235 | } 236 | ``` 237 | 238 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [2017] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------