package mtlsproxy import ( "context" "crypto/tls" "errors" "fmt" "io" "net" "sync" "time" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig" ) type Config struct { ListenAddress string TargetAddress string CAPath string CertificatePath string PrivateKeyPath string AllowedClientURI string ALPNProtocols []string DialTimeout time.Duration } func Run(ctx context.Context, config Config) error { if config.ListenAddress == "" || config.TargetAddress == "" || config.DialTimeout <= 0 { return errors.New("invalid mTLS proxy configuration") } tlsConfiguration, err := tlsconfig.LoadServer(tlsconfig.ServerConfig{ CAPath: config.CAPath, CertificatePath: config.CertificatePath, PrivateKeyPath: config.PrivateKeyPath, AllowedClientURI: config.AllowedClientURI, }) if err != nil { return err } tlsConfiguration.NextProtos = config.ALPNProtocols listener, err := net.Listen("tcp", config.ListenAddress) if err != nil { return fmt.Errorf("listen: %w", err) } defer func() { _ = listener.Close() }() go func() { <-ctx.Done() _ = listener.Close() }() var connections sync.WaitGroup defer connections.Wait() for { connection, err := listener.Accept() if err != nil { if ctx.Err() != nil { return nil } return fmt.Errorf("accept: %w", err) } connections.Add(1) go func() { defer connections.Done() serve(ctx, connection, config, tlsConfiguration) }() } } func serve(ctx context.Context, connection net.Conn, config Config, tlsConfiguration *tls.Config) { client := tls.Server(connection, tlsConfiguration) defer func() { _ = client.Close() }() handshakeCtx, cancel := context.WithTimeout(ctx, config.DialTimeout) defer cancel() if err := client.HandshakeContext(handshakeCtx); err != nil { return } target, err := (&net.Dialer{Timeout: config.DialTimeout}).DialContext(ctx, "tcp", config.TargetAddress) if err != nil { return } defer func() { _ = target.Close() }() result := make(chan struct{}, 2) copyConnection := func(destination, source net.Conn) { _, _ = io.Copy(destination, source) if writer, ok := destination.(interface{ CloseWrite() error }); ok { _ = writer.CloseWrite() } result <- struct{}{} } go copyConnection(target, client) go copyConnection(client, target) select { case <-ctx.Done(): case <-result: } }