| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package workercmd |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "crypto" |
| 22 | "crypto/hmac" |
| 23 | "crypto/rsa" |
| 24 | "crypto/x509" |
| 25 | "encoding/json" |
| 26 | "errors" |
| 27 | "fmt" |
| 28 | "io" |
| 29 | "net/http" |
| 30 | "os" |
| 31 | "time" |
| 32 | |
| 33 | "github.com/miekg/pkcs11" |
| 34 | "github.com/rs/zerolog/log" |
| 35 | |
| 36 | "github.com/sassoftware/relic/v7/cmdline/shared" |
| 37 | "github.com/sassoftware/relic/v7/internal/workerrpc" |
| 38 | "github.com/sassoftware/relic/v7/token" |
| 39 | "github.com/sassoftware/relic/v7/token/tokencache" |
| 40 | ) |
| 41 | |
| 42 | // an arbitarily-chosen set of error codes that indicate that the token session |
| 43 | // is busted and that the worker should exit and start over |
| 44 | var fatalErrors = map[pkcs11Error]bool{ |
| 45 | pkcs11.CKR_CRYPTOKI_NOT_INITIALIZED: true, |
| 46 | pkcs11.CKR_DEVICE_REMOVED: true, |
| 47 | pkcs11.CKR_GENERAL_ERROR: true, |
| 48 | pkcs11.CKR_HOST_MEMORY: true, |
| 49 | pkcs11.CKR_LIBRARY_LOAD_FAILED: true, |
| 50 | pkcs11.CKR_SESSION_CLOSED: true, |
| 51 | pkcs11.CKR_SESSION_HANDLE_INVALID: true, |
| 52 | pkcs11.CKR_TOKEN_NOT_PRESENT: true, |
| 53 | pkcs11.CKR_TOKEN_NOT_RECOGNIZED: true, |
| 54 | pkcs11.CKR_USER_NOT_LOGGED_IN: true, |
| 55 | } |
| 56 | |
| 57 | func (h *handler) healthCheck() { |
| 58 | interval := time.Duration(shared.CurrentConfig.Server.TokenCheckInterval) * time.Second |
| 59 | timeout := time.Duration(shared.CurrentConfig.Server.TokenCheckTimeout) * time.Second |
| 60 | ppid := os.Getppid() |
| 61 | tick := time.NewTicker(interval) |
| 62 | errch := make(chan error) |
| 63 | for { |
| 64 | // check if parent process went away |
| 65 | if os.Getppid() != ppid { |
| 66 | log.Error(). |
| 67 | Int("old_ppid", ppid).Int("new_ppid", os.Getppid()). |
| 68 | Msg("parent process disappeared, worker stopping") |
| 69 | h.shutdown() |
| 70 | return |
| 71 | } |
| 72 | // check if token is alive |
| 73 | ctx, cancel := context.WithTimeout(context.Background(), timeout) |
| 74 | go func() { |
| 75 | errch <- h.token.Ping(ctx) |
| 76 | }() |
| 77 | var err error |
| 78 | select { |
| 79 | case err = <-errch: |
| 80 | // ping completed |
| 81 | case <-ctx.Done(): |
| 82 | // timed out |
| 83 | err = fmt.Errorf("timed out after %s", timeout) |
| 84 | } |
| 85 | cancel() |
| 86 | if err != nil { |
| 87 | // stop the worker on error |
| 88 | log.Err(err).Msg("token health check failed") |
| 89 | h.shutdown() |
| 90 | return |
| 91 | } |
| 92 | // wait for next tick |
| 93 | <-tick.C |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | type handler struct { |
| 98 | token *tokencache.Cache |
| 99 | cookie []byte |
| 100 | shutdown func() |
| 101 | } |
| 102 | |
| 103 | func (h *handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { |
| 104 | // validate auth cookie |
| 105 | cookie := req.Header.Get("Auth-Cookie") |
| 106 | if !hmac.Equal([]byte(cookie), []byte(h.cookie)) { |
| 107 | rw.WriteHeader(http.StatusForbidden) |
| 108 | return |
| 109 | } |
| 110 | // dispatch |
| 111 | resp, err := h.handle(rw, req) |
| 112 | if err != nil { |
| 113 | resp.Retryable = true |
| 114 | resp.Err = err.Error() |
| 115 | switch e := err.(type) { |
| 116 | case pkcs11Error: |
| 117 | if fatalErrors[e] { |
| 118 | log.Err(err).Msg("terminating worker due to token error") |
| 119 | go h.shutdown() |
| 120 | // errors that cause the worker to restart are also retryable |
| 121 | resp.Retryable = true |
| 122 | } else { |
| 123 | // pkcs11 errors not in fatalErrors are probably user error, so don't retry |
| 124 | resp.Retryable = false |
| 125 | } |
| 126 | case token.NotImplementedError: |
| 127 | resp.Retryable = false |
| 128 | case token.KeyUsageError: |
| 129 | resp.Retryable = false |
| 130 | resp.Usage = true |
| 131 | resp.Key = e.Key |
| 132 | resp.Err = e.Err.Error() |
| 133 | } |
| 134 | } |
| 135 | // marshal response |
| 136 | blob, err := json.Marshal(resp) |
| 137 | if err == nil { |
| 138 | _, err = rw.Write(blob) |
| 139 | } |
| 140 | if err != nil { |
| 141 | log.Err(err).Msg("error handling worker request") |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | func (h *handler) handle(rw http.ResponseWriter, req *http.Request) (resp workerrpc.Response, err error) { |
| 146 | blob, err := io.ReadAll(req.Body) |
| 147 | if err != nil { |
| 148 | return resp, err |
| 149 | } |
| 150 | var rr workerrpc.Request |
| 151 | if err := json.Unmarshal(blob, &rr); err != nil { |
| 152 | return resp, err |
| 153 | } |
| 154 | ctx := req.Context() |
| 155 | if rr.KeyID != nil { |
| 156 | // if the caller knows the key ID already, pass that along to ensure the |
| 157 | // same key is used in case it got rotated |
| 158 | ctx = token.WithKeyID(ctx, rr.KeyID) |
| 159 | } |
| 160 | switch req.URL.Path { |
| 161 | case workerrpc.Ping: |
| 162 | return resp, h.token.Ping(ctx) |
| 163 | case workerrpc.GetKey: |
| 164 | key, err := h.token.GetKey(ctx, rr.KeyName) |
| 165 | if err != nil { |
| 166 | return resp, err |
| 167 | } |
| 168 | resp.ID = key.GetID() |
| 169 | resp.Cert = key.Certificate() |
| 170 | resp.Value, err = x509.MarshalPKIXPublicKey(key.Public()) |
| 171 | return resp, err |
| 172 | case workerrpc.Sign: |
| 173 | hash := crypto.Hash(rr.Hash) |
| 174 | opts := crypto.SignerOpts(hash) |
| 175 | if rr.SaltLength != nil { |
| 176 | opts = &rsa.PSSOptions{SaltLength: *rr.SaltLength, Hash: hash} |
| 177 | } |
| 178 | key, err := h.token.GetKey(ctx, rr.KeyName) |
| 179 | if err != nil { |
| 180 | return resp, err |
| 181 | } |
| 182 | resp.Value, err = key.SignContext(ctx, rr.Digest, opts) |
| 183 | return resp, err |
| 184 | default: |
| 185 | return resp, errors.New("invalid method: " + req.URL.Path) |
| 186 | } |
| 187 | } |