k3s/pkg/server/router.go

304 lines
8.4 KiB
Go
Raw Normal View History

2019-01-01 08:23:01 +00:00
package server
import (
2019-05-29 18:53:51 +00:00
"crypto"
2019-04-19 18:20:34 +00:00
"crypto/x509"
2019-05-29 18:53:51 +00:00
"encoding/csv"
"errors"
"fmt"
2019-05-29 18:53:51 +00:00
"io"
2019-04-19 18:20:34 +00:00
"io/ioutil"
"net"
2019-01-01 08:23:01 +00:00
"net/http"
"os"
"path/filepath"
2019-01-26 04:56:12 +00:00
"strconv"
"strings"
2019-01-01 08:23:01 +00:00
"github.com/gorilla/mux"
2019-05-09 22:05:51 +00:00
certutil "github.com/rancher/dynamiclistener/cert"
2019-01-09 16:54:15 +00:00
"github.com/rancher/k3s/pkg/daemons/config"
2019-05-29 18:53:51 +00:00
"github.com/rancher/k3s/pkg/daemons/control"
2019-01-26 04:56:12 +00:00
"github.com/rancher/k3s/pkg/openapi"
2019-04-19 18:20:34 +00:00
"github.com/sirupsen/logrus"
2019-01-09 16:54:15 +00:00
"k8s.io/apimachinery/pkg/util/json"
2019-01-01 08:23:01 +00:00
)
2019-01-26 04:56:12 +00:00
const (
jsonMediaType = "application/json"
binaryMediaType = "application/octet-stream"
pbMediaType = "application/com.github.proto-openapi.spec.v2@v1.0+protobuf"
openapiPrefix = "openapi."
staticURL = "/static/"
2019-01-26 04:56:12 +00:00
)
2019-01-01 08:23:01 +00:00
type CACertsGetter func() (string, error)
func router(serverConfig *config.Control, tunnel http.Handler, cacertsGetter CACertsGetter) http.Handler {
authed := mux.NewRouter()
authed.Use(authMiddleware(serverConfig))
authed.NotFoundHandler = serverConfig.Runtime.Handler
authed.Path("/v1-k3s/connect").Handler(tunnel)
2019-05-29 18:53:51 +00:00
authed.Path("/v1-k3s/serving-kubelet.crt").Handler(servingKubeletCert(serverConfig))
authed.Path("/v1-k3s/serving-kubelet.key").Handler(fileHandler(serverConfig.Runtime.ServingKubeletKey))
authed.Path("/v1-k3s/client-kubelet.crt").Handler(clientKubeletCert(serverConfig))
authed.Path("/v1-k3s/client-kubelet.key").Handler(fileHandler(serverConfig.Runtime.ClientKubeletKey))
authed.Path("/v1-k3s/client-kube-proxy.crt").Handler(fileHandler(serverConfig.Runtime.ClientKubeProxyCert))
authed.Path("/v1-k3s/client-kube-proxy.key").Handler(fileHandler(serverConfig.Runtime.ClientKubeProxyKey))
authed.Path("/v1-k3s/client-ca.crt").Handler(fileHandler(serverConfig.Runtime.ClientCA))
authed.Path("/v1-k3s/server-ca.crt").Handler(fileHandler(serverConfig.Runtime.ServerCA))
2019-01-01 08:23:01 +00:00
authed.Path("/v1-k3s/config").Handler(configHandler(serverConfig))
staticDir := filepath.Join(serverConfig.DataDir, "static")
2019-01-01 08:23:01 +00:00
router := mux.NewRouter()
router.NotFoundHandler = authed
router.PathPrefix(staticURL).Handler(serveStatic(staticURL, staticDir))
2019-01-01 08:23:01 +00:00
router.Path("/cacerts").Handler(cacerts(cacertsGetter))
2019-01-26 04:56:12 +00:00
router.Path("/openapi/v2").Handler(serveOpenapi())
2019-01-31 22:42:27 +00:00
router.Path("/ping").Handler(ping())
2019-01-01 08:23:01 +00:00
return router
}
func cacerts(getter CACertsGetter) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
content, err := getter()
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(err.Error()))
}
resp.Header().Set("content-type", "text/plain")
resp.Write([]byte(content))
})
}
2019-05-29 18:53:51 +00:00
func getNodeInfo(req *http.Request) (string, string, error) {
nodeNames := req.Header["K3s-Node-Name"]
if len(nodeNames) != 1 || nodeNames[0] == "" {
return "", "", errors.New("node name not set")
}
nodePasswords := req.Header["K3s-Node-Password"]
if len(nodePasswords) != 1 || nodePasswords[0] == "" {
return "", "", errors.New("node password not set")
}
2019-06-25 17:42:15 +00:00
return strings.ToLower(nodeNames[0]), nodePasswords[0], nil
2019-05-29 18:53:51 +00:00
}
func getCACertAndKeys(caCertFile, caKeyFile, signingKeyFile string) ([]*x509.Certificate, crypto.Signer, crypto.Signer, error) {
keyBytes, err := ioutil.ReadFile(signingKeyFile)
if err != nil {
return nil, nil, nil, err
}
key, err := certutil.ParsePrivateKeyPEM(keyBytes)
if err != nil {
return nil, nil, nil, err
}
caKeyBytes, err := ioutil.ReadFile(caKeyFile)
if err != nil {
return nil, nil, nil, err
}
caKey, err := certutil.ParsePrivateKeyPEM(caKeyBytes)
if err != nil {
return nil, nil, nil, err
}
caBytes, err := ioutil.ReadFile(caCertFile)
if err != nil {
return nil, nil, nil, err
}
caCert, err := certutil.ParseCertsPEM(caBytes)
if err != nil {
return nil, nil, nil, err
}
return caCert, caKey.(crypto.Signer), key.(crypto.Signer), nil
}
func servingKubeletCert(server *config.Control) http.Handler {
2019-01-01 08:23:01 +00:00
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if req.TLS == nil {
resp.WriteHeader(http.StatusNotFound)
return
}
2019-04-19 18:20:34 +00:00
2019-05-29 18:53:51 +00:00
nodeName, nodePassword, err := getNodeInfo(req)
if err != nil {
sendError(err, resp)
2019-07-30 22:44:34 +00:00
return
}
2019-06-25 17:42:15 +00:00
if err := ensureNodePassword(server.Runtime.NodePasswdFile, nodeName, nodePassword); err != nil {
sendError(err, resp, http.StatusForbidden)
return
2019-04-19 18:20:34 +00:00
}
2019-05-29 18:53:51 +00:00
caCert, caKey, key, err := getCACertAndKeys(server.Runtime.ServerCA, server.Runtime.ServerCAKey, server.Runtime.ServingKubeletKey)
2019-04-19 18:20:34 +00:00
if err != nil {
sendError(err, resp)
return
}
2019-05-29 18:53:51 +00:00
cert, err := certutil.NewSignedCert(certutil.Config{
CommonName: nodeName,
Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
AltNames: certutil.AltNames{
DNSNames: []string{nodeName, "localhost"},
IPs: []net.IP{net.ParseIP("127.0.0.1")},
},
}, key, caCert[0], caKey)
2019-04-19 18:20:34 +00:00
if err != nil {
sendError(err, resp)
return
}
2019-05-29 18:53:51 +00:00
resp.Write(append(certutil.EncodeCertPEM(cert), certutil.EncodeCertPEM(caCert[0])...))
})
}
2019-04-19 18:20:34 +00:00
2019-05-29 18:53:51 +00:00
func clientKubeletCert(server *config.Control) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if req.TLS == nil {
resp.WriteHeader(http.StatusNotFound)
2019-04-19 18:20:34 +00:00
return
}
2019-05-29 18:53:51 +00:00
nodeName, nodePassword, err := getNodeInfo(req)
2019-04-19 18:20:34 +00:00
if err != nil {
sendError(err, resp)
2019-07-30 22:44:34 +00:00
return
2019-04-19 18:20:34 +00:00
}
2019-06-25 17:42:15 +00:00
if err := ensureNodePassword(server.Runtime.NodePasswdFile, nodeName, nodePassword); err != nil {
2019-05-29 18:53:51 +00:00
sendError(err, resp, http.StatusForbidden)
2019-04-19 18:20:34 +00:00
return
}
2019-05-29 18:53:51 +00:00
caCert, caKey, key, err := getCACertAndKeys(server.Runtime.ClientCA, server.Runtime.ClientCAKey, server.Runtime.ClientKubeletKey)
2019-04-19 18:20:34 +00:00
if err != nil {
sendError(err, resp)
return
}
2019-05-29 18:53:51 +00:00
cert, err := certutil.NewSignedCert(certutil.Config{
CommonName: "system:node:" + nodeName,
Organization: []string{"system:nodes"},
Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}, key, caCert[0], caKey)
2019-04-19 18:20:34 +00:00
if err != nil {
sendError(err, resp)
return
}
resp.Write(append(certutil.EncodeCertPEM(cert), certutil.EncodeCertPEM(caCert[0])...))
2019-01-01 08:23:01 +00:00
})
}
2019-05-29 18:53:51 +00:00
func fileHandler(fileName string) http.Handler {
2019-01-01 08:23:01 +00:00
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if req.TLS == nil {
resp.WriteHeader(http.StatusNotFound)
return
}
2019-05-29 18:53:51 +00:00
http.ServeFile(resp, req, fileName)
2019-01-01 08:23:01 +00:00
})
}
func configHandler(server *config.Control) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if req.TLS == nil {
resp.WriteHeader(http.StatusNotFound)
return
}
resp.Header().Set("content-type", "application/json")
json.NewEncoder(resp).Encode(server)
})
}
2019-01-26 04:56:12 +00:00
func serveOpenapi() http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
suffix := "json"
contentType := jsonMediaType
if req.Header.Get("Accept") == pbMediaType {
suffix = "pb"
contentType = binaryMediaType
}
data, err := openapi.Asset(openapiPrefix + suffix)
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(err.Error()))
return
}
resp.Header().Set("Content-Type", contentType)
resp.Header().Set("Content-Length", strconv.Itoa(len(data)))
resp.Write(data)
})
}
2019-01-31 22:42:27 +00:00
func ping() http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
data := []byte("pong")
resp.Header().Set("Content-Type", "text/plain")
resp.Header().Set("Content-Length", strconv.Itoa(len(data)))
resp.Write(data)
})
}
func serveStatic(urlPrefix, staticDir string) http.Handler {
return http.StripPrefix(urlPrefix, http.FileServer(http.Dir(staticDir)))
}
2019-04-19 18:20:34 +00:00
func sendError(err error, resp http.ResponseWriter, status ...int) {
code := http.StatusInternalServerError
if len(status) == 1 {
code = status[0]
}
2019-04-19 18:20:34 +00:00
logrus.Error(err)
resp.WriteHeader(code)
2019-04-19 18:20:34 +00:00
resp.Write([]byte(err.Error()))
}
func ensureNodePassword(passwdFile, nodeName, passwd string) error {
2019-05-29 18:53:51 +00:00
records := [][]string{}
2019-06-25 17:42:15 +00:00
if _, err := os.Stat(passwdFile); !os.IsNotExist(err) {
f, err := os.Open(passwdFile)
2019-05-29 18:53:51 +00:00
if err != nil {
return err
}
2019-06-25 17:42:15 +00:00
defer f.Close()
reader := csv.NewReader(f)
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
return err
}
if len(record) < 2 {
return fmt.Errorf("password file '%s' must have at least 2 columns (password, nodeName), found %d", passwdFile, len(record))
}
if record[1] == nodeName {
if record[0] == passwd {
return nil
}
return fmt.Errorf("Node password validation failed for '%s', using passwd file '%s'", nodeName, passwdFile)
}
2019-06-25 17:42:15 +00:00
records = append(records, record)
}
2019-06-25 17:42:15 +00:00
f.Close()
}
2019-06-25 17:42:15 +00:00
records = append(records, []string{passwd, nodeName})
2019-05-29 18:53:51 +00:00
return control.WritePasswords(passwdFile, records)
}