| 1 |
package handshake |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"slices" |
| 7 |
"time" |
| 8 |
|
| 9 |
"github.com/flynn/noise" |
| 10 |
"github.com/slackhq/nebula/cert" |
| 11 |
"github.com/slackhq/nebula/header" |
| 12 |
) |
| 13 |
|
| 14 |
// IndexAllocator is called by the Machine to allocate a local index for the |
| 15 |
// handshake. It is called at most once, when the first outgoing message that |
| 16 |
// carries a payload is built. |
| 17 |
// |
| 18 |
// Implementations MUST NOT return 0. Zero is reserved as a sentinel meaning |
| 19 |
// "no index assigned" on the wire and in the payload-presence checks. If an |
| 20 |
// allocator ever returned 0, a legitimate handshake's payload could be |
| 21 |
// indistinguishable from an empty one and would be rejected. |
| 22 |
type IndexAllocator func() (uint32, error) |
| 23 |
|
| 24 |
// CertVerifier is called by the Machine after reconstructing the peer's |
| 25 |
// certificate from the handshake. The verifier performs all validation |
| 26 |
// (CA trust, expiry, policy checks, allow lists). |
| 27 |
type CertVerifier func(cert.Certificate) (*cert.CachedCertificate, error) |
| 28 |
|
| 29 |
// Result contains the results of a successful handshake. |
| 30 |
// Returned by ProcessPacket when the handshake is complete. |
| 31 |
type Result struct { |
| 32 |
EKey *noise.CipherState |
| 33 |
DKey *noise.CipherState |
| 34 |
Cipher noise.CipherFunc // identifies which post-handshake CipherState the data plane should wrap EKey/DKey in |
| 35 |
MyCert cert.Certificate |
| 36 |
RemoteCert *cert.CachedCertificate |
| 37 |
RemoteIndex uint32 |
| 38 |
LocalIndex uint32 |
| 39 |
HandshakeTime uint64 |
| 40 |
MessageIndex uint64 // number of messages exchanged during the handshake |
| 41 |
Initiator bool |
| 42 |
} |
| 43 |
|
| 44 |
// Machine drives a Noise handshake through N messages. It handles Noise |
| 45 |
// protocol operations, certificate reconstruction, and payload encoding. |
| 46 |
// Certificate validation is delegated to the caller via CertVerifier. |
| 47 |
// |
| 48 |
// A Machine is not safe for concurrent use. The caller must ensure that |
| 49 |
// Initiate and ProcessPacket are not called concurrently. |
| 50 |
// |
| 51 |
// Error contract: when ProcessPacket or Initiate returns an error, callers |
| 52 |
// must check Failed() to decide what to do next. If Failed() is false the |
| 53 |
// underlying noise state was not advanced (the packet was rejected before |
| 54 |
// ReadMessage took effect, or the rejection is non-fatal like a stale |
| 55 |
// retransmit) and the Machine can accept another packet. If Failed() is |
| 56 |
// true the Machine is unrecoverable and the caller must abandon it. |
| 57 |
type Machine struct { |
| 58 |
hs *noise.HandshakeState |
| 59 |
getCred GetCredentialFunc |
| 60 |
allocIndex IndexAllocator |
| 61 |
verifier CertVerifier |
| 62 |
result *Result |
| 63 |
msgs []msgFlags |
| 64 |
myVersion cert.Version |
| 65 |
subtype header.MessageSubType |
| 66 |
indexAllocated bool |
| 67 |
remoteCertSet bool |
| 68 |
payloadSet bool |
| 69 |
failed bool |
| 70 |
} |
| 71 |
|
| 72 |
// NewMachine creates a handshake state machine. The subtype determines both |
| 73 |
// the noise pattern and the per-message content layout. The credential for |
| 74 |
// `version` is fetched via getCred and used to seed the noise.HandshakeState. |
| 75 |
// IndexAllocator is called lazily when the first outgoing payload is built. |
| 76 |
func NewMachine( |
| 77 |
version cert.Version, |
| 78 |
getCred GetCredentialFunc, |
| 79 |
verifier CertVerifier, |
| 80 |
allocIndex IndexAllocator, |
| 81 |
initiator bool, |
| 82 |
subtype header.MessageSubType, |
| 83 |
) (*Machine, error) { |
| 84 |
info, err := subtypeInfoFor(subtype) |
| 85 |
if err != nil { |
| 86 |
return nil, err |
| 87 |
} |
| 88 |
|
| 89 |
cred := getCred(version) |
| 90 |
if cred == nil { |
| 91 |
return nil, fmt.Errorf("%w: %v", ErrNoCredential, version) |
| 92 |
} |
| 93 |
|
| 94 |
hs, err := cred.buildHandshakeState(initiator, info.pattern) |
| 95 |
if err != nil { |
| 96 |
return nil, fmt.Errorf("build noise state: %w", err) |
| 97 |
} |
| 98 |
|
| 99 |
return &Machine{ |
| 100 |
hs: hs, |
| 101 |
subtype: subtype, |
| 102 |
msgs: info.msgs, |
| 103 |
getCred: getCred, |
| 104 |
allocIndex: allocIndex, |
| 105 |
verifier: verifier, |
| 106 |
myVersion: version, |
| 107 |
result: &Result{ |
| 108 |
Initiator: initiator, |
| 109 |
Cipher: cred.cipherSuite, |
| 110 |
}, |
| 111 |
}, nil |
| 112 |
} |
| 113 |
|
| 114 |
// Failed returns true if the Machine is in an unrecoverable state. |
| 115 |
func (m *Machine) Failed() bool { |
| 116 |
return m.failed |
| 117 |
} |
| 118 |
|
| 119 |
// Subtype returns the handshake subtype this Machine was built for. |
| 120 |
func (m *Machine) Subtype() header.MessageSubType { |
| 121 |
return m.subtype |
| 122 |
} |
| 123 |
|
| 124 |
// MessageIndex returns the noise handshake message index, which equals the |
| 125 |
// wire counter of the most recently sent or received message. |
| 126 |
func (m *Machine) MessageIndex() int { |
| 127 |
return m.hs.MessageIndex() |
| 128 |
} |
| 129 |
|
| 130 |
// requireComplete checks that both a peer cert and payload have been received. |
| 131 |
// Marks the machine as failed if not. |
| 132 |
func (m *Machine) requireComplete() error { |
| 133 |
if !m.payloadSet || !m.remoteCertSet { |
| 134 |
m.failed = true |
| 135 |
return ErrIncompleteHandshake |
| 136 |
} |
| 137 |
return nil |
| 138 |
} |
| 139 |
|
| 140 |
// myMsgFlags returns the flags for the current outgoing message. |
| 141 |
func (m *Machine) myMsgFlags() msgFlags { |
| 142 |
idx := m.hs.MessageIndex() |
| 143 |
if idx < len(m.msgs) { |
| 144 |
return m.msgs[idx] |
| 145 |
} |
| 146 |
return msgFlags{} |
| 147 |
} |
| 148 |
|
| 149 |
// peerMsgFlags returns the flags for the message we just read. |
| 150 |
func (m *Machine) peerMsgFlags() msgFlags { |
| 151 |
idx := m.hs.MessageIndex() - 1 |
| 152 |
if idx >= 0 && idx < len(m.msgs) { |
| 153 |
return m.msgs[idx] |
| 154 |
} |
| 155 |
return msgFlags{} |
| 156 |
} |
| 157 |
|
| 158 |
// Initiate produces the first handshake message. Only valid for initiators, |
| 159 |
// and must be called exactly once before ProcessPacket. |
| 160 |
// |
| 161 |
// out is a destination buffer the message is appended to and returned. Pass |
| 162 |
// nil to allocate fresh, or pass a re-used buffer sliced to length 0 (e.g. |
| 163 |
// buf[:0]) with sufficient capacity to avoid allocation. |
| 164 |
// |
| 165 |
// An error return may not indicate a fatal condition, check Failed() to |
| 166 |
// determine if the Machine can still be used. |
| 167 |
func (m *Machine) Initiate(out []byte) ([]byte, error) { |
| 168 |
if m.failed { |
| 169 |
return nil, ErrMachineFailed |
| 170 |
} |
| 171 |
if !m.result.Initiator { |
| 172 |
m.failed = true |
| 173 |
return nil, ErrInitiateOnResponder |
| 174 |
} |
| 175 |
if m.hs.MessageIndex() != 0 { |
| 176 |
m.failed = true |
| 177 |
return nil, ErrInitiateAlreadyCalled |
| 178 |
} |
| 179 |
|
| 180 |
// At MessageIndex=0 with RemoteIndex still zero, buildResponse produces |
| 181 |
// header counter 1 and remote index 0, which is what the initial message needs. |
| 182 |
out, _, _, err := m.buildResponse(out) |
| 183 |
if err != nil { |
| 184 |
m.failed = true |
| 185 |
return nil, err |
| 186 |
} |
| 187 |
return out, nil |
| 188 |
} |
| 189 |
|
| 190 |
// ProcessPacket handles an incoming handshake message. It advances the Noise |
| 191 |
// state, validates the peer certificate via the verifier, and optionally |
| 192 |
// produces a response. |
| 193 |
// |
| 194 |
// out is a destination buffer the response is appended to and returned. Pass |
| 195 |
// nil to allocate fresh, or pass a re-used buffer sliced to length 0 (e.g. |
| 196 |
// buf[:0]) with sufficient capacity to avoid allocation. The returned slice |
| 197 |
// is nil when no outgoing message is produced (handshake complete on this |
| 198 |
// side, or final message of a multi-message pattern). |
| 199 |
// |
| 200 |
// Returns a non-nil Result when the handshake is complete. |
| 201 |
// An error return may not indicate a fatal condition, check Failed() to |
| 202 |
// determine if the Machine can still be used. |
| 203 |
func (m *Machine) ProcessPacket(out, packet []byte) ([]byte, *Result, error) { |
| 204 |
if m.failed { |
| 205 |
return nil, nil, ErrMachineFailed |
| 206 |
} |
| 207 |
if len(packet) < header.Len { |
| 208 |
return nil, nil, ErrPacketTooShort |
| 209 |
} |
| 210 |
// Reject packets whose subtype doesn't match the one this Machine was |
| 211 |
// built for. A pending handshake that suddenly receives a different |
| 212 |
// subtype on its index is either a stray packet that matched by chance |
| 213 |
// or a peer protocol violation; drop it without failing the Machine so |
| 214 |
// the legitimate retransmit can still complete. |
| 215 |
if header.MessageSubType(packet[1]) != m.subtype { |
| 216 |
return nil, nil, ErrSubtypeMismatch |
| 217 |
} |
| 218 |
if m.result.Initiator && m.hs.MessageIndex() == 0 { |
| 219 |
m.failed = true |
| 220 |
return nil, nil, ErrInitiateNotCalled |
| 221 |
} |
| 222 |
|
| 223 |
// The (eKey, dKey) ordering here is correct for IX, where the initiator |
| 224 |
// completes the handshake by reading the responder's stage-2 message. |
| 225 |
// noise returns (cs1, cs2) where cs1 is the initiator->responder cipher. |
| 226 |
// For 3-message patterns where a responder finishes by reading the final |
| 227 |
// message, this ordering would be wrong; revisit when XX/pqIX lands. |
| 228 |
msg, eKey, dKey, err := m.hs.ReadMessage(nil, packet[header.Len:]) |
| 229 |
if err != nil { |
| 230 |
// Noise ReadMessage failed. The noise library checkpoints and rolls back |
| 231 |
// on failure, so the Machine is still alive. The caller can retry with |
| 232 |
// a different packet. |
| 233 |
return nil, nil, fmt.Errorf("noise ReadMessage: %w", err) |
| 234 |
} |
| 235 |
|
| 236 |
// From here on, noise state has advanced. Any error is fatal. |
| 237 |
flags := m.peerMsgFlags() |
| 238 |
|
| 239 |
if err := m.processPayload(msg, flags); err != nil { |
| 240 |
return nil, nil, err |
| 241 |
} |
| 242 |
|
| 243 |
// If ReadMessage derived keys, the handshake is complete. Noise should |
| 244 |
// always produce both keys together; asymmetry is a protocol invariant |
| 245 |
// violation. |
| 246 |
if eKey != nil || dKey != nil { |
| 247 |
if eKey == nil || dKey == nil { |
| 248 |
m.failed = true |
| 249 |
return nil, nil, ErrAsymmetricCipherKeys |
| 250 |
} |
| 251 |
if err := m.requireComplete(); err != nil { |
| 252 |
return nil, nil, err |
| 253 |
} |
| 254 |
return nil, m.completed(eKey, dKey), nil |
| 255 |
} |
| 256 |
|
| 257 |
// ReadMessage didn't complete, produce the next outgoing message |
| 258 |
out, dk, ek, err := m.buildResponse(out) |
| 259 |
if err != nil { |
| 260 |
m.failed = true |
| 261 |
return nil, nil, err |
| 262 |
} |
| 263 |
|
| 264 |
if ek != nil || dk != nil { |
| 265 |
if ek == nil || dk == nil { |
| 266 |
m.failed = true |
| 267 |
return nil, nil, ErrAsymmetricCipherKeys |
| 268 |
} |
| 269 |
if err := m.requireComplete(); err != nil { |
| 270 |
return nil, nil, err |
| 271 |
} |
| 272 |
return out, m.completed(ek, dk), nil |
| 273 |
} |
| 274 |
|
| 275 |
return out, nil, nil |
| 276 |
} |
| 277 |
|
| 278 |
func (m *Machine) completed(eKey, dKey *noise.CipherState) *Result { |
| 279 |
m.result.EKey = eKey |
| 280 |
m.result.DKey = dKey |
| 281 |
m.result.MessageIndex = uint64(m.hs.MessageIndex()) |
| 282 |
return m.result |
| 283 |
} |
| 284 |
|
| 285 |
func (m *Machine) processPayload(msg []byte, flags msgFlags) error { |
| 286 |
if len(msg) == 0 { |
| 287 |
if flags.expectsPayload || flags.expectsCert { |
| 288 |
m.failed = true |
| 289 |
return ErrMissingContent |
| 290 |
} |
| 291 |
return nil |
| 292 |
} |
| 293 |
|
| 294 |
payload, err := UnmarshalPayload(msg) |
| 295 |
if err != nil { |
| 296 |
m.failed = true |
| 297 |
return fmt.Errorf("unmarshal handshake: %w", err) |
| 298 |
} |
| 299 |
|
| 300 |
// Assert the payload contains exactly what we expect |
| 301 |
hasPayloadData := payload.InitiatorIndex != 0 || payload.ResponderIndex != 0 || payload.Time != 0 |
| 302 |
if hasPayloadData != flags.expectsPayload { |
| 303 |
m.failed = true |
| 304 |
return ErrUnexpectedContent |
| 305 |
} |
| 306 |
|
| 307 |
hasCertData := len(payload.Cert) > 0 |
| 308 |
if hasCertData != flags.expectsCert { |
| 309 |
m.failed = true |
| 310 |
return ErrUnexpectedContent |
| 311 |
} |
| 312 |
|
| 313 |
// Process payload |
| 314 |
if flags.expectsPayload { |
| 315 |
var remoteIndex uint32 |
| 316 |
if m.result.Initiator { |
| 317 |
remoteIndex = payload.ResponderIndex |
| 318 |
} else { |
| 319 |
remoteIndex = payload.InitiatorIndex |
| 320 |
} |
| 321 |
// The payload presence check above can be satisfied by Time alone, so a payload |
| 322 |
// could still carry a zero index here. We need to reject it. |
| 323 |
if remoteIndex == 0 { |
| 324 |
m.failed = true |
| 325 |
return ErrInvalidRemoteIndex |
| 326 |
} |
| 327 |
m.result.RemoteIndex = remoteIndex |
| 328 |
m.result.HandshakeTime = payload.Time |
| 329 |
m.payloadSet = true |
| 330 |
} |
| 331 |
|
| 332 |
// Process certificate |
| 333 |
if flags.expectsCert { |
| 334 |
if err := m.validateCert(payload); err != nil { |
| 335 |
return err |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
return nil |
| 340 |
} |
| 341 |
|
| 342 |
func (m *Machine) validateCert(payload Payload) error { |
| 343 |
cred := m.getCred(m.myVersion) |
| 344 |
if cred == nil { |
| 345 |
m.failed = true |
| 346 |
return fmt.Errorf("%w: %v", ErrNoCredential, m.myVersion) |
| 347 |
} |
| 348 |
rc, err := cert.Recombine( |
| 349 |
cert.Version(payload.CertVersion), |
| 350 |
payload.Cert, |
| 351 |
m.hs.PeerStatic(), |
| 352 |
cred.Cert.Curve(), |
| 353 |
) |
| 354 |
if err != nil { |
| 355 |
m.failed = true |
| 356 |
return fmt.Errorf("recombine cert: %w", err) |
| 357 |
} |
| 358 |
|
| 359 |
if !bytes.Equal(rc.PublicKey(), m.hs.PeerStatic()) { |
| 360 |
m.failed = true |
| 361 |
return ErrPublicKeyMismatch |
| 362 |
} |
| 363 |
|
| 364 |
// Version negotiation, if the peer sent a different version and we have it, switch |
| 365 |
if rc.Version() != m.myVersion { |
| 366 |
if m.getCred(rc.Version()) != nil { |
| 367 |
m.myVersion = rc.Version() |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
verified, err := m.verifier(rc) |
| 372 |
if err != nil { |
| 373 |
m.failed = true |
| 374 |
return fmt.Errorf("verify cert: %w", err) |
| 375 |
} |
| 376 |
|
| 377 |
m.result.RemoteCert = verified |
| 378 |
m.remoteCertSet = true |
| 379 |
return nil |
| 380 |
} |
| 381 |
|
| 382 |
func (m *Machine) marshalOutgoing(flags msgFlags) ([]byte, error) { |
| 383 |
if !flags.expectsPayload && !flags.expectsCert { |
| 384 |
return nil, nil |
| 385 |
} |
| 386 |
|
| 387 |
var p Payload |
| 388 |
if flags.expectsPayload { |
| 389 |
if !m.indexAllocated { |
| 390 |
index, err := m.allocIndex() |
| 391 |
if err != nil { |
| 392 |
return nil, fmt.Errorf("%w: %w", ErrIndexAllocation, err) |
| 393 |
} |
| 394 |
m.result.LocalIndex = index |
| 395 |
m.indexAllocated = true |
| 396 |
} |
| 397 |
|
| 398 |
if m.result.Initiator { |
| 399 |
p.InitiatorIndex = m.result.LocalIndex |
| 400 |
} else { |
| 401 |
p.ResponderIndex = m.result.LocalIndex |
| 402 |
p.InitiatorIndex = m.result.RemoteIndex |
| 403 |
} |
| 404 |
p.Time = uint64(time.Now().UnixNano()) |
| 405 |
} |
| 406 |
if flags.expectsCert { |
| 407 |
cred := m.getCred(m.myVersion) |
| 408 |
if cred == nil { |
| 409 |
return nil, fmt.Errorf("%w: %v", ErrNoCredential, m.myVersion) |
| 410 |
} |
| 411 |
p.Cert = cred.Bytes |
| 412 |
p.CertVersion = uint32(cred.Cert.Version()) |
| 413 |
m.result.MyCert = cred.Cert |
| 414 |
} |
| 415 |
|
| 416 |
return MarshalPayload(nil, p), nil |
| 417 |
} |
| 418 |
|
| 419 |
func (m *Machine) buildResponse(out []byte) ([]byte, *noise.CipherState, *noise.CipherState, error) { |
| 420 |
flags := m.myMsgFlags() |
| 421 |
hsBytes, err := m.marshalOutgoing(flags) |
| 422 |
if err != nil { |
| 423 |
return nil, nil, nil, err |
| 424 |
} |
| 425 |
|
| 426 |
// Extend out by header.Len to make room for the header. slices.Grow is a |
| 427 |
// no-op when the cap is already sufficient (the zero-copy case where the |
| 428 |
// caller passed a pre-sized buffer). header.Encode overwrites the new |
| 429 |
// bytes, so they don't need to be zeroed. |
| 430 |
start := len(out) |
| 431 |
out = slices.Grow(out, header.Len)[:start+header.Len] |
| 432 |
header.Encode( |
| 433 |
out[start:], |
| 434 |
header.Version, header.Handshake, m.subtype, |
| 435 |
m.result.RemoteIndex, |
| 436 |
uint64(m.hs.MessageIndex()+1), |
| 437 |
) |
| 438 |
|
| 439 |
// noise.WriteMessage appends the encrypted handshake message to out, |
| 440 |
// reusing capacity when present. |
| 441 |
// |
| 442 |
// The (dKey, eKey) ordering here is correct for IX, where the responder |
| 443 |
// completes the handshake by writing the stage-2 message. noise returns |
| 444 |
// (cs1, cs2) where cs1 is the initiator->responder cipher (which is the |
| 445 |
// responder's decrypt key). For 3-message patterns where an initiator |
| 446 |
// finishes by writing the final message, this ordering would be wrong; |
| 447 |
// revisit when XX/pqIX lands. |
| 448 |
out, dKey, eKey, err := m.hs.WriteMessage(out, hsBytes) |
| 449 |
if err != nil { |
| 450 |
return nil, nil, nil, fmt.Errorf("noise WriteMessage: %w", err) |
| 451 |
} |
| 452 |
|
| 453 |
return out, dKey, eKey, nil |
| 454 |
} |