Vladislav Yarmak 1 year ago
parent
commit
c89ed84e98
6 changed files with 261 additions and 22 deletions
  1. 48 22
      cmd/dtlspipe/main.go
  2. 7 0
      go.mod
  3. 54 0
      go.sum
  4. 28 0
      server/config.go
  5. 94 0
      server/server.go
  6. 30 0
      util/util.go

+ 48 - 22
cmd/dtlspipe/main.go

@@ -10,18 +10,21 @@ import (
 	"strings"
 	"syscall"
 	"time"
+
+	"github.com/Snawoot/dtlspipe/util"
 )
 
 const (
 	ProgName = "dtlspipe"
+	PSKEnvVarKey = "DTLSPIPE_PSK"
 )
-
 var (
 	version = "undefined"
 
 	timeout   = flag.Duration("timeout", 10*time.Second, "network operation timeout")
 	idleTime  = flag.Duration("idle-time", 90*time.Second, "max idle time for UDP session")
-	passwdOpt = flag.String("password", "", "password used to derive PSK key")
+	pskHexOpt = flag.String("psk", "", "hex-encoded pre-shared key. Can be generated with `genpsk` subcommand")
+	keyLength = flag.Uint("key-length", 16, "generate key with specified length")
 )
 
 func usage() {
@@ -30,19 +33,35 @@ func usage() {
 	fmt.Fprintln(out)
 	fmt.Fprintf(out, "%s [OPTION]... server <BIND ADDRESS> <REMOTE ADDRESS>\n", ProgName)
 	fmt.Fprintf(out, "%s [OPTION]... client <BIND ADDRESS> <REMOTE ADDRESS>\n", ProgName)
+	fmt.Fprintf(out, "%s [OPTION]... genpsk\n", ProgName)
 	fmt.Fprintf(out, "%s version\n", ProgName)
 	fmt.Fprintln(out)
 	fmt.Fprintln(out, "Options:")
 	flag.PrintDefaults()
 }
 
+func cmdGenPSK() int {
+	if *keyLength > 64 {
+		fmt.Fprintln(os.Stderr, "key length is too big")
+		return 1
+	}
+	psk, err := util.GenPSKHex(int(*keyLength))
+	if err != nil {
+		fmt.Fprintf(os.Stderr, "key generation error: %v\n", err)
+		return 1
+	}
+
+	fmt.Println(psk)
+	return 0
+}
+
 func cmdVersion() int {
 	fmt.Println(version)
 	return 0
 }
 
-func cmdClient(bindAddress, remoteAddress, password string) int {
-	log.Printf("starting dtlspipe client: %s => %s", bindAddress, remoteAddress)
+func cmdClient(bindAddress, remoteAddress string, psk []byte) int {
+	log.Printf("starting dtlspipe client: %s =[wrap into DTLS]=> %s", bindAddress, remoteAddress)
 	defer log.Println("dtlspipe client stopped")
 
 	appCtx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
@@ -53,8 +72,8 @@ func cmdClient(bindAddress, remoteAddress, password string) int {
 	return 0
 }
 
-func cmdServer(bindAddress, remoteAddress, password string) int {
-	log.Printf("starting dtlspipe server: %s => %s", bindAddress, remoteAddress)
+func cmdServer(bindAddress, remoteAddress string, psk []byte) int {
+	log.Printf("starting dtlspipe server: %s =[unwrap from DTLS]=> %s", bindAddress, remoteAddress)
 	defer log.Println("dtlspipe server stopped")
 
 	appCtx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
@@ -69,32 +88,39 @@ func run() int {
 	flag.Parse()
 	args := flag.Args()
 
-	passwd := os.Getenv("PSK_PASSWD")
-	if passwd == "" {
-		os.Unsetenv("PSK_PASSWD")
-	}
-	if *passwdOpt != "" {
-		passwd = *passwdOpt
-	}
-	if passwd == "" {
-		fmt.Fprintln(os.Stderr)
-		fmt.Fprintln(os.Stderr, "Error: no password option provided and neither PSK_PASSWD environment variable is set")
-		fmt.Fprintln(os.Stderr)
-		return 2
-	}
-
 	switch len(args) {
 	case 1:
 		switch args[0] {
+		case "genpsk":
+			return cmdGenPSK()
 		case "version":
 			return cmdVersion()
 		}
 	case 3:
+		pskHex := os.Getenv(PSKEnvVarKey)
+		if pskHex == "" {
+			os.Unsetenv(PSKEnvVarKey)
+		}
+		if *pskHexOpt != "" {
+			pskHex = *pskHexOpt
+		}
+		if pskHex == "" {
+			fmt.Fprintln(os.Stderr)
+			fmt.Fprintf(os.Stderr, "Error: no PSK option provided and neither %s environment variable is set\n", PSKEnvVarKey)
+			fmt.Fprintln(os.Stderr)
+			return 2
+		}
+
+		psk, err := util.PSKFromHex(pskHex)
+		if err != nil {
+			fmt.Fprintf(os.Stderr, "Error: can't hex-decode PSK: %v\n", err)
+			return 2
+		}
 		switch args[0] {
 		case "server":
-			return cmdServer(args[1], args[2], passwd)
+			return cmdServer(args[1], args[2], psk)
 		case "client":
-			return cmdServer(args[1], args[2], passwd)
+			return cmdClient(args[1], args[2], psk)
 		}
 	}
 	usage()

+ 7 - 0
go.mod

@@ -1,3 +1,10 @@
 module github.com/Snawoot/dtlspipe
 
 go 1.21.0
+
+require (
+	github.com/pion/dtls/v2 v2.2.7 // indirect
+	github.com/pion/logging v0.2.2 // indirect
+	github.com/pion/transport/v2 v2.2.1 // indirect
+	golang.org/x/crypto v0.8.0 // indirect
+)

+ 54 - 0
go.sum

@@ -0,0 +1,54 @@
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8=
+github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s=
+github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
+github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
+github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N7c=
+github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ=
+golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

+ 28 - 0
server/config.go

@@ -0,0 +1,28 @@
+package server
+
+import (
+	"context"
+	"time"
+)
+
+type Config struct {
+	BindAddress   string
+	RemoteAddress string
+	Password      string
+	Timeout       time.Duration
+	IdleTimeout   time.Duration
+	BaseContext   context.Context
+}
+
+func (cfg *Config) populateDefaults() *Config {
+	newCfg := new(Config)
+	*newCfg = *cfg
+	cfg = newCfg
+	if cfg.BaseContext == nil {
+		cfg.BaseContext = context.Background()
+	}
+	if cfg.IdleTimeout == 0 {
+		cfg.IdleTimeout = 90 * time.Second
+	}
+	return cfg
+}

+ 94 - 0
server/server.go

@@ -0,0 +1,94 @@
+package server
+
+import (
+	"context"
+	"fmt"
+	"log"
+	"net"
+	"net/netip"
+	"time"
+
+	"github.com/pion/dtls/v2"
+)
+
+type Server struct {
+	listener    net.Listener
+	rAddr       string
+	psk         []byte
+	timeout     time.Duration
+	idleTimeout time.Duration
+	baseCtx     context.Context
+	cancelCtx   func()
+}
+
+func New(cfg *Config) (*Server, error) {
+	cfg = cfg.populateDefaults()
+
+	baseCtx, cancelCtx := context.WithCancel(cfg.BaseContext)
+
+	srv := &Server{
+		rAddr:       cfg.RemoteAddress,
+		psk:         []byte(cfg.Password), // TODO: key derivation
+		timeout:     cfg.Timeout,
+		idleTimeout: cfg.IdleTimeout,
+		baseCtx:     baseCtx,
+		cancelCtx:   cancelCtx,
+	}
+
+	lAddrPort, err := netip.ParseAddrPort(cfg.BindAddress)
+	if err != nil {
+		cancelCtx()
+		return nil, fmt.Errorf("can't parse bind address: %w", err)
+	}
+
+	dtlsConfig := &dtls.Config{
+		CipherSuites: []dtls.CipherSuiteID{
+			dtls.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
+			dtls.TLS_PSK_WITH_AES_128_CCM,
+			dtls.TLS_PSK_WITH_AES_128_CCM_8,
+			dtls.TLS_PSK_WITH_AES_256_CCM_8,
+			dtls.TLS_PSK_WITH_AES_128_GCM_SHA256,
+			dtls.TLS_PSK_WITH_AES_128_CBC_SHA256,
+		},
+		ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
+		ConnectContextMaker:  srv.contextMaker,
+		PSK: func(hint []byte) ([]byte, error) {
+			return []byte(cfg.Password), nil
+		},
+	}
+	listener, err := dtls.Listen("udp", net.UDPAddrFromAddrPort(lAddrPort), dtlsConfig)
+	if err != nil {
+		cancelCtx()
+		return nil, fmt.Errorf("server listen failed: %w", err)
+	}
+
+	srv.listener = listener
+
+	return srv, nil
+}
+
+func (srv *Server) listen() {
+	for srv.baseCtx.Err() == nil {
+		conn, err := srv.listener.Accept()
+		if err != nil {
+			log.Printf("conn accept failed: %v", err)
+			return
+		}
+
+		go srv.serve(conn)
+	}
+}
+
+func (srv *Server) serve(conn net.Conn) {
+	defer conn.Close()
+	conn.Write([]byte("Hello, World!"))
+}
+
+func (srv *Server) contextMaker() (context.Context, func()) {
+	return context.WithTimeout(srv.baseCtx, srv.timeout)
+}
+
+func (srv *Server) Close() error {
+	srv.cancelCtx()
+	return srv.listener.Close()
+}

+ 30 - 0
util/util.go

@@ -0,0 +1,30 @@
+package util
+
+import (
+	"crypto/rand"
+	"encoding/hex"
+	"fmt"
+)
+
+func GenPSK(length int) ([]byte, error) {
+	b := make([]byte, length)
+	_, err := rand.Read(b)
+	if err != nil {
+		return nil, fmt.Errorf("random bytes generation failed: %w", err)
+	}
+
+	return b, nil
+}
+
+func GenPSKHex(length int) (string, error) {
+	b, err := GenPSK(length)
+	if err != nil {
+		return "", fmt.Errorf("can't generate hex key: %w", err)
+	}
+
+	return hex.EncodeToString(b), nil
+}
+
+func PSKFromHex(input string) ([]byte, error) {
+	return hex.DecodeString(input)
+}