srptls

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2026 License: BSD-3-Clause Imports: 23 Imported by: 2

README

go-tls-srp

Package srptls is a TLS 1.2 server that signs clients in with SRP, the Secure Remote Password key exchange of RFC 5054. A client proves that it knows a password. The server stores only a verifier derived from that password and needs no certificate.

Go's crypto/tls has no SRP. This module is a trimmed copy of crypto/tls from Go 1.27.2, cut down to the server side of the SRP handshake. It exists for devices that already authenticate with TLS-SRP, for example EST clients built on libest or OpenSSL.

What it supports

  • Server only, TLS 1.2 only. A client that offers only TLS 1.0 or 1.1 gets a protocol_version alert. SRP has no TLS 1.3 cipher suites.
  • Cipher suites TLS_SRP_SHA_WITH_AES_256_CBC_SHA and TLS_SRP_SHA_WITH_AES_128_CBC_SHA, in that order by default. TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA is used only when listed in Config.CipherSuites. The suites that also sign with a server certificate are not implemented.
  • All seven groups of RFC 5054, Appendix A, from 1024 to 8192 bits. The package offers no other groups. OpenSSL clients refuse other groups by default.
  • Extended Master Secret (RFC 7627) when the client offers it. ConnectionState.ExportKeyingMaterial works only on such connections.
  • Secure renegotiation indication (RFC 5746). Renegotiation itself is refused.
  • SNI is reported in ConnectionState.ServerName. The tls-unique channel binding is in ConnectionState.TLSUnique.

Not included: the client side, TLS 1.3, session resumption and tickets, certificates, ALPN, encrypt-then-MAC, QUIC and ECH.

Usage

Config.GetVerifier returns the stored verifier for the username in the ClientHello:

config := &srptls.Config{
	GetVerifier: func(info *srptls.ClientHelloInfo) (*srptls.Verifier, error) {
		if v, ok := store[info.Username]; ok {
			return v, nil
		}
		return srptls.SimulatedVerifier(seed, group, []byte(info.Username)), nil
	},
}
l, err := srptls.Listen("tcp", ":8443", config)

NewVerifier creates a verifier from a username, a password and a salt from NewSalt. A verifier exported by OpenSSL, such as an srpvfile entry, can be used directly. Decode its salt and verifier to big-endian bytes without leading zeros and pick the group with GroupByBits or GroupByParameters.

For an unknown username, return either a SimulatedVerifier or ErrUnknownUsername:

  • With SimulatedVerifier, the handshake fails exactly like a wrong password, with a bad_record_mac alert. The client cannot tell whether the username exists. Use the same seed on every server instance and keep it across restarts. Otherwise a client can spot an unknown username by its salt changing.
  • With ErrUnknownUsername, the server sends an unknown_psk_identity alert, which reveals that the username does not exist.

To refuse a client before the costly SRP computation, for example one over a rate limit, return ErrAccessDenied or an error that wraps it. The client gets an access_denied alert.

With net/http

net/http only fills Request.TLS for crypto/tls connections, so it stays nil here. Store the connection with http.Server.ConnContext and read ConnectionState from it in the handler. The handshake runs on the first read of the connection, so ReadHeaderTimeout also limits how long it may take. See Example_httpServer in example_test.go.

Errors

A wrong password, or an unknown user with a simulated verifier, fails the handshake with an error that wraps ErrWrongPassword. The client gets a bad_record_mac alert. Conn.Handshake returns the same error again after a failed handshake. An alert from the client is a *net.OpError with Op set to "remote error". A refused unknown username returns ErrUnknownUsername and a refusal from GetVerifier the error it returned. Other handshake errors describe the cause in their text.

Security notes

  • SRP in TLS uses SHA-1 for the SRP values, as RFC 5054 requires, and CBC with HMAC-SHA1 for the records. The CBC code keeps the partial Lucky13 countermeasures of crypto/tls.
  • The server's big-number arithmetic uses filippo.io/bigmod, the constant-time modular arithmetic of the Go standard library exported as a module.
  • After GetVerifier returns, a simulated verifier costs the server the same work as a real one. The time of the lookup itself is up to the caller.
  • To limit password guessing, count a failed sign-in when the handshake error wraps ErrWrongPassword and check the count in GetVerifier, returning ErrAccessDenied once it is used up.

Tested clients

  • OpenSSL 1.1.1k s_client and curl 7.61.1 on Rocky Linux 8.
  • libssl 3.5.9 and 4.0.3 through the SRP API (SSL_CTX_set_srp_username and SSL_CTX_set_srp_password).

openssl s_client from OpenSSL 3.0 onward ignores -srppass and uses a wrong password (openssl/openssl#32565). Test with OpenSSL 1.1.1, curl or a program that calls libssl directly.

Following Go releases

Commit b52d68c holds crypto/tls from Go 1.27.2 unchanged. The kept files are alert.go, cipher_suites.go, common.go, conn.go, handshake_messages.go, handshake_server.go, prf.go and tls.go. The SRP code is in srp.go and groups_rfc5054.go.

To pick up fixes from a newer Go release, compare its crypto/tls with Go 1.27.2 for those files and port the changes that affect the TLS 1.2 server, the CBC record layer or the handshake message parsing:

git diff --no-index "$(go1.27.2 env GOROOT)/src/crypto/tls/conn.go" "$(go env GOROOT)/src/crypto/tls/conn.go"

Releases

CHANGELOG.md has one section per version. Before tagging, run the release check on main:

VERSION=v0.1.0 make release-check

It tests an export of HEAD and imports it from a separate module, so it catches files that are untracked or only present locally. A release starts when a version tag reachable from main is pushed:

git tag -s v0.1.0 -m 'v0.1.0'
git push origin main v0.1.0

The release workflow repeats the check on the tag, builds source archives, an SBOM and checksums, attests their provenance and creates a draft release with the changelog section as its description. Review the draft and publish it. Do not draft a release in the GitHub UI. That creates the tag and the workflow refuses to rebuild a published release.

Licence

BSD-3-Clause, the licence of the Go project. See LICENSE.

Documentation

Overview

Package srptls is a TLS 1.2 server that authenticates clients with SRP, the Secure Remote Password key exchange of RFC 5054. It is a trimmed copy of Go's crypto/tls that serves the SRP cipher suites without certificates. It has no client side, no TLS 1.3, no session resumption, no renegotiation and no certificate authentication.

Example (HttpServer)

Example_httpServer serves HTTPS over TLS-SRP. net/http leaves Request.TLS nil for connections that are not crypto/tls, so the handler reads the connection state from the request context instead.

package main

import (
	"context"
	"crypto/rand"
	"fmt"
	"log"
	"net"
	"net/http"
	"time"

	srptls "github.com/misiektoja/go-tls-srp"
)

type connKey struct{}

// Example_httpServer serves HTTPS over TLS-SRP. net/http leaves Request.TLS
// nil for connections that are not crypto/tls, so the handler reads the
// connection state from the request context instead.
func main() {
	group, err := srptls.GroupByBits(3072)
	if err != nil {
		log.Fatal(err)
	}
	salt, err := srptls.NewSalt(rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	stored, err := srptls.NewVerifier(group, []byte("device-1"), []byte("secret"), salt)
	if err != nil {
		log.Fatal(err)
	}
	// The seed must stay the same across restarts and replicas.
	seed := []byte("load this from configuration")

	config := &srptls.Config{
		GetVerifier: func(info *srptls.ClientHelloInfo) (*srptls.Verifier, error) {
			if info.Username == "device-1" {
				return stored, nil
			}
			return srptls.SimulatedVerifier(seed, group, []byte(info.Username)), nil
		},
	}
	l, err := srptls.Listen("tcp", "127.0.0.1:0", config)
	if err != nil {
		log.Fatal(err)
	}
	srv := &http.Server{
		// The handshake runs in the first read, so this also bounds it.
		ReadHeaderTimeout: 10 * time.Second,
		ConnContext: func(ctx context.Context, c net.Conn) context.Context {
			return context.WithValue(ctx, connKey{}, c)
		},
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			state := r.Context().Value(connKey{}).(*srptls.Conn).ConnectionState()
			fmt.Fprintf(w, "hello %s\n", state.SRPUsername)
		}),
	}
	go srv.Serve(l)
	defer srv.Close()
}

Index

Examples

Constants

View Source
const (
	TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc01a
	TLS_SRP_SHA_WITH_AES_128_CBC_SHA  uint16 = 0xc01d
	TLS_SRP_SHA_WITH_AES_256_CBC_SHA  uint16 = 0xc020
)

SRP cipher suite IDs from RFC 5054, Section 2.7. The suites that also sign with a server certificate are not implemented.

View Source
const (
	VersionTLS10 = 0x0301
	VersionTLS11 = 0x0302
	VersionTLS12 = 0x0303
)

Variables

View Source
var ErrAccessDenied = errors.New("srptls: access denied")

ErrAccessDenied may be returned by Config.GetVerifier, also wrapped, to refuse a client, for example one over a rate limit. The server then aborts the handshake with an access_denied alert before it does the costly SRP computation.

View Source
var ErrUnknownUsername = errors.New("srptls: unknown SRP username")

ErrUnknownUsername may be returned by Config.GetVerifier. The server then aborts the handshake with an unknown_psk_identity alert, which tells the client that the username does not exist. Return a SimulatedVerifier instead to hide which usernames exist.

View Source
var ErrWrongPassword = errors.New("srptls: wrong SRP password")

ErrWrongPassword is wrapped by the handshake error when the client's Finished message does not decrypt or does not verify. With SRP that means the client used another password than the verifier was made from, or the username is unknown and a simulated verifier answered. An attacker who alters the client's records on the way causes the same error.

Functions

func CipherSuiteName

func CipherSuiteName(id uint16) string

CipherSuiteName returns the standard name for the passed cipher suite ID, or a hexadecimal fallback if the suite is not one of this package's.

func Listen

func Listen(network, laddr string, config *Config) (net.Listener, error)

Listen creates a TLS listener accepting connections on the given network address using net.Listen. The configuration must be non-nil and must set GetVerifier.

func NewListener

func NewListener(inner net.Listener, config *Config) net.Listener

NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server. The configuration must be non-nil and must set GetVerifier.

func NewSalt

func NewSalt(rand io.Reader) ([]byte, error)

NewSalt returns a random salt of 20 bytes without a leading zero byte. OpenSSL clients treat the salt as a number and drop leading zeros, so such a salt would give them another x.

Types

type ClientHelloInfo

type ClientHelloInfo struct {
	// Username is the SRP username from the ClientHello, as sent. It is
	// between 1 and 255 bytes and may not be valid UTF-8.
	Username string

	// ServerName indicates the name of the server requested by the client.
	// It is only set if the client is using SNI.
	ServerName string

	// CipherSuites lists the cipher suites offered by the client.
	CipherSuites []uint16

	// Conn is the underlying net.Conn for the connection. Do not read
	// from, or write to, this connection; that will cause the TLS
	// connection to fail.
	Conn net.Conn
	// contains filtered or unexported fields
}

ClientHelloInfo contains information from a ClientHello message to guide the GetVerifier callback.

func (*ClientHelloInfo) Context

func (c *ClientHelloInfo) Context() context.Context

Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.

type Config

type Config struct {
	// GetVerifier returns the SRP verifier for the username in the
	// ClientHello. It is required. Any error other than ErrUnknownUsername
	// and ErrAccessDenied aborts the handshake with an internal_error alert.
	GetVerifier func(*ClientHelloInfo) (*Verifier, error)

	// CipherSuites is the server's preference order of SRP cipher suites.
	// The server picks the first one the client offers. If nil, the server
	// uses TLS_SRP_SHA_WITH_AES_256_CBC_SHA and then
	// TLS_SRP_SHA_WITH_AES_128_CBC_SHA. TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA is
	// used only when listed here.
	CipherSuites []uint16

	// Rand provides the source of entropy for nonces and the server's SRP
	// private value. If Rand is nil, the server uses crypto/rand.
	Rand io.Reader

	// KeyLogWriter optionally specifies a destination for TLS master secrets
	// in NSS key log format that can be used to allow external programs
	// such as Wireshark to decrypt TLS connections.
	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
	// Use of KeyLogWriter compromises security and should only be
	// used for debugging.
	KeyLogWriter io.Writer
}

A Config structure is used to configure a TLS-SRP server. After one has been passed to a TLS function it must not be modified. A Config may be reused.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

A Conn represents a secured connection. It implements the net.Conn interface.

func Server

func Server(conn net.Conn, config *Config) *Conn

Server returns a new TLS-SRP server side connection using conn as the underlying transport. The configuration must be non-nil and must set GetVerifier.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) CloseWrite

func (c *Conn) CloseWrite() error

CloseWrite shuts down the writing side of the connection. It should only be called once the handshake has completed and does not call CloseWrite on the underlying connection. Most callers should just use Conn.Close.

func (*Conn) ConnectionState

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns basic TLS details about the connection.

The returned ConnectionState is only meaningful after the handshake has completed, as reported by ConnectionState.HandshakeComplete; before then its fields are not populated. The handshake is run automatically by the first Conn.Read or Conn.Write, or it can be triggered explicitly with Conn.Handshake.

func (*Conn) Handshake

func (c *Conn) Handshake() error

Handshake runs the server handshake if it has not yet been run.

Most uses of this package need not call Handshake explicitly: the first Conn.Read or Conn.Write will call it automatically.

For control over canceling or setting a timeout on a handshake, use Conn.HandshakeContext.

func (*Conn) HandshakeContext

func (c *Conn) HandshakeContext(ctx context.Context) error

HandshakeContext runs the server handshake if it has not yet been run.

The provided Context must be non-nil. If the context is canceled before the handshake is complete, the handshake is interrupted and an error is returned. Once the handshake has completed, cancellation of the context will not affect the connection.

Most uses of this package need not call HandshakeContext explicitly: the first Conn.Read or Conn.Write will call it automatically.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Conn) NetConn

func (c *Conn) NetConn() net.Conn

NetConn returns the underlying connection that is wrapped by c. Note that writing to or reading from this connection directly will corrupt the TLS session.

func (*Conn) Read

func (c *Conn) Read(b []byte) (int, error)

Read reads data from the connection.

As Read calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Conn.Write before Read is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Conn.Read and Conn.Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Conn.Read will not time out.

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means Conn.Write will not time out. After a Conn.Write has timed out, the TLS state is corrupt and all future writes will return the same error.

func (*Conn) Write

func (c *Conn) Write(b []byte) (int, error)

Write writes data to the connection.

As Write calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Conn.Read and Write before Write is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.

type ConnectionState

type ConnectionState struct {
	// Version is the TLS version used by the connection. It is always VersionTLS12.
	Version uint16

	// HandshakeComplete is true if the handshake has concluded.
	HandshakeComplete bool

	// CipherSuite is the cipher suite negotiated for the connection, such as
	// TLS_SRP_SHA_WITH_AES_256_CBC_SHA.
	CipherSuite uint16

	// ServerName is the value of the Server Name Indication extension sent by
	// the client.
	ServerName string

	// SRPUsername is the username the client proved it holds the password of.
	SRPUsername string

	// ExtendedMasterSecret is true if the client and server used the extended
	// master secret of RFC 7627.
	ExtendedMasterSecret bool

	// TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
	// Section 3). It is the client's Finished message because every handshake
	// is a full handshake.
	TLSUnique []byte
	// contains filtered or unexported fields
}

ConnectionState records basic TLS details about the connection.

func (*ConnectionState) ExportKeyingMaterial

func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)

ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in RFC 5705. If context is nil, it is not used as part of the seed. It returns an error unless the connection used Extended Master Secret.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group is one of the seven SRP groups of RFC 5054 Appendix A. OpenSSL clients accept only these groups, so the package offers no way to define another one.

func GroupByBits

func GroupByBits(bits int) (*Group, error)

GroupByBits returns the RFC 5054 group with a prime of the given size, such as 1536 or 3072.

func GroupByParameters

func GroupByParameters(n, g []byte) (*Group, error)

GroupByParameters returns the RFC 5054 group whose prime and generator match. Leading zero bytes are ignored, so values from any encoding of the numbers match.

func (*Group) Bits

func (g *Group) Bits() int

Bits returns the size of the group's prime in bits.

func (*Group) Generator

func (g *Group) Generator() []byte

Generator returns a copy of the group's generator in big-endian bytes.

func (*Group) N

func (g *Group) N() []byte

N returns a copy of the group's prime in big-endian bytes.

type RecordHeaderError

type RecordHeaderError struct {
	// Msg contains a human readable string that describes the error.
	Msg string
	// RecordHeader contains the five bytes of TLS record header that
	// triggered the error.
	RecordHeader [5]byte
	// Conn provides the underlying net.Conn in the case that a client
	// sent an initial handshake that didn't look like TLS.
	// It is nil if there's already been a handshake or a TLS alert has
	// been written to the connection.
	Conn net.Conn
}

RecordHeaderError is returned when a TLS record header is invalid.

func (RecordHeaderError) Error

func (e RecordHeaderError) Error() string

Error returns the error description.

type Verifier

type Verifier struct {
	Group *Group
	// Salt is sent to the client exactly as stored. OpenSSL computes x from the salt as a number,
	// so a salt imported from an OpenSSL srpv file must not keep a leading zero byte.
	Salt []byte
	// Value is v in big-endian bytes, with or without leading zeros.
	Value []byte
}

Verifier is the stored SRP record of one username: the group, the salt and the verifier v = g^x mod N. The server needs no password.

func NewVerifier

func NewVerifier(group *Group, username, password, salt []byte) (*Verifier, error)

NewVerifier computes the verifier of a username and password with RFC 5054 Section 2.4: x = SHA1(s | SHA1(I | ":" | P)) and v = g^x mod N. The bytes are hashed as given, without SASLprep, as OpenSSL does.

func SimulatedVerifier

func SimulatedVerifier(seed []byte, group *Group, username []byte) *Verifier

SimulatedVerifier returns a verifier for a username the server does not know, as RFC 5054 Section 2.5.1.3 suggests. The same seed and username always give the same salt, and the handshake fails like a wrong password. The verifier is a pseudo-random number below N rather than g^x, because the client never sees it and an exponentiation would make unknown usernames slower than known ones. Every server that answers the same clients must use the same seed.

func (*Verifier) Validate

func (v *Verifier) Validate() error

Validate checks the limits RFC 5054 and the group place on a verifier.

Notes

Bugs

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL