1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
|
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httputil"
"github.com/cloudflare/cfssl/api"
"github.com/cloudflare/cfssl/auth"
"github.com/cloudflare/cfssl/helpers"
"github.com/cloudflare/cfssl/log"
"github.com/cloudflare/cfssl/signer"
"github.com/cloudflare/cfssl/whitelist"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
// A SignatureResponse contains only a certificate, as there is no other
// useful data for the CA to return at this time.
type SignatureResponse struct {
Certificate string `json:"certificate"`
}
type filter func(string, *signer.SignRequest) bool
var filters = map[string][]filter{}
var (
requests = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "requests_total",
Help: "How many requests for each operation type and signer were succesfully processed.",
},
[]string{"operation", "signer"},
)
erroredRequests = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "requests_errored_total",
Help: "How many requests for each operation type resulted in an error.",
},
[]string{"operation", "signer"},
)
badInputs = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "bad_inputs_total",
Help: "How many times the input was malformed or not allowed.",
},
[]string{"operation"},
)
)
const (
signOperation = "sign"
)
func fail(w http.ResponseWriter, req *http.Request, status, code int, msg, ad string) {
badInputs.WithLabelValues(signOperation).Inc()
if ad != "" {
ad = " (" + ad + ")"
}
log.Errorf("[HTTP %d] %d - %s%s", status, code, msg, ad)
dumpReq, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Printf("%v#v\n", req)
} else {
fmt.Printf("%s\n", dumpReq)
}
res := api.NewErrorResponse(msg, code)
w.WriteHeader(status)
jenc := json.NewEncoder(w)
jenc.Encode(res)
}
func dispatchRequest(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
fail(w, req, http.StatusMethodNotAllowed, 1, "only POST is permitted", "")
return
}
defer req.Body.Close()
body, err := io.ReadAll(req.Body)
if err != nil {
fail(w, req, http.StatusInternalServerError, 1, err.Error(), "while reading request body")
return
}
var authReq auth.AuthenticatedRequest
err = json.Unmarshal(body, &authReq)
if err != nil {
fail(w, req, http.StatusBadRequest, 1, err.Error(), "while unmarshaling request body")
return
}
var sigRequest signer.SignRequest
err = json.Unmarshal(authReq.Request, &sigRequest)
if err != nil {
fail(w, req, http.StatusBadRequest, 1, err.Error(), "while unmarshalling authenticated request")
return
}
if sigRequest.Label == "" {
sigRequest.Label = defaultLabel
}
acl := whitelists[sigRequest.Label]
if acl != nil {
ip, err := whitelist.HTTPRequestLookup(req)
if err != nil {
fail(w, req, http.StatusInternalServerError, 1, err.Error(), "while getting request IP")
return
}
if !acl.Permitted(ip) {
fail(w, req, http.StatusForbidden, 1, "not authorised", "because IP is not whitelisted")
return
}
}
s, ok := signers[sigRequest.Label]
if !ok {
fail(w, req, http.StatusBadRequest, 1, "bad request", "request is for non-existent label "+sigRequest.Label)
return
}
requests.WithLabelValues(signOperation, sigRequest.Label).Inc()
// Sanity checks to ensure that we have a valid policy. This
// should have been checked in NewAuthSignHandler.
policy := s.Policy()
if policy == nil {
fail(w, req, http.StatusInternalServerError, 1, "invalid policy", "signer was initialised without a signing policy")
return
}
profile := policy.Default
if policy.Profiles != nil && sigRequest.Profile != "" {
profile = policy.Profiles[sigRequest.Profile]
if profile == nil {
fail(w, req, http.StatusBadRequest, 1, "invalid profile", "failed to look up profile with name: "+sigRequest.Profile)
return
}
}
if profile == nil {
fail(w, req, http.StatusInternalServerError, 1, "invalid profile", "signer was initialised without any valid profiles")
return
}
if profile.Provider == nil {
fail(w, req, http.StatusUnauthorized, 1, "authorisation required", "received unauthenticated request")
return
}
validAuth := false
if profile.Provider.Verify(&authReq) {
validAuth = true
} else if profile.PrevProvider != nil && profile.PrevProvider.Verify(&authReq) {
validAuth = true
}
if !validAuth {
fail(w, req, http.StatusBadRequest, 1, "invalid token", "received authenticated request with invalid token")
return
}
if sigRequest.Request == "" {
fail(w, req, http.StatusBadRequest, 1, "invalid request", "empty request")
return
}
cert, err := s.Sign(sigRequest)
if err != nil {
erroredRequests.WithLabelValues(signOperation, sigRequest.Label).Inc()
fail(w, req, http.StatusBadRequest, 1, "bad request", "signature failed: "+err.Error())
return
}
x509Cert, err := helpers.ParseCertificatePEM(cert)
if err != nil {
erroredRequests.WithLabelValues(signOperation, sigRequest.Label).Inc()
fail(w, req, http.StatusInternalServerError, 1, "bad certificate", err.Error())
}
log.Infof("signature: requester=%s, label=%s, profile=%s, serialno=%s",
req.RemoteAddr, sigRequest.Label, sigRequest.Profile, x509Cert.SerialNumber)
res := api.NewSuccessResponse(&SignatureResponse{Certificate: string(cert)})
jenc := json.NewEncoder(w)
err = jenc.Encode(res)
if err != nil {
log.Errorf("error writing response: %v", err)
}
}
func metricsDisallowed(w http.ResponseWriter, req *http.Request) {
log.Warning("attempt to access metrics endpoint from external address ", req.RemoteAddr)
http.NotFound(w, req)
}
|