mirror of
https://github.com/bingohuang/docker-labs.git
synced 2025-07-16 03:07:26 +08:00
Add TLS certificates for machine drivers (#73)
This commit is contained in:
parent
93740dc9f5
commit
dea778440e
@ -33,7 +33,7 @@ WORKDIR /root
|
|||||||
# Remove IPv6 alias for localhost and start docker in the background ...
|
# Remove IPv6 alias for localhost and start docker in the background ...
|
||||||
CMD cat /etc/hosts >/etc/hosts.bak && \
|
CMD cat /etc/hosts >/etc/hosts.bak && \
|
||||||
sed 's/^::1.*//' /etc/hosts.bak > /etc/hosts && \
|
sed 's/^::1.*//' /etc/hosts.bak > /etc/hosts && \
|
||||||
dockerd -g /graph --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 \
|
dockerd --experimental -g /graph --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 \
|
||||||
--storage-driver=$DOCKER_STORAGE_DRIVER &>/docker.log & \
|
--storage-driver=$DOCKER_STORAGE_DRIVER &>/docker.log & \
|
||||||
while true ; do /bin/bash ; done
|
while true ; do /bin/bash ; done
|
||||||
# ... and then put a shell in the foreground, restarting it if it exits
|
# ... and then put a shell in the foreground, restarting it if it exits
|
||||||
|
81
api.go
81
api.go
@ -1,9 +1,12 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"flag"
|
"flag"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -17,8 +20,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var portNumber int
|
var sslPortNumber, portNumber int
|
||||||
|
var key, cert string
|
||||||
flag.IntVar(&portNumber, "port", 3000, "Give a TCP port to run the application")
|
flag.IntVar(&portNumber, "port", 3000, "Give a TCP port to run the application")
|
||||||
|
flag.IntVar(&sslPortNumber, "sslPort", 3001, "Give a SSL TCP port")
|
||||||
|
flag.StringVar(&key, "key", "./pwd/server-key.pem", "Server key for SSL")
|
||||||
|
flag.StringVar(&cert, "cert", "./pwd/server.pem", "Give a SSL cert")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
bypassCaptcha := len(os.Getenv("GOOGLE_RECAPTCHA_DISABLED")) > 0
|
bypassCaptcha := len(os.Getenv("GOOGLE_RECAPTCHA_DISABLED")) > 0
|
||||||
@ -36,14 +43,31 @@ func main() {
|
|||||||
|
|
||||||
// Reverse proxy (needs to be the first route, to make sure it is the first thing we check)
|
// Reverse proxy (needs to be the first route, to make sure it is the first thing we check)
|
||||||
proxyHandler := handlers.NewMultipleHostReverseProxy()
|
proxyHandler := handlers.NewMultipleHostReverseProxy()
|
||||||
|
|
||||||
|
// Specific routes
|
||||||
r.Host(`{node:ip[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}}-{port:[0-9]*}.{tld:.*}`).Handler(proxyHandler)
|
r.Host(`{node:ip[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}}-{port:[0-9]*}.{tld:.*}`).Handler(proxyHandler)
|
||||||
r.Host(`{node:ip[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}}.{tld:.*}`).Handler(proxyHandler)
|
r.Host(`{node:ip[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}}.{tld:.*}`).Handler(proxyHandler)
|
||||||
|
r.HandleFunc("/ping", handlers.Ping).Methods("GET")
|
||||||
|
r.HandleFunc("/sessions/{sessionId}", handlers.GetSession).Methods("GET")
|
||||||
|
r.HandleFunc("/sessions/{sessionId}/instances", handlers.NewInstance).Methods("POST")
|
||||||
|
r.HandleFunc("/sessions/{sessionId}/instances/{instanceName}", handlers.DeleteInstance).Methods("DELETE")
|
||||||
|
r.HandleFunc("/sessions/{sessionId}/instances/{instanceName}/keys", handlers.SetKeys).Methods("POST")
|
||||||
|
|
||||||
r.StrictSlash(false)
|
h := func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.ServeFile(w, r, "./www/index.html")
|
||||||
|
}
|
||||||
|
|
||||||
r.HandleFunc("/ping", http.HandlerFunc(handlers.Ping)).Methods("GET")
|
r.HandleFunc("/p/{sessionId}", h).Methods("GET")
|
||||||
|
r.PathPrefix("/assets").Handler(http.FileServer(http.Dir("./www")))
|
||||||
|
r.HandleFunc("/robots.txt", func(rw http.ResponseWriter, r *http.Request) {
|
||||||
|
http.ServeFile(rw, r, "www/robots.txt")
|
||||||
|
})
|
||||||
|
|
||||||
r.HandleFunc("/", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
r.Handle("/sessions/{sessionId}/ws/", server)
|
||||||
|
r.Handle("/metrics", promhttp.Handler())
|
||||||
|
|
||||||
|
// Generic routes
|
||||||
|
r.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
|
||||||
if bypassCaptcha {
|
if bypassCaptcha {
|
||||||
http.ServeFile(rw, r, "./www/bypass.html")
|
http.ServeFile(rw, r, "./www/bypass.html")
|
||||||
} else {
|
} else {
|
||||||
@ -53,31 +77,38 @@ func main() {
|
|||||||
}
|
}
|
||||||
rw.Write(welcome)
|
rw.Write(welcome)
|
||||||
}
|
}
|
||||||
})).Methods("GET")
|
}).Methods("GET")
|
||||||
|
|
||||||
r.HandleFunc("/", http.HandlerFunc(handlers.NewSession)).Methods("POST")
|
r.HandleFunc("/", handlers.NewSession).Methods("POST")
|
||||||
|
|
||||||
r.HandleFunc("/sessions/{sessionId}", http.HandlerFunc(handlers.GetSession)).Methods("GET")
|
|
||||||
r.HandleFunc("/sessions/{sessionId}/instances", http.HandlerFunc(handlers.NewInstance)).Methods("POST")
|
|
||||||
r.HandleFunc("/sessions/{sessionId}/instances/{instanceName}", http.HandlerFunc(handlers.DeleteInstance)).Methods("DELETE")
|
|
||||||
|
|
||||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
http.ServeFile(w, r, "./www/index.html")
|
|
||||||
})
|
|
||||||
|
|
||||||
r.HandleFunc("/p/{sessionId}", h).Methods("GET")
|
|
||||||
r.PathPrefix("/assets").Handler(http.FileServer(http.Dir("./www")))
|
|
||||||
r.HandleFunc("/robots.txt", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
|
||||||
http.ServeFile(rw, r, "www/robots.txt")
|
|
||||||
}))
|
|
||||||
|
|
||||||
r.Handle("/sessions/{sessionId}/ws/", server)
|
|
||||||
r.Handle("/metrics", promhttp.Handler())
|
|
||||||
|
|
||||||
n := negroni.Classic()
|
n := negroni.Classic()
|
||||||
n.UseHandler(r)
|
n.UseHandler(r)
|
||||||
|
|
||||||
log.Println("Listening on port " + strconv.Itoa(portNumber))
|
go func() {
|
||||||
log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(portNumber), n))
|
log.Println("Listening on port " + strconv.Itoa(portNumber))
|
||||||
|
log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(portNumber), n))
|
||||||
|
}()
|
||||||
|
|
||||||
|
ssl := mux.NewRouter()
|
||||||
|
sslProxyHandler := handlers.NewSSLDaemonHandler()
|
||||||
|
ssl.Host(`{node:ip[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}_[0-9]{1,3}}-2375.{tld:.*}`).Handler(sslProxyHandler)
|
||||||
|
log.Println("Listening TLS on port " + strconv.Itoa(sslPortNumber))
|
||||||
|
|
||||||
|
s := &http.Server{Addr: "0.0.0.0:" + strconv.Itoa(sslPortNumber), Handler: ssl}
|
||||||
|
s.TLSConfig = &tls.Config{}
|
||||||
|
s.TLSConfig.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||||
|
|
||||||
|
chunks := strings.Split(clientHello.ServerName, ".")
|
||||||
|
chunks = strings.Split(chunks[0], "-")
|
||||||
|
ip := strings.Replace(strings.TrimPrefix(chunks[0], "ip"), "_", ".", -1)
|
||||||
|
i := services.FindInstanceByIP(ip)
|
||||||
|
if i == nil {
|
||||||
|
return nil, fmt.Errorf("Instance %s doesn't exist", clientHello.ServerName)
|
||||||
|
}
|
||||||
|
if i.GetCertificate() == nil {
|
||||||
|
return nil, fmt.Errorf("Instance %s doesn't have a certificate", clientHello.ServerName)
|
||||||
|
}
|
||||||
|
return i.GetCertificate(), nil
|
||||||
|
}
|
||||||
|
log.Fatal(s.ListenAndServeTLS("", ""))
|
||||||
}
|
}
|
||||||
|
@ -10,6 +10,7 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
# app exposes port 3000
|
# app exposes port 3000
|
||||||
- "3000:3000"
|
- "3000:3000"
|
||||||
|
- "3001:3001"
|
||||||
volumes:
|
volumes:
|
||||||
# since this app creates networks and launches containers, we need to talk to docker daemon
|
# since this app creates networks and launches containers, we need to talk to docker daemon
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
@ -37,3 +37,27 @@ func NewMultipleHostReverseProxy() *httputil.ReverseProxy {
|
|||||||
|
|
||||||
return &httputil.ReverseProxy{Director: director}
|
return &httputil.ReverseProxy{Director: director}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewSSLDaemonHandler() *httputil.ReverseProxy {
|
||||||
|
director := func(req *http.Request) {
|
||||||
|
v := mux.Vars(req)
|
||||||
|
node := v["node"]
|
||||||
|
if strings.HasPrefix(node, "ip") {
|
||||||
|
// Node is actually an ip, need to convert underscores by dots.
|
||||||
|
ip := strings.Replace(strings.TrimPrefix(node, "ip"), "_", ".", -1)
|
||||||
|
|
||||||
|
if net.ParseIP(ip) == nil {
|
||||||
|
// Not a valid IP, so treat this is a hostname.
|
||||||
|
} else {
|
||||||
|
node = ip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only proxy http for now
|
||||||
|
req.URL.Scheme = "http"
|
||||||
|
|
||||||
|
req.URL.Host = fmt.Sprintf("%s:%s", node, "2375")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &httputil.ReverseProxy{Director: director}
|
||||||
|
}
|
||||||
|
43
handlers/set_keys.go
Normal file
43
handlers/set_keys.go
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/franela/play-with-docker/services"
|
||||||
|
"github.com/gorilla/mux"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetKeys(rw http.ResponseWriter, req *http.Request) {
|
||||||
|
vars := mux.Vars(req)
|
||||||
|
sessionId := vars["sessionId"]
|
||||||
|
instanceName := vars["instanceName"]
|
||||||
|
|
||||||
|
type certs struct {
|
||||||
|
ServerCert []byte `json:"server_cert"`
|
||||||
|
ServerKey []byte `json:"server_key"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var c certs
|
||||||
|
jsonErr := json.NewDecoder(req.Body).Decode(&c)
|
||||||
|
if jsonErr != nil {
|
||||||
|
log.Println(jsonErr)
|
||||||
|
rw.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s := services.GetSession(sessionId)
|
||||||
|
s.Lock()
|
||||||
|
defer s.Unlock()
|
||||||
|
i := services.GetInstance(s, instanceName)
|
||||||
|
|
||||||
|
_, err := i.SetCertificate(c.ServerCert, c.ServerKey)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
rw.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("Set keys for instance %s\n", instanceName)
|
||||||
|
}
|
@ -180,7 +180,6 @@ func ResizeConnection(name string, cols, rows uint) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func CreateInstance(session *Session, dindImage string) (*Instance, error) {
|
func CreateInstance(session *Session, dindImage string) (*Instance, error) {
|
||||||
|
|
||||||
h := &container.HostConfig{NetworkMode: container.NetworkMode(session.Id), Privileged: true}
|
h := &container.HostConfig{NetworkMode: container.NetworkMode(session.Id), Privileged: true}
|
||||||
h.Resources.PidsLimit = int64(500)
|
h.Resources.PidsLimit = int64(500)
|
||||||
h.Resources.Memory = 4092 * Megabyte
|
h.Resources.Memory = 4092 * Megabyte
|
||||||
|
@ -2,6 +2,7 @@ package services
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
@ -29,6 +30,9 @@ type Instance struct {
|
|||||||
Cpu string `json:"cpu"`
|
Cpu string `json:"cpu"`
|
||||||
Ports []uint16 `json:"ports"`
|
Ports []uint16 `json:"ports"`
|
||||||
tempPorts []uint16 `json:"-"`
|
tempPorts []uint16 `json:"-"`
|
||||||
|
ServerCert []byte `json:"server_cert"`
|
||||||
|
ServerKey []byte `json:"server_key"`
|
||||||
|
cert *tls.Certificate `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *Instance) setUsedPort(port uint16) {
|
func (i *Instance) setUsedPort(port uint16) {
|
||||||
@ -43,6 +47,25 @@ func (i *Instance) setUsedPort(port uint16) {
|
|||||||
i.tempPorts = append(i.tempPorts, port)
|
i.tempPorts = append(i.tempPorts, port)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (i *Instance) SetCertificate(cert, key []byte) (*tls.Certificate, error) {
|
||||||
|
i.ServerCert = cert
|
||||||
|
i.ServerKey = key
|
||||||
|
c, e := tls.X509KeyPair(i.ServerCert, i.ServerKey)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
i.cert = &c
|
||||||
|
|
||||||
|
// We store sessions as soon as we set instance keys
|
||||||
|
if err := saveSessionsToDisk(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return i.cert, nil
|
||||||
|
}
|
||||||
|
func (i *Instance) GetCertificate() *tls.Certificate {
|
||||||
|
return i.cert
|
||||||
|
}
|
||||||
|
|
||||||
func (i *Instance) IsConnected() bool {
|
func (i *Instance) IsConnected() bool {
|
||||||
return i.conn != nil
|
return i.conn != nil
|
||||||
|
|
||||||
@ -131,6 +154,18 @@ func (i *Instance) Attach() {
|
|||||||
func GetInstance(session *Session, name string) *Instance {
|
func GetInstance(session *Session, name string) *Instance {
|
||||||
return session.Instances[name]
|
return session.Instances[name]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func FindInstanceByIP(ip string) *Instance {
|
||||||
|
for _, s := range sessions {
|
||||||
|
for _, i := range s.Instances {
|
||||||
|
if i.IP == ip {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func DeleteInstance(session *Session, instance *Instance) error {
|
func DeleteInstance(session *Session, instance *Instance) error {
|
||||||
if instance.conn != nil {
|
if instance.conn != nil {
|
||||||
instance.conn.Close()
|
instance.conn.Close()
|
||||||
|
@ -304,6 +304,14 @@ func LoadSessionsFromDisk() error {
|
|||||||
for _, i := range s.Instances {
|
for _, i := range s.Instances {
|
||||||
// wire the session back to the instance
|
// wire the session back to the instance
|
||||||
i.session = s
|
i.session = s
|
||||||
|
|
||||||
|
if i.ServerCert != nil && i.ServerKey != nil {
|
||||||
|
_, err := i.SetCertificate(i.ServerCert, i.ServerKey)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Connect PWD daemon to the new network
|
// Connect PWD daemon to the new network
|
||||||
|
Loading…
x
Reference in New Issue
Block a user