Skip to content

Commit

Permalink
Merge pull request #1 from convox/protocol-labels
Browse files Browse the repository at this point in the history
proxy https and tls inbound and proxy protocol outbound
  • Loading branch information
ddollar committed Apr 20, 2016
2 parents 65a30c7 + 22a2e42 commit e5dbd79
Showing 1 changed file with 66 additions and 11 deletions.
77 changes: 66 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
package main

import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"os"
"strings"
Expand All @@ -24,13 +31,31 @@ func main() {
from := os.Args[1]
to := os.Args[2]
protocol := os.Args[3]
proxy := false

if len(os.Args) > 4 && os.Args[4] == "proxy" {
proxy = true
}

ln, err := net.Listen("tcp", fmt.Sprintf(":%s", from))

if err != nil {
die(err)
}

switch protocol {
case "https", "tls":
cert, err := generateSelfSignedCertificate("convox.local")

if err != nil {
die(err)
}

ln = tls.NewListener(ln, &tls.Config{
Certificates: []tls.Certificate{cert},
})
}

defer ln.Close()

fmt.Printf("listen %s\n", from)
Expand All @@ -42,23 +67,14 @@ func main() {
die(err)
}

switch protocol {
case "http":
go handleHttpConnection(conn, to)
case "proxy":
if proxy {
go handleProxyConnection(conn, to)
case "tcp":
} else {
go handleTcpConnection(conn, to)
default:
die(fmt.Errorf("unknown protocol: %s", protocol))
}
}
}

func handleHttpConnection(in net.Conn, to string) {
handleTcpConnection(in, to)
}

func handleProxyConnection(in net.Conn, to string) {
rp := strings.SplitN(in.RemoteAddr().String(), ":", 2)
top := strings.SplitN(to, ":", 2)
Expand Down Expand Up @@ -106,3 +122,42 @@ func copyWait(to io.Writer, from io.Reader, wg *sync.WaitGroup) {
defer wg.Done()
io.Copy(to, from)
}

func generateSelfSignedCertificate(host string) (tls.Certificate, error) {
rkey, err := rsa.GenerateKey(rand.Reader, 2048)

if err != nil {
return tls.Certificate{}, err
}

serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))

if err != nil {
return tls.Certificate{}, err
}

template := x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
CommonName: host,
Organization: []string{"convox"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: []string{host},
}

data, err := x509.CreateCertificate(rand.Reader, &template, &template, &rkey.PublicKey, rkey)

if err != nil {
return tls.Certificate{}, err
}

pub := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: data})
key := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rkey)})

return tls.X509KeyPair(pub, key)
}

0 comments on commit e5dbd79

Please sign in to comment.