http_signature_auth

package module
v0.0.0-...-fb58307 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2024 License: Apache-2.0 Imports: 20 Imported by: 0

README

http-signature-auth-go

Implements https://www.ietf.org/archive/id/draft-ietf-httpbis-unprompted-auth-05.html HTTP1.1, HTTP/2 and HTTP/3 servers can place their resources behind HTTP Signature authentication by using the HTTP handler provided by this library. This is currently only for interop purpose and not production use yet.

Examples

Server: Serving an HTTP URL behind Signature Authentication

keysDB := http_signature_auth.NewKeysDatabase()
var keys []crypto.PublicKey = ...
for i := range keys {
    keysDB.AddKey(keyIDs[i], keys[i])
}
mux := http.NewServeMux()
handler := http_signature_auth.NewSignatureAuthHandler(keysDB, func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
})
mux.Handle("/my-protected-resource", handler)
server := http.Server{
    TLSConfig: tlsConfig,
    Addr:      *bindAddr,
    Handler:   mux,
}
log.Info().Msgf("Start HTTPS over TLS on %s", *bindAddr)
go func() {
    err = server.ListenAndServeTLS("", "")
    if err != nil {
        log.Fatal().Msgf("cannot listen and serve TLS: %s", err)
    }
}()
log.Info().Msgf("Start HTTPS over QUIC on %s", *bindAddr)
quicServer := http3.Server{
    TLSConfig: tlsConfig,
    Addr:      *bindAddr,
    Handler:   mux,
}
err = quicServer.ListenAndServe()

Client: Accessing a resource through HTTP/3 using Signature Auth (using quic-go)

request, err := http.NewRequest("GET", "https://example.org", nil)
if err != nil {
    log.Fatal().Msgf("could not build request from URL: %s", err)
}

var signer *rsa.PrivateKey = ... // also works with ecdsa and ed25519

// we must set NextProtos to "h3" to enable HTTP/3
tlsConf := &tls.Config{
    NextProtos: []string{http3.NextProtoH3}
}
// establish a QUIC connection
log.Debug().Msgf("Establish QUIC connection to %s:%s", request.URL.Hostname(), port)
qConn, err := quic.DialAddr(context.Background(), request.Host, &tlsConf, nil)
if err != nil {
    log.Fatal().Msgf("could establish QUIC connection: %s", err)
}

tlsConnState := qConn.ConnectionState().TLS

roundTripper := &http3.RoundTripper{
    Dial: func(ctx context.Context, addr string, tlsConf *tls.Config, quicConf *quic.Config) (quic.EarlyConnection, error) {
        return qConn.(quic.EarlyConnection), nil
    },
}


signature, err := http_signature_auth.NewSignatureForRequest(&tlsConnState, request, http_signature_auth.KeyID(keyID[:]), signer, signatureScheme)
if err != nil {
    log.Fatal().Msgf("could not generate signature for request: %s", err)
}

authHeaderValue, err := signature.SignatureAuthorizationHeader()
if err != nil {
    log.Fatal().Msgf("could not generate signature authorization header: %s", err)
}

request.Header.Set("Authorization", authHeaderValue)
response, err := roundTripper.RoundTrip(request)
log.Debug().Msgf("negotiated protocol is %s", connState.NegotiatedProtocol)
if err != nil {
    log.Fatal().Msgf("could not perform request: %s", err)
}
defer response.Body.Close()
fmt.Println("Got response", response.Status)
bodyContent, err := io.ReadAll(response.Body)
if err != nil {
    log.Error().Msgf("Could not read body content")
}
if bodyContent != nil {
    fmt.Println("Body:")
    fmt.Println(string(bodyContent))
}

Documentation

Overview

handler.go

Index

Constants

This section is empty.

Variables

View Source
var SIGNATURE_HEADER = append(SIGNATURE_HEADER_PART_1[:], []byte("HTTP Signature Authentication\x00")...)
View Source
var SIGNATURE_HEADER_PART_1 [64]byte = [64]byte{
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
	0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
}

Functions

func GetHash

func GetHash(scheme tls.SignatureScheme) (crypto.Hash, error)

func GetPortFromRequest

func GetPortFromRequest(r *http.Request, httpScheme string) (uint16, error)

func IsPubkeySupported

func IsPubkeySupported(key crypto.PublicKey) bool

func NewSignatureAuthHandler

func NewSignatureAuthHandler(keysDB *Keys, handlerFunc http.HandlerFunc) http.HandlerFunc

func ParseAndValidateSignatureScheme

func ParseAndValidateSignatureScheme(schemeStr string) (tls.SignatureScheme, error)

ParseAndValidateSignatureScheme parses the given string into a tls.SignatureScheme and ensures it only corresponds to a supported signature scheme such as the ones defined in https://www.ietf.org/archive/id/draft-ietf-httpbis-unprompted-auth-05.html

func ParsePublicKey

func ParsePublicKey(keyBase64 string, signatureScheme tls.SignatureScheme) (crypto.PublicKey, error)

func ParseUncompressedPoint

func ParseUncompressedPoint(uncompressedPoint []byte, scheme tls.SignatureScheme) (*ecdsa.PublicKey, error)

ParseUncompressedPoint parses the given public key in uncompressed point format (cf RFC8446 Section 4.2.8.2) into an ECDSA public key

func PrepareTLSExporterInput

func PrepareTLSExporterInput(signatureScheme tls.SignatureScheme, keyID KeyID, pubKey crypto.PublicKey, httpScheme string, httpHost string, httpPort uint16, httpRealm string) (out []byte, err error)

func SerializePublicKey

func SerializePublicKey(out []byte, pubkey crypto.PublicKey) ([]byte, error)

func SerializeUncompressedPoint

func SerializeUncompressedPoint(out []byte, pubkey *ecdsa.PublicKey) ([]byte, error)

ParseUncompressedPoint parses the given public key in uncompressed point format (cf RFC8446 Section 4.2.8.2) into an ECDSA public key

func VerifySignature

func VerifySignature(keysDB *Keys, r *http.Request) (bool, error)

func VerifySignatureWithMaterial

func VerifySignatureWithMaterial(keysDB *Keys, signatureCandidate *Signature, material *TLSExporterMaterial) (bool, error)

Types

type InvalidPublicKeyFormat

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

func (InvalidPublicKeyFormat) Error

func (e InvalidPublicKeyFormat) Error() string

type InvalidTLSSignatureSchemeFormat

type InvalidTLSSignatureSchemeFormat struct {
	Value string
}

func (InvalidTLSSignatureSchemeFormat) Error

type KeyID

type KeyID string

func ParseKeyID

func ParseKeyID(idBase64 string) (KeyID, error)

ParseKeyID parses the given base64-encoded string into a KeyID The id parameter must be a valid base64-encoded string following the base64url encoding scheme *without padding* as defined in RFC 4648, Section 5.

func (KeyID) String

func (k KeyID) String() string

type KeyType

type KeyType int
const (
	RSA KeyType = iota
	ECDSA
	EdDSA
)

func GetKeyType

func GetKeyType(scheme tls.SignatureScheme) (KeyType, error)

type Keys

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

currently a simple wrapper around a SyncMap

func NewKeysDatabase

func NewKeysDatabase() *Keys

func (*Keys) AddKey

func (k *Keys) AddKey(id KeyID, key crypto.PublicKey) crypto.PublicKey

AddKey adds a public key with the given Key ID to the database of keys. Returns nil if no previous key was present with this ID, otherwise returns the previous key.

func (*Keys) GetKey

func (k *Keys) GetKey(id KeyID) crypto.PublicKey

GetKey returns the public key with the given Key ID from the database Returns nil if none was found

func (*Keys) RemoveKey

func (k *Keys) RemoveKey(id KeyID) crypto.PublicKey

RemoveKey removes the public key with the given Key ID from the database

type MalformedHTTPSignatureAuth

type MalformedHTTPSignatureAuth struct {
	Msg string
}

func (MalformedHTTPSignatureAuth) Error

type PubkeyEqual

type PubkeyEqual interface {
	Equal(crypto.PublicKey) bool
}

type PublicKeysMismatch

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

func (PublicKeysMismatch) Error

func (e PublicKeysMismatch) Error() string

type Signature

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

func ExtractSignature

func ExtractSignature(r *http.Request) (*Signature, error)

ExtractSignature extracts the HTTP signature from the Authorization header It may return a nil signature with a nil error if no signature was found. It returns a non-nil error if the Signature was present in the Authorization header but was malformed.

example from the draft:

Authorization: Signature \
  k=YmFzZW1lbnQ, \
  a=VGhpcyBpcyBhIHB1YmxpYyBrZXkgaW4gdXNlIGhlcmU, \
  s=2055, \
  v=dmVyaWZpY2F0aW9uXzE2Qg, \
  p=SW5zZXJ0IHNpZ25hdHVyZSBvZiBub25jZSBoZXJlIHdo \
    aWNoIHRha2VzIDUxMiBiaXRzIGZvciBFZDI1NTE5IQ

func NewSignatureForRequest

func NewSignatureForRequest(tls *tls.ConnectionState, r *http.Request, keyID KeyID, signer crypto.Signer, signatureScheme tls.SignatureScheme) (*Signature, error)

func NewSignatureWithMaterial

func NewSignatureWithMaterial(material *TLSExporterMaterial, keyID KeyID, signer crypto.Signer, signatureScheme tls.SignatureScheme) (*Signature, error)

func ParseSignatureAuthorizationContent

func ParseSignatureAuthorizationContent(content string) (*Signature, error)

ParseSignatureAuthorizationContent parses the given Authorization header content into a Signature. content must be a value Signature Authorization header content, i.e. it must start with "Signature " and follow the specification in https://www.ietf.org/archive/id/draft-ietf-httpbis-unprompted-auth-05.html

func (*Signature) KeyID

func (s *Signature) KeyID() KeyID

func (*Signature) PublicKey

func (s *Signature) PublicKey() crypto.PublicKey

func (*Signature) SignatureAuthorizationHeader

func (s *Signature) SignatureAuthorizationHeader() (string, error)

SignatureAuthorizationHeader serializes the signature into a string that can be used in the Authorization header. The returned value takes the form k, a, v and p are base64url-encoded s is base10-encoded "Signature k=<keyID>,a=<pubkey>,s=<signatureScheme>,v=<exporterVerification>,p=<proof>"

func (*Signature) SignatureScheme

func (s *Signature) SignatureScheme() tls.SignatureScheme

type SignatureNotFound

type SignatureNotFound struct {
}

func (SignatureNotFound) Error

func (e SignatureNotFound) Error() string

type SyncMap

type SyncMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewSyncMap

func NewSyncMap[K comparable, V any]() SyncMap[K, V]

func (*SyncMap[K, V]) Get

func (m *SyncMap[K, V]) Get(key K) (V, bool)

func (*SyncMap[K, V]) Insert

func (m *SyncMap[K, V]) Insert(key K, val V)

func (*SyncMap[K, V]) Remove

func (m *SyncMap[K, V]) Remove(key K)

type TLSExporterMaterial

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

from draft-05: The key exporter output is 48 bytes long. Of those, the first 32 bytes are part of the input to the signature and the next 16 bytes are sent alongside the signature. This allows the recipient to confirm that the exporter produces the right values.

func GenerateTLSExporterMaterial

func GenerateTLSExporterMaterial(tls *tls.ConnectionState, signatureScheme tls.SignatureScheme, keyID KeyID, pubKey crypto.PublicKey, httpScheme string, httpHost string, httpPort uint16, httpRealm string) (TLSExporterMaterial, error)

func (*TLSExporterMaterial) SignatureInput

func (m *TLSExporterMaterial) SignatureInput() [32]byte

func (*TLSExporterMaterial) String

func (m *TLSExporterMaterial) String() string

func (*TLSExporterMaterial) Verification

func (m *TLSExporterMaterial) Verification() [16]byte

type TLSSignatureSchemeNotSupported

type TLSSignatureSchemeNotSupported struct {
	Scheme tls.SignatureScheme
	Reason string
}

func (TLSSignatureSchemeNotSupported) Error

type UnsupportedKeyType

type UnsupportedKeyType struct {
	Type string
}

func (UnsupportedKeyType) Error

func (e UnsupportedKeyType) Error() string

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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