blob: f014a346662f16e240c29dfe0f73ef591f314e3a [file] [log] [blame]
Serge Bazanski814749f2018-10-25 12:01:10 +01001package pki
Sergiusz Bazanskif02cd772018-08-28 15:25:33 +01002
3// Copyright 2018 Sergiusz Bazanski <q3k@hackerspace.pl>
4//
5// Permission to use, copy, modify, and/or distribute this software for any
6// purpose with or without fee is hereby granted, provided that the above
7// copyright notice and this permission notice appear in all copies.
8//
9// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
15// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
17import (
18 "context"
19 "crypto/tls"
20 "crypto/x509"
21 "flag"
22 "fmt"
23 "io/ioutil"
24 "strings"
25
26 "github.com/golang/glog"
27 "golang.org/x/net/trace"
28 "google.golang.org/grpc"
29 "google.golang.org/grpc/codes"
30 "google.golang.org/grpc/credentials"
31 "google.golang.org/grpc/peer"
32 "google.golang.org/grpc/status"
33)
34
35var (
36 flagCAPath string
37 flagCertificatePath string
38 flagKeyPath string
39 flagPKIRealm string
40
41 // Enable logging HSPKI info into traces
42 Trace = true
43 // Enable logging HSPKI info into glog
44 Log = false
45)
46
47const (
48 ctxKeyClientInfo = "hspki-client-info"
49)
50
51func init() {
52 flag.StringVar(&flagCAPath, "hspki_tls_ca_path", "pki/ca.pem", "Path to PKI CA certificate")
53 flag.StringVar(&flagCertificatePath, "hspki_tls_certificate_path", "pki/service.pem", "Path to PKI service certificate")
54 flag.StringVar(&flagKeyPath, "hspki_tls_key_path", "pki/service-key.pem", "Path to PKI service private key")
55 flag.StringVar(&flagPKIRealm, "hspki_realm", "svc.cluster.local", "PKI realm")
56}
57
58func maybeTrace(ctx context.Context, f string, args ...interface{}) {
59 if Log {
60 glog.Infof(f, args...)
61 }
62
63 if !Trace {
64 return
65 }
66
67 tr, ok := trace.FromContext(ctx)
68 if !ok {
69 if !Log {
70 fmtd := fmt.Sprintf(f, args...)
71 glog.Info("[no trace] %v", fmtd)
72 }
73 return
74 }
75 tr.LazyPrintf(f, args...)
76}
77
78func parseClientName(name string) (*ClientInfo, error) {
79 if !strings.HasSuffix(name, "."+flagPKIRealm) {
80 return nil, fmt.Errorf("invalid realm")
81 }
82 service := strings.TrimSuffix(name, "."+flagPKIRealm)
83 parts := strings.Split(service, ".")
84 if len(parts) != 2 {
85 return nil, fmt.Errorf("invalid job/principal format")
86 }
87 return &ClientInfo{
88 Realm: flagPKIRealm,
89 Principal: parts[1],
90 Job: parts[0],
91 }, nil
92}
93
94func withPKIInfo(ctx context.Context, c *ClientInfo) context.Context {
95 maybeTrace(ctx, "HSPKI: Applying ClientInfo: %s", c.String())
96 return context.WithValue(ctx, ctxKeyClientInfo, c)
97}
98
99func grpcInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
100 peer, ok := peer.FromContext(ctx)
101 if !ok {
102 maybeTrace(ctx, "HSPKI: Could not establish identity of peer.")
103 return nil, status.Errorf(codes.PermissionDenied, "no peer info")
104 }
105
106 authInfo, ok := peer.AuthInfo.(credentials.TLSInfo)
107 if !ok {
108 maybeTrace(ctx, "HSPKI: Could not establish TLS identity of peer.")
109 return nil, status.Errorf(codes.PermissionDenied, "no TLS certificate presented")
110 }
111
112 chains := authInfo.State.VerifiedChains
113 if len(chains) != 1 {
114 maybeTrace(ctx, "HSPKI: No trusted chains found.")
115 return nil, status.Errorf(codes.PermissionDenied, "no trusted TLS certificate presented")
116 }
117
118 chain := chains[0]
119
120 certDNs := make([]string, len(chain))
121 for i, cert := range chain {
122 certDNs[i] = cert.Subject.String()
123 }
124 maybeTrace(ctx, "HSPKI: Trust chain: %s", strings.Join(certDNs, ", "))
125
126 clientInfo, err := parseClientName(chain[0].Subject.CommonName)
127 if err != nil {
128 maybeTrace(ctx, "HSPKI: Invalid CN %q: %v", chain[0].Subject.CommonName, err)
129 return nil, status.Errorf(codes.PermissionDenied, "invalid TLS CN format")
130 }
131 ctx = withPKIInfo(ctx, clientInfo)
132 return handler(ctx, req)
133}
134
135// ClientInfo contains information about the HSPKI authentication data of the
136// gRPC client that has made the request.
137type ClientInfo struct {
138 Realm string
139 Principal string
140 Job string
141}
142
143// String returns a human-readable representation of the ClientInfo in the
144// form "job=foo, principal=bar, realm=baz".
145func (c *ClientInfo) String() string {
146 return fmt.Sprintf("job=%q, principal=%q, realm=%q", c.Job, c.Principal, c.Realm)
147}
148
149// ClientInfoFromContext returns ClientInfo from a gRPC service context.
150func ClientInfoFromContext(ctx context.Context) *ClientInfo {
151 v := ctx.Value(ctxKeyClientInfo)
152 if v == nil {
153 return nil
154 }
155 ci, ok := v.(*ClientInfo)
156 if !ok {
157 return nil
158 }
159 return ci
160}
161
162// WithServerHSPKI is a grpc.ServerOptions array that ensures that the gRPC server:
163// - runs with HSPKI TLS Service Certificate
164// - rejects all non_HSPKI compatible requests
165// - injects ClientInfo into the service context, which can be later retrieved
166// using ClientInfoFromContext
167func WithServerHSPKI() []grpc.ServerOption {
168 if !flag.Parsed() {
169 glog.Exitf("WithServerHSPKI called before flag.Parse!")
170 }
171 serverCert, err := tls.LoadX509KeyPair(flagCertificatePath, flagKeyPath)
172 if err != nil {
173 glog.Exitf("WithServerHSPKI: cannot load service certificate/key: %v", err)
174 }
175
176 certPool := x509.NewCertPool()
177 ca, err := ioutil.ReadFile(flagCAPath)
178 if err != nil {
179 glog.Exitf("WithServerHSPKI: cannot load CA certificate: %v", err)
180 }
181 if ok := certPool.AppendCertsFromPEM(ca); !ok {
182 glog.Exitf("WithServerHSPKI: cannot use CA certificate: %v", err)
183 }
184
185 creds := grpc.Creds(credentials.NewTLS(&tls.Config{
186 ClientAuth: tls.RequireAndVerifyClientCert,
187 Certificates: []tls.Certificate{serverCert},
188 ClientCAs: certPool,
189 }))
190
191 interceptor := grpc.UnaryInterceptor(grpcInterceptor)
192
193 return []grpc.ServerOption{creds, interceptor}
194}
Serge Bazanski624295d2018-10-06 18:17:56 +0100195
196func WithClientHSPKI() grpc.DialOption {
197 certPool := x509.NewCertPool()
198 ca, err := ioutil.ReadFile(flagCAPath)
199 if err != nil {
200 glog.Exitf("WithClientHSPKI: cannot load CA certificate: %v", err)
201 }
202 if ok := certPool.AppendCertsFromPEM(ca); !ok {
203 glog.Exitf("WithClientHSPKI: cannot use CA certificate: %v", err)
204 }
205
206 clientCert, err := tls.LoadX509KeyPair(flagCertificatePath, flagKeyPath)
207 if err != nil {
208 glog.Exitf("WithClientHSPKI: cannot load service certificate/key: %v", err)
209 }
210
211 creds := credentials.NewTLS(&tls.Config{
212 Certificates: []tls.Certificate{clientCert},
213 RootCAs: certPool,
214 })
215 return grpc.WithTransportCredentials(creds)
216}