ike

package module
v0.0.0-...-2e9568b Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2017 License: MIT Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const REPLY_WAIT_TIMEOUT = 5 * time.Second

Variables

View Source
var (
	AsnSHA1WithRSA      = "300d06092a864886f70d0101050500"
	AsnSHA256WithRSA    = "300d06092a864886f70d01010b0500"
	AsnSHA384WithRSA    = "300d06092a864886f70d01010c0500"
	AsnSHA512WithRSA    = "300d06092a864886f70d01010d0500"
	AsnDSAWithSHA1      = "300906072a8648ce380403"
	AsnDSAWithSHA256    = "300b0609608648016503040302"
	AsnECDSAWithSHA1    = "300906072a8648ce3d0401"
	AsnECDSAWithSHA256  = "300a06082a8648ce3d040302"
	AsnECDSAWithSHA384  = "300a06082a8648ce3d040303"
	AsnECDSAWithSHA512  = "300a06082a8648ce3d040304"
	AsnRsaSsaPss        = "300d06092a864886f70d01010a3000"
	AsnRsaSsaPssDefault = "" /* 128-byte string literal not displayed */
	AsnSHA256WithRSAPSS = "" /* 144-byte string literal not displayed */
)

asn1 objects from rfc7427

View Source
var ErrorUDPOnly = errors.New("only udp is supported for now")

ErrorUDPOnly is returned if the given address is other than UDP

Functions

func AddrToIp

func AddrToIp(addr net.Addr) net.IP

func AddrToIpPort

func AddrToIpPort(addr net.Addr) (net.IP, int)

func CreateSignature

func CreateSignature(algo x509.SignatureAlgorithm, authMethod protocol.AuthMethod, signed []byte, private crypto.Signer, log log.Logger) ([]byte, error)

CreateSignature signs request using private key & configured method

func DecryptMessage

func DecryptMessage(msg *Message, tkm *Tkm, forInitiator bool, log log.Logger) (err error)

DecryptMessage uses crypto keys to decode & verify the message

func FirstLastAddressToIPNet

func FirstLastAddressToIPNet(start, end net.IP) *net.IPNet

func IPNetToFirstLastAddress

func IPNetToFirstLastAddress(n *net.IPNet) (first, last net.IP, err error)

IPNetToFirstLastAddress returns the first & last address derived from the IPNet notation

func Jitter

func Jitter(duration time.Duration, maxFactor float64) time.Duration

Jitter returns a time.Duration between duration and duration + maxFactor * duration, to allow clients to avoid converging on periodic behavior. If maxFactor is 0.0, a suggested default value will be chosen.

func LoadCerts

func LoadCerts(certFile string) ([]*x509.Certificate, error)

func LoadKey

func LoadKey(keyFile string) (*rsa.PrivateKey, error)

func LoadPEMCert

func LoadPEMCert(certFile string) (*x509.Certificate, error)

func LoadRoot

func LoadRoot(caCert string) (*x509.CertPool, error)

func MakeSpi

func MakeSpi() (ret protocol.Spi)

func MatchNameFromCert

func MatchNameFromCert(cert *CertID, name string) bool

MatchNameFromCert checks if name is specified in Subject or Altnames

func NewECCA

func NewECCA(name string) (*x509.Certificate, interface{}, error)

NewSelfSignedCACert creates a CA certificate

func NewSignedCert

func NewSignedCert(cfg CertID, publicKey interface{}, caCert *x509.Certificate, caKey interface{}) (*x509.Certificate, error)

NewSignedCert creates a signed certificate using the given CA certificate and key

func RunSession

func RunSession(sess *Session) error

RunSession starts and monitors the session returning when the session ends

func SpiToInt32

func SpiToInt32(spi protocol.Spi) uint32

func SpiToInt64

func SpiToInt64(spi protocol.Spi) uint64

func VerifySignature

func VerifySignature(authMethod protocol.AuthMethod, signed, signature []byte, cert *x509.Certificate, log log.Logger) error

VerifySignature using certificate & configured auth method

func WriteData

func WriteData(conn Conn, data []byte, remote net.Addr, log log.Logger) (err error)

func WriteMessage

func WriteMessage(conn Conn, msg *Message, tkm *Tkm, forInitiator bool, log log.Logger) (err error)

Types

type AltNames

type AltNames struct {
	DNSNames []string
	IPs      []net.IP
	Emails   []string
}

AltNames contains the domain names and IP addresses that will be added to the API Server's x509 certificate SubAltNames field. The values will be passed directly to the x509.Certificate object.

type Authenticator

type Authenticator interface {
	Identity() Identity
	Sign([]byte, *protocol.IdPayload, log.Logger) ([]byte, error)
	Verify(initB []byte, idP *protocol.IdPayload, authMethod protocol.AuthMethod, authData []byte, inbandData interface{}, logger log.Logger) error
}

Authenticator is used to authenticate & create AUTH payloads

func NewAuthenticator

func NewAuthenticator(id Identity, tkm *Tkm, forInitiator, rfc7427Signatures bool) Authenticator

type CertAuthenticator

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

CertAuthenticator is an Authenticator

func (*CertAuthenticator) Identity

func (o *CertAuthenticator) Identity() Identity

func (*CertAuthenticator) Sign

func (o *CertAuthenticator) Sign(initB []byte, idP *protocol.IdPayload, logger log.Logger) ([]byte, error)

func (*CertAuthenticator) Verify

func (o *CertAuthenticator) Verify(initB []byte, idP *protocol.IdPayload, authMethod protocol.AuthMethod, authData []byte, inbandData interface{}, logger log.Logger) error

Verify using one of: AUTH_RSA_DIGITAL_SIGNATURE with certificates RFC 7427 - Signature Authentication in IKEv2 tkm.Auth always uses the hash negotiated with prf TODO: implement raw AUTH_RSA_DIGITAL_SIGNATURE & AUTH_DSS_DIGITAL_SIGNATURE TODO: implement ECDSA from RFC4754

type CertID

type CertID struct {
	CommonName          string
	Organization        []string
	AltNames            AltNames
	Issuer              string
	NotBefore, NotAfter time.Time
	IsCA                bool
}

func FormatCert

func FormatCert(c *x509.Certificate) (id CertID)

FormatCert receives certificate and formats in human-readable format

func (*CertID) String

func (c *CertID) String() string

type CertIdentity

type CertIdentity struct {
	Certificate          *x509.Certificate
	PrivateKey           crypto.Signer
	Roots                *x509.CertPool
	Name                 string
	AuthenticationMethod protocol.AuthMethod
}

func (*CertIdentity) AuthData

func (c *CertIdentity) AuthData(id []byte) []byte

func (*CertIdentity) AuthMethod

func (c *CertIdentity) AuthMethod() protocol.AuthMethod

func (*CertIdentity) Id

func (c *CertIdentity) Id() []byte

func (*CertIdentity) IdType

func (c *CertIdentity) IdType() protocol.IdType

type Cmd

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

Cmd provides utilities for building ike apps

func NewCmd

func NewCmd(conn Conn, cb *SessionCallback) *Cmd

func (*Cmd) Run

func (i *Cmd) Run(config *Config, log log.Logger) error

Run loops until there is a socket error

func (*Cmd) RunInitiator

func (i *Cmd) RunInitiator(localAddr, remoteAddr net.Addr, config *Config, log log.Logger)

RunInitiator starts & watches over on initiator session in a separate goroutine

func (*Cmd) ShutDown

func (i *Cmd) ShutDown(err error)

ShutDown closes all active IKE sessions

type Config

type Config struct {
	ProposalIke, ProposalEsp protocol.TransformMap

	LocalID, PeerID Identity

	TsI, TsR             protocol.Selectors
	IsTransportMode      bool
	ThrottleInitRequests bool
	Lifetime             time.Duration
}

func DefaultConfig

func DefaultConfig() *Config

func (*Config) AddHostSelectors

func (cfg *Config) AddHostSelectors(local, remote net.IP, forInitiator bool) error

AddHostSelectors builds selectors from ip addresses

func (*Config) AddNetworkSelectors

func (cfg *Config) AddNetworkSelectors(localnet, remotenet *net.IPNet, forInitiator bool) (err error)

AddNetworkSelectors builds selector from address & mask

func (*Config) CheckDhTransform

func (cfg *Config) CheckDhTransform(dhID protocol.DhTransformId) error

func (*Config) CheckProposals

func (cfg *Config) CheckProposals(prot protocol.ProtocolID, proposals protocol.Proposals) (err error)

CheckProposals checks if incoming proposals include our configuration

func (*Config) CheckSelectors

func (cfg *Config) CheckSelectors(tsi, tsr protocol.Selectors, isTransportMode bool) error

CheckSelectors checks if incoming selectors match our configuration

func (*Config) Policy

func (cfg *Config) Policy() *protocol.PolicyParams

Policy converts the selectors to policy

type Conn

type Conn interface {
	ReadPacket() (b []byte, remoteAddr, localAddr net.Addr, err error)
	WritePacket(reply []byte, remoteAddr net.Addr) error
	Inner() net.Conn
	Close() error
}

func Listen

func Listen(network, address string, logger log.Logger) (Conn, error)

type Identity

type Identity interface {
	IdType() protocol.IdType
	Id() []byte
	AuthMethod() protocol.AuthMethod
	AuthData(id []byte) []byte
}

type InformationalEvent

type InformationalEvent struct {
	SessionNotificationType
	Message interface{}
}

func HandleInformationalForSession

func HandleInformationalForSession(sess *Session, msg *Message) *InformationalEvent

HandleInformationalForSession handles informational from peer TODO : handles a single payload only

type Message

type Message struct {
	IkeHeader             *protocol.IkeHeader
	Payloads              *protocol.Payloads
	LocalAddr, RemoteAddr net.Addr

	Data   []byte      // used to carry raw bytes
	Params interface{} // used to carry the parsed/source structure
}

Message carries the ike packet

func ChildSaFromSession

func ChildSaFromSession(sess *Session, newTkm *Tkm, isInitiator bool, espSpi []byte) *Message

ChildSaFromSession creates CREATE_CHILD_SA messages HDR, SK {N(REKEY_SA), SA, Ni, [KEi,] TSi, TSr} --> <-- HDR, SK {SA, Nr, [KEr,] TSi, TSr}

func DecodeMessage

func DecodeMessage(b []byte, log log.Logger) (msg *Message, err error)

DecodeMessage decodes an keeps the message buffer for later decryption

func DeleteFromSession

func DeleteFromSession(sess *Session) *Message

DeleteFromSession builds an IKE delete Request

func EmptyFromSession

func EmptyFromSession(sess *Session, isResponse bool) *Message

EmptyFromSession can build an empty Request or a Response

func InitFromSession

func InitFromSession(sess *Session) *Message

InitFromSession creates IKE_SA_INIT messages

func NotifyFromSession

func NotifyFromSession(sess *Session, ie protocol.IkeErrorCode, isResponse bool) *Message

NotifyFromSession builds a Notification Request

func ReadMessage

func ReadMessage(conn Conn, log log.Logger) (*Message, error)

ReadMessage reads an IKE message from connection Connection errors are returned, protocol errors are simply logged TODO - defrag logic seems wrong; revisit

func (*Message) CheckFlags

func (msg *Message) CheckFlags() error

CheckFlags checks if flags are correctly set for us NOTE: To simply implementation, we do not handle the case where original responder starts transactions. In reality this only effects CHILD_SA txns so this function is not to be used for NOTIFICATIONS

func (*Message) DecodeHeader

func (msg *Message) DecodeHeader(b []byte) (err error)

DecodeHeader decodes the ike header and replaces the IkeHeader member

func (*Message) DecodePayloads

func (msg *Message) DecodePayloads(b []byte, nextPayload protocol.PayloadType, log log.Logger) (err error)

DecodePayloads decodes & replaces the payloads member with list of decoded payloads

func (*Message) Encode

func (msg *Message) Encode(tkm *Tkm, forInitiator bool, log log.Logger) (b []byte, err error)

Encode encodes the message using crypto keys

func (*Message) EnsurePayloads

func (msg *Message) EnsurePayloads(payloadTypes []protocol.PayloadType) error

EnsurePayloads checks if the needed payloads are present in the message

type OutgoingMessage

type OutgoingMessage struct {
	Data []byte
}

type PskAuthenticator

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

PskAuthenticator is an Authenticator

func (*PskAuthenticator) Identity

func (psk *PskAuthenticator) Identity() Identity

func (*PskAuthenticator) Sign

func (psk *PskAuthenticator) Sign(initB []byte, idP *protocol.IdPayload, logger log.Logger) ([]byte, error)

signB := responder: initRB | Ni | prf(SK_pr, IDr') initiator: initIB | Nr | prf(SK_pi, IDi') authB = prf( prf(Shared Secret, "Key Pad for IKEv2"), SignB)

func (*PskAuthenticator) Verify

func (psk *PskAuthenticator) Verify(initB []byte, idP *protocol.IdPayload, authMethod protocol.AuthMethod, authData []byte, inbandData interface{}, logger log.Logger) error

type PskIdentities

type PskIdentities struct {
	Ids     map[string][]byte
	Primary string
}

func (*PskIdentities) AuthData

func (psk *PskIdentities) AuthData(id []byte) []byte

func (*PskIdentities) AuthMethod

func (psk *PskIdentities) AuthMethod() protocol.AuthMethod

func (*PskIdentities) Id

func (psk *PskIdentities) Id() []byte

func (*PskIdentities) IdType

func (psk *PskIdentities) IdType() protocol.IdType

type Session

type Session struct {
	SessionID int32

	IkeSpiI, IkeSpiR protocol.Spi
	EspSpiI, EspSpiR protocol.Spi

	// data from client
	Conn          Conn
	Local, Remote net.Addr
	Cb            SessionCallback

	Logger log.Logger
	// contains filtered or unexported fields
}

Session stores IKE session's local state

func NewInitiator

func NewInitiator(cfg *Config, localAddr, remoteAddr net.Addr, conn Conn, cb *SessionCallback, logger log.Logger) (*Session, error)

NewInitiator creates an initiator session

func NewResponder

func NewResponder(cfg *Config, conn Conn, cb *SessionCallback, initI *Message, logger log.Logger) (*Session, error)

NewResponder creates a Responder session

func (*Session) AddSa

func (sess *Session) AddSa(sa *platform.SaParams) (err error)

AddSa adds Child SA

func (*Session) AuthMsg

func (sess *Session) AuthMsg() (*OutgoingMessage, error)

AuthMsg generates IKE_AUTH

func (*Session) AuthReply

func (sess *Session) AuthReply(ie error)

func (*Session) CheckError

func (sess *Session) CheckError(err error, isResponse bool) error

CheckError checks error for error & sends notification within INFORMATIONAL

func (*Session) CreateIkeSa

func (sess *Session) CreateIkeSa(init *initParams) error

func (*Session) InitMsg

func (sess *Session) InitMsg() (*OutgoingMessage, error)

InitMsg generates IKE_INIT

func (*Session) IsInitiator

func (sess *Session) IsInitiator() bool

func (*Session) MarshalJSON

func (sess *Session) MarshalJSON() ([]byte, error)

func (*Session) Notify

func (sess *Session) Notify(ie protocol.IkeErrorCode, isResponse bool)

func (*Session) PostMessage

func (sess *Session) PostMessage(msg *Message)

func (*Session) RekeyMsg

func (sess *Session) RekeyMsg(child *Message) (*OutgoingMessage, error)

func (*Session) RemoveSa

func (sess *Session) RemoveSa() (err error)

RemoveSa removes Child SA

func (*Session) SendEmptyInformational

func (sess *Session) SendEmptyInformational(isResponse bool) error

SendEmptyInformational can be used for periodic keepalive

func (*Session) SendMsgGetReply

func (sess *Session) SendMsgGetReply(genMsg func() (*OutgoingMessage, error)) (*Message, error)

SendMsgGetReply sends a request and waits for valid reply

func (*Session) SetCookie

func (sess *Session) SetCookie(cn *protocol.NotifyPayload)

func (*Session) Shutdown

func (sess *Session) Shutdown(err error)

Shutdown is called to initiate a session shutdown 1: peer shut us down, or 2: we are shutting down all sessions

func (*Session) String

func (sess *Session) String() string

type SessionCallback

type SessionCallback struct {
	InstallPolicy func(*Session, *protocol.PolicyParams) error
	RemovePolicy  func(*Session, *protocol.PolicyParams) error

	InstallChildSa func(*Session, *platform.SaParams) error
	RemoveChildSa  func(*Session, *platform.SaParams) error
}

SessionCallback holds the callbacks used by the session to notify the user

type SessionNotificationType

type SessionNotificationType int
const (
	MSG_EMPTY_REQUEST SessionNotificationType = iota
	MSG_EMPTY_RESPONSE
	MSG_NOTIFICATION
	MSG_ERROR
)

type Sessions

type Sessions interface {
	Add(spi uint64, session *Session)
	Remove(spi uint64)
	Get(spi uint64) (*Session, bool)
	ForEach(action func(*Session))
}

func NewSessions

func NewSessions() Sessions

type Tkm

type Tkm struct {
	Nr, Ni *big.Int

	DhPublic *big.Int
	DhShared *big.Int
	// contains filtered or unexported fields
}

func NewTkm

func NewTkm(cfg *Config, ni *big.Int) (*Tkm, error)

func (*Tkm) CryptoOverhead

func (t *Tkm) CryptoOverhead(b []byte) int

func (*Tkm) DhGenerateKey

func (t *Tkm) DhGenerateKey(theirPublic *big.Int) (err error)

DhGenerateKey creates & stores the dh key upon receipt of peers resp, a dh shared secret can be calculated

func (*Tkm) EncryptMac

func (t *Tkm) EncryptMac(ike []byte, forInitiator bool) (b []byte, err error)

encrypt-then-MAC

func (*Tkm) IkeSaKeys

func (t *Tkm) IkeSaKeys(spiI, spiR []byte, old_skD []byte)

IkeSaKeys creates ike sa keys

func (*Tkm) IpsecSaKeys

func (t *Tkm) IpsecSaKeys(ni, nr, dhShared *big.Int) (espEi, espAi, espEr, espAr []byte)

IpsecSaKeys generates & returns Ipsec Sa keys

func (*Tkm) MarshalJSON

func (t *Tkm) MarshalJSON() ([]byte, error)

func (*Tkm) SignB

func (t *Tkm) SignB(initB []byte, id []byte, forInitiator bool) []byte

SignB gets signed data from tkm section 2.15 For the responder, the octets to be signed start with the first octet of the first SPI in the header of the second message (IKE_SA_INIT response) and end with the last octet of the last payload in the second message. => initIRB Appended to this (for the purposes of computing the signature) are the initiator's nonce Ni (just the value, not the payload containing it), and the value prf(SK_pr, IDr') so signB := responder: initRB | Ni | prf(SK_pr, IDr') initiator: initIB | Nr | prf(SK_pi, IDi') this method can be used by signer & verifier

func (*Tkm) String

func (t *Tkm) String() string

func (*Tkm) VerifyDecrypt

func (t *Tkm) VerifyDecrypt(ike []byte, forInitiator bool) (dec []byte, err error)

MAC-then-decrypt

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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