From e6adac12ada2d57e07f88dbdeb4f0b190723e708 Mon Sep 17 00:00:00 2001 From: Jeroen van der Heijden Date: Mon, 4 Dec 2023 09:24:35 +0100 Subject: [PATCH] Initial commit --- .github/FUNDING.yml | 1 + .github/workflows/ci.yml | 23 +++++ .github/workflows/deploy.yml | 47 ++++++++++ .github/workflows/release.yml | 48 ++++++++++ .gitignore | 5 ++ Dockerfile | 32 +++++++ LICENSE | 21 +++++ README.md | 57 ++++++++++++ go.mod | 3 + go.sum | 0 tlsproxy.go | 164 ++++++++++++++++++++++++++++++++++ version.go | 4 + 12 files changed, 405 insertions(+) create mode 100644 .github/FUNDING.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/deploy.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 tlsproxy.go create mode 100644 version.go diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..4518086 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: cesbit diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c72a491 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: '1.21' + cache: false + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + version: latest \ No newline at end of file diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..568cb8c --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,47 @@ +name: Deploy + +on: + push: + tags: + - "v*-*" # v1.2.3-alpha0 etc. + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + build-and-push-image: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Log in to the Container registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v4 + with: + images: ${{ env.REGISTRY }}/cesbit/tlsproxy + + - name: Get the version + id: get_version + run: echo "VERSION=$(echo $GITHUB_REF | cut -d / -f 3)" >> $GITHUB_OUTPUT + + - name: Build and push Docker image + uses: docker/build-push-action@v3 + with: + context: . + push: true + file: Dockerfile + tags: ghcr.io/cesbit/tlsproxy:${{ steps.get_version.outputs.VERSION }} + labels: ${{ steps.meta.outputs.labels }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..a7a56fa --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,48 @@ +name: Release + +on: + push: + tags: + - "v*" + - "!v*-*" # v1.2.3-alphd0 + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + build-and-push-image: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Log in to the Container registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v4 + with: + images: ${{ env.REGISTRY }}/cesbit/tlsproxy + + - name: Get the version + id: get_version + run: echo "VERSION=$(echo $GITHUB_REF | cut -d / -f 3)" >> $GITHUB_OUTPUT + + - name: Build and push Docker image + uses: docker/build-push-action@v3 + with: + context: . + push: true + file: Dockerfile + tags: ghcr.io/cesbit/tlsproxy:${{ steps.get_version.outputs.VERSION }},ghcr.io/cesbit/tlsproxy:latest + labels: ${{ steps.meta.outputs.labels }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0b3233d --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Test build +tlsproxy + +# Certificates +certificates/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b9427a7 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,32 @@ +# syntax=docker/dockerfile:1 + +FROM golang:1.21 + +# Set destination for COPY +WORKDIR /app + +# Download Go modules +COPY go.mod go.sum ./ +RUN go mod download + +# Copy the source code. Note the slash at the end, as explained in +# https://docs.docker.com/engine/reference/builder/#copy +COPY *.go ./ + +# Build +RUN CGO_ENABLED=0 GOOS=linux go build -o /tlsproxy + +# Expose (accept client connections) +EXPOSE 443 +EXPOSE 8000 + +ENV TLSPROXY_TARGET "localhost" +ENV TLSPROXY_PORTS "443:80,8000" +ENV TLSPROXY_CERT_FILE "certificates/server.crt" +ENV TLSPROXY_KEY_FILE "certificates/server.key" + +VOLUME "/certificates" + +# Run +WORKDIR / +CMD ["/tlsproxy"] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e55e6c8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Cesbit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..920a770 --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +[![CI](https://github.com/cesbit/tlsproxy/workflows/CI/badge.svg)](https://github.com/cesbit/tlsproxy/actions) +[![Release Version](https://img.shields.io/github/release/cesbit/tlsproxy)](https://github.com/cesbit/tlsproxy/releases) + +# TLS Proxy + +## Installation + +Just clone the project and make a build + +``` +git clone git@github.com:cesbit/tlsproxy.git +cd tlsproxy +go build +``` + +## Example usage + +The following assumes a server.crt and server.key and will forward 443->80 and 8000->8000 to just-a-host.local + +``` +TLSPROXY_TARGET=just-a-host.local \ +TLSPROXY_PORTS=443:80,8000 \ +TLSPROXY_CERT_FILE=server.crt \ +TLSPROXY_KEY_FILE=server.key \ +tlsproxy +``` + +## Environment variable + +Environment | Description +----------------------- | ----------- +`TLSPROXY_TARGET` | Address of the host. +`TLSPROXY_PORTS` | Specify the ports you want to secure with TLS. You can list multiple ports separated by commas. Use the following syntax: `:` _(example `443:80`)_. If the outside and inside ports are the same, you can simply specify the port number _(example `8000`)_. +`TLSPROXY_CERT_FILE` | Path to the certificate file _(example `/certs/server.crt`)_. +`TLSPROXY_KEY_FILE` | Path to the key file _(example `/certs/server.key`)_. +`TLSPROXY_DEBUG` | A value of `1` or `enable` will enable debug logging. +## Certificates + +For testing, one can create certificates using the following commands: + +Generate private key (.key) +Key considerations for algorithm "RSA" ≥ 2048-bit +``` +openssl genrsa -out server.key 2048 +``` +Key considerations for algorithm "ECDSA" (X25519 || ≥ secp384r1) +https://safecurves.cr.yp.to/ +List ECDSA the supported curves (openssl ecparam -list_curves) +``` +openssl ecparam -genkey -name secp384r1 -out server.key +``` +Generation of self-signed(x509) public key (PEM-encodings .pem|.crt) based on the private (.key) +``` +openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650 +``` + + diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..9f355d4 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/cesbit/tlsproxy + +go 1.21.4 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/tlsproxy.go b/tlsproxy.go new file mode 100644 index 0000000..192b9d9 --- /dev/null +++ b/tlsproxy.go @@ -0,0 +1,164 @@ +// Generate private key (.key) +// Key considerations for algorithm "RSA" ≥ 2048-bit +// +// openssl genrsa -out server.key 2048 +// +// Key considerations for algorithm "ECDSA" (X25519 || ≥ secp384r1) +// https://safecurves.cr.yp.to/ +// List ECDSA the supported curves (openssl ecparam -list_curves) +// +// openssl ecparam -genkey -name secp384r1 -out server.key +// +// Generation of self-signed(x509) public key (PEM-encodings .pem|.crt) based on the private (.key) +// +// openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650 +package main + +import ( + "bufio" + "crypto/tls" + "fmt" + "io" + "log" + "net" + "os" + "os/signal" + "path/filepath" + "regexp" + "strconv" + "strings" + "syscall" +) + +var targetAddress string +var printDebug bool + +func copyConn(reader io.Reader, writer io.Writer, done chan bool) { + buffer := make([]byte, 512) + r := bufio.NewReader(reader) + + for { + n, err := r.Read(buffer) + if err != nil { + if err != io.EOF && printDebug { + log.Printf("Read error: %v", err) + } + break + } + + if n > 0 { + _, err = writer.Write(buffer[0:n]) + if err != nil && printDebug { + log.Printf("Write error: %v", err) + break + } + } + } + done <- true +} + +func handleConnection(clientConn net.Conn, targetPort int) { + if printDebug { + log.Printf("Handle new connection %v", clientConn.RemoteAddr()) + } + defer clientConn.Close() + + target := fmt.Sprintf("%s:%d", targetAddress, targetPort) + targetConn, err := net.Dial("tcp", target) + if err != nil { + log.Printf("Failed to connect to %s: %v", target, err) + return + } + defer targetConn.Close() + done := make(chan bool, 1) + + go copyConn(clientConn, targetConn, done) + go copyConn(targetConn, clientConn, done) + + <-done + if printDebug { + log.Printf("Closed connection %v", clientConn.RemoteAddr()) + } +} + +func startSocket(clientPort int, targetPort int, config *tls.Config) { + ln, err := tls.Listen("tcp", fmt.Sprintf(":%d", clientPort), config) + if err != nil { + log.Fatal("ListenAndServeSocket", err) + } + defer ln.Close() + + for { + conn, err := ln.Accept() + if err != nil { + log.Println(err) + continue + } + go handleConnection(conn, targetPort) + } +} + +func main() { + log.Printf("TLS proxy version %s", Version) + + debugEnv := strings.ToLower(os.Getenv("TLSPROXY_DEBUG")) + + printDebug = debugEnv == "1" || debugEnv == "true" || debugEnv == "enable" || debugEnv == "on" + + targetEnv := os.Getenv("TLSPROXY_TARGET") + if targetEnv == "" { + log.Fatal("Error: missing or empty TLSPROXY_TARGET env var\n") + } + targetAddress = targetEnv + + portsEnv := os.Getenv("TLSPROXY_PORTS") + if portsEnv == "" { + log.Fatal("Error: missing or empty TLSPROXY_PORTS env var\n") + } + + certFileEnv := os.Getenv("TLSPROXY_CERT_FILE") + if certFileEnv == "" { + certFileEnv = filepath.Join("certificates", "server.crt") + log.Printf("Missing or empty TLSPROXY_CERT_FILE, using '%s' as default value", certFileEnv) + } + + keyFileEnv := os.Getenv("TLSPROXY_KEY_FILE") + if keyFileEnv == "" { + keyFileEnv = filepath.Join("certificates", "server.key") + log.Printf("Missing or empty TLSPROXY_KEY_FILE, using '%s' as default value", keyFileEnv) + } + + cert, err := tls.LoadX509KeyPair(certFileEnv, keyFileEnv) + if err != nil { + log.Fatal("LoadingCertKeyPair", err) + } + + config := &tls.Config{Certificates: []tls.Certificate{cert}} + + r := regexp.MustCompile(`([0-9]+)(:([0-9]+))?`) + match := r.FindAllStringSubmatch(portsEnv, -1) + + // Loop over all matches and start listeners for each one + for _, m := range match { + if m[3] == "" { + port, _ := strconv.Atoi(m[1]) + go startSocket(port, port, config) + } else { + clientPort, _ := strconv.Atoi(m[1]) + targetPort, _ := strconv.Atoi(m[3]) + go startSocket(clientPort, targetPort, config) + } + } + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) + done := make(chan bool, 1) + + go func() { + sig := <-sigs + log.Printf("Quit (%v)", sig) + done <- true + }() + + <-done +} diff --git a/version.go b/version.go new file mode 100644 index 0000000..3f298f1 --- /dev/null +++ b/version.go @@ -0,0 +1,4 @@ +package main + +// Version exposes the TLS Proxy version +const Version = "0.1.2"