Skip to content

Instantly share code, notes, and snippets.

@iamshreeram
Created April 28, 2025 00:40
Show Gist options
  • Save iamshreeram/9994c84b26aafc84e12d313c3ba87517 to your computer and use it in GitHub Desktop.
Save iamshreeram/9994c84b26aafc84e12d313c3ba87517 to your computer and use it in GitHub Desktop.
plain tcp proxy for db
package main
import (
"io"
"log"
"net"
"sync"
"github.com/denisenkom/go-mssqldb/msdsn"
)
// Configuration
const (
proxyListenAddr = ":1434" // Default MSSQL port
targetDBAddr = "localhost" // Without port
targetDBPort = 1433
dbUser = "sa"
dbPassword = "SomeRandPass123"
dbName = "master"
)
func main() {
// Start listening for incoming MSSQL connections
listener, err := net.Listen("tcp", proxyListenAddr)
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
defer listener.Close()
log.Printf("MSSQL proxy server listening on %s", proxyListenAddr)
for {
// Accept incoming client connections
clientConn, err := listener.Accept()
if err != nil {
log.Printf("Error accepting connection: %v", err)
continue
}
// Handle each connection in a separate goroutine
go handleClientConnection(clientConn)
}
}
func handleClientConnection(clientConn net.Conn) {
defer clientConn.Close()
// Create connection config (not used directly but kept for reference)
_ = msdsn.Config{
Host: targetDBAddr,
Port: targetDBPort,
User: dbUser,
Password: dbPassword,
Database: dbName,
Encryption: msdsn.EncryptionDisabled, // Adjust as needed
}
// Connect to the target MSSQL server
targetConn, err := net.Dial("tcp", net.JoinHostPort(targetDBAddr, "1433"))
if err != nil {
log.Printf("Failed to connect to target DB: %v", err)
return
}
defer targetConn.Close()
log.Printf("Proxy established connection from %s to %s",
clientConn.RemoteAddr(), targetConn.RemoteAddr())
// Use wait groups to wait for both directions to complete
var wg sync.WaitGroup
wg.Add(2)
// Forward data from client to DB server
go func() {
defer wg.Done()
_, err := io.Copy(targetConn, clientConn)
if err != nil {
log.Printf("Client->DB copy error: %v", err)
}
}()
// Forward data from DB server to client
go func() {
defer wg.Done()
_, err := io.Copy(clientConn, targetConn)
if err != nil {
log.Printf("DB->Client copy error: %v", err)
}
}()
// Wait for both directions to complete
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment