-
Notifications
You must be signed in to change notification settings - Fork 13
/
handshake.rs
663 lines (594 loc) · 24.3 KB
/
handshake.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Distribution Handshake.
//!
//! This handshake is used by an Erlang node for connecting to another one.
//!
//! See
//! [Distribution Handshake (Erlang Official Doc)](https://www.erlang.org/doc/apps/erts/erl_dist_protocol.html#distribution-handshake)
//! for more details.
use crate::io::Connection;
use crate::node::{Creation, LocalNode, NodeName, PeerNode};
use crate::DistributionFlags;
use byteorder::{BigEndian, ReadBytesExt};
use futures::io::{AsyncRead, AsyncWrite};
/// Client-side handshake.
#[derive(Debug)]
pub struct ClientSideHandshake<T> {
local_node: LocalNode,
local_challenge: Challenge,
cookie: String,
connection: Connection<T>,
send_name_status: Option<HandshakeStatus>,
may_need_complement: bool,
}
impl<T> ClientSideHandshake<T>
where
T: AsyncRead + AsyncWrite + Unpin,
{
/// Makes a new [`ClientSideHandshake`] instance.
pub fn new(connection: T, local_node: LocalNode, cookie: &str) -> Self {
Self {
local_node,
local_challenge: Challenge::new(),
cookie: cookie.to_owned(),
connection: Connection::new(connection),
send_name_status: None,
may_need_complement: false,
}
}
/// Executes the first part of the handshake protocol.
///
/// To complete the handshake, you then need to call [`ClientSideHandshake::execute_rest()`] method
/// taking into account the [`HandshakeStatus`] replied from the peer node.
pub async fn execute_send_name(
&mut self,
protocol_version: u16,
) -> Result<HandshakeStatus, HandshakeError> {
self.send_name(protocol_version).await?;
let status = self.recv_status().await?;
self.send_name_status = Some(status.clone());
Ok(status)
}
/// Executes the rest part of the handshake protocol.
///
/// You must need to have called [`ClientSideHandshake::execute_send_name()`] before this method.
/// In a case where [`HandshakeStatus`] of the first part is [`HandshakeStatus::Alive`],
/// the `do_continue` argument is used to indicate whether this handshake should continue or not
/// (otherwise the argument is ignored).
///
/// If the [`HandshakeStatus`] returned is a non-ok status, this method call fails immediately.
pub async fn execute_rest(
mut self,
do_continue: bool,
) -> Result<(T, PeerNode), HandshakeError> {
match self.send_name_status {
None => {
return Err(HandshakeError::PhaseError {
current: "ClientSideHandshake::execute_rest()",
depends_on: "ClientSideHandshake::execute_send_name()",
})
}
Some(HandshakeStatus::Nok) => return Err(HandshakeError::OngoingHandshake),
Some(HandshakeStatus::NotAllowed) => return Err(HandshakeError::NotAllowed),
Some(HandshakeStatus::Alive) => {
self.send_status(if do_continue { "true" } else { "false" })
.await?;
if !do_continue {
return Err(HandshakeError::AlreadyActive);
}
}
_ => {}
}
let (peer_node, peer_challenge) = self.recv_challenge().await?;
if self.may_need_complement && peer_node.creation.is_some() {
self.send_complement().await?;
}
self.send_challenge_reply(peer_challenge).await?;
self.recv_challenge_ack().await?;
let connection = self.connection.into_inner();
Ok((connection, peer_node))
}
async fn send_name(&mut self, protocol_version: u16) -> Result<(), HandshakeError> {
let mut writer = self.connection.handshake_message_writer();
match protocol_version {
5 => {
writer.write_u8(b'n')?;
writer.write_u16(5)?;
writer.write_u32(self.local_node.flags.bits() as u32)?;
writer.write_all(self.local_node.name.to_string().as_bytes())?;
self.may_need_complement = true;
}
6 => {
writer.write_u8(b'N')?;
writer.write_u64(self.local_node.flags.bits())?;
writer.write_u32(self.local_node.creation.get())?;
if self.local_node.flags.contains(DistributionFlags::NAME_ME) {
writer.write_u16(self.local_node.name.host().len() as u16)?;
writer.write_all(self.local_node.name.host().as_bytes())?;
} else {
writer.write_u16(self.local_node.name.len() as u16)?;
writer.write_all(self.local_node.name.to_string().as_bytes())?;
}
}
value => {
return Err(HandshakeError::UnknownProtocolVersion { value });
}
}
writer.finish().await?;
Ok(())
}
async fn recv_status(&mut self) -> Result<HandshakeStatus, HandshakeError> {
let mut reader = self.connection.handshake_message_reader().await?;
let tag = reader.read_u8().await?;
if tag != b's' {
return Err(HandshakeError::UnexpectedTag {
message: "STATUS",
tag,
});
}
let status = reader.read_bytes().await?;
let status = match status.as_slice() {
b"ok" => HandshakeStatus::Ok,
b"ok_simultaneous" => HandshakeStatus::OkSimultaneous,
b"nok" => HandshakeStatus::Nok,
b"not_allowed" => HandshakeStatus::NotAllowed,
b"alive" => HandshakeStatus::Alive,
_ => {
if status.starts_with(b"named:") {
use std::io::Read as _;
let mut bytes = &status["named:".len()..];
let n = u64::from(bytes.read_u16::<BigEndian>()?);
let mut name = String::new();
bytes.take(n).read_to_string(&mut name)?;
let node_name: NodeName = name.parse()?;
let name = node_name.name().to_owned();
let creation = Creation::new(bytes.read_u32::<BigEndian>()?);
HandshakeStatus::Named { name, creation }
} else {
let status = String::from_utf8_lossy(&status).to_string();
return Err(HandshakeError::UnknownStatus { status });
}
}
};
reader.finish().await?;
Ok(status)
}
async fn send_status(&mut self, status: &str) -> Result<(), HandshakeError> {
let mut writer = self.connection.handshake_message_writer();
writer.write_u8(b's')?;
writer.write_all(status.as_bytes())?;
Ok(())
}
async fn recv_challenge(&mut self) -> Result<(PeerNode, Challenge), HandshakeError> {
let mut reader = self.connection.handshake_message_reader().await?;
let (node, challenge) = match reader.read_u8().await? {
b'n' => {
let version = reader.read_u16().await?;
if version != 5 {
return Err(HandshakeError::InvalidVersionValue { value: version });
}
let flags =
DistributionFlags::from_bits_truncate(u64::from(reader.read_u32().await?));
let challenge = Challenge(reader.read_u32().await?);
let name = reader.read_string().await?.parse()?;
let node = PeerNode {
name,
flags,
creation: None,
};
(node, challenge)
}
b'N' => {
let flags = DistributionFlags::from_bits_truncate(reader.read_u64().await?);
let challenge = Challenge(reader.read_u32().await?);
let creation = Creation::new(reader.read_u32().await?);
let name = reader.read_u16_string().await?.parse()?;
let node = PeerNode {
name,
flags,
creation: Some(creation),
};
(node, challenge)
}
tag => {
return Err(HandshakeError::UnexpectedTag {
message: "CHALLENGE",
tag,
})
}
};
reader.finish().await?;
Ok((node, challenge))
}
async fn send_complement(&mut self) -> Result<(), HandshakeError> {
let mut writer = self.connection.handshake_message_writer();
writer.write_u8(b'c')?;
writer.write_u32((self.local_node.flags.bits() >> 32) as u32)?;
writer.write_u32(self.local_node.creation.get())?;
writer.finish().await?;
Ok(())
}
async fn send_challenge_reply(
&mut self,
peer_challenge: Challenge,
) -> Result<(), HandshakeError> {
let mut writer = self.connection.handshake_message_writer();
writer.write_u8(b'r')?;
writer.write_u32(self.local_challenge.0)?;
writer.write_all(&peer_challenge.digest(&self.cookie).0)?;
writer.finish().await?;
Ok(())
}
async fn recv_challenge_ack(&mut self) -> Result<(), HandshakeError> {
let mut reader = self.connection.handshake_message_reader().await?;
let tag = reader.read_u8().await?;
if tag != b'a' {
return Err(HandshakeError::UnexpectedTag {
message: "CHALLENGE_ACK",
tag,
});
}
let mut digest = [0; 16];
reader.read_exact(&mut digest).await?;
if digest != self.local_challenge.digest(&self.cookie).0 {
return Err(HandshakeError::CookieMismatch);
}
reader.finish().await?;
Ok(())
}
}
/// Server-side handshake.
#[derive(Debug)]
pub struct ServerSideHandshake<T> {
local_node: LocalNode,
local_challenge: Challenge,
cookie: String,
connection: Connection<T>,
peer_node: Option<PeerNode>,
}
impl<T> ServerSideHandshake<T>
where
T: AsyncRead + AsyncWrite + Unpin,
{
/// Makes a new [`ServerSideHandshake`] instance.
pub fn new(connection: T, local_node: LocalNode, cookie: &str) -> Self {
Self {
local_node,
local_challenge: Challenge::new(),
cookie: cookie.to_owned(),
connection: Connection::new(connection),
peer_node: None,
}
}
/// Executes the first part of the handshake protocol.
///
/// To complete the handshake, you then need to call [`ServerSideHandshake::execute_rest()`] method
/// taking into account the [`NodeName`] sent from the peer node.
///
/// Note that the return value becomes `None` if the peer requested a dynamic node name.
/// In the case, if you want to continue the handshake, you need to use [`HandshakeStatus::Named`] for the reply.
pub async fn execute_recv_name(&mut self) -> Result<Option<NodeName>, HandshakeError> {
let mut reader = self.connection.handshake_message_reader().await?;
let tag = reader.read_u8().await?;
let node = match tag {
b'n' => {
let version = reader.read_u16().await?;
if version != 5 {
return Err(HandshakeError::InvalidVersionValue { value: version });
}
let flags =
DistributionFlags::from_bits_truncate(u64::from(reader.read_u32().await?));
let name = reader.read_string().await?.parse()?;
PeerNode {
name,
flags,
creation: None,
}
}
b'N' => {
let flags = DistributionFlags::from_bits_truncate(reader.read_u64().await?);
let creation = Creation::new(reader.read_u32().await?);
let name = if flags.contains(DistributionFlags::NAME_ME) {
let host = reader.read_u16_string().await?;
NodeName::new("nonode", &host)?
} else {
reader.read_u16_string().await?.parse()?
};
PeerNode {
name,
flags,
creation: Some(creation),
}
}
_ => {
return Err(HandshakeError::UnexpectedTag {
message: "NAME",
tag,
})
}
};
reader.finish().await?;
let name = node.name.clone();
let is_dynamic = node.flags.contains(DistributionFlags::NAME_ME);
self.peer_node = Some(node);
if is_dynamic {
Ok(None)
} else {
Ok(Some(name))
}
}
/// Executes the rest part of the handshake protocol.
///
/// You must need to have called [`ServerSideHandshake::execute_recv_name()`] before this method.
///
/// Note that if the [`HandshakeStatus`] is a non-ok status, this method call fails just
/// after sending the status to the peer node.
pub async fn execute_rest(
mut self,
status: HandshakeStatus,
) -> Result<(T, PeerNode), HandshakeError> {
let (peer_flags, peer_creation) = if let Some(peer) = &self.peer_node {
(peer.flags, peer.creation)
} else {
return Err(HandshakeError::PhaseError {
current: "ServerSideHandshake::execute_rest()",
depends_on: "ServerSideHandshake::execute_recv_name()",
});
};
self.send_status(status).await?;
self.send_challenge(peer_flags).await?;
if peer_flags.contains(DistributionFlags::HANDSHAKE_23) && peer_creation.is_none() {
self.recv_complement().await?;
}
let peer_challenge = self.recv_challenge_reply().await?;
self.send_challenge_ack(peer_challenge).await?;
let peer_node = self.peer_node.take().expect("unreachable");
let connection = self.connection.into_inner();
Ok((connection, peer_node))
}
async fn send_status(&mut self, status: HandshakeStatus) -> Result<(), HandshakeError> {
let mut writer = self.connection.handshake_message_writer();
writer.write_u8(b's')?;
match &status {
HandshakeStatus::Ok => writer.write_all(b"ok")?,
HandshakeStatus::OkSimultaneous => writer.write_all(b"ok_simultaneous")?,
HandshakeStatus::Nok => writer.write_all(b"nok")?,
HandshakeStatus::NotAllowed => writer.write_all(b"not_allowed")?,
HandshakeStatus::Alive => writer.write_all(b"alive")?,
HandshakeStatus::Named { name, creation } => {
let peer_node = self.peer_node.as_mut().expect("unreachable");
let node_name = NodeName::new(name, peer_node.name.host())?;
writer.write_all(b"named:")?;
writer.write_u16(node_name.len() as u16)?;
writer.write_all(node_name.to_string().as_bytes())?;
writer.write_u32(creation.get())?;
peer_node.name = node_name;
peer_node.creation = Some(*creation);
self.local_node.flags |= DistributionFlags::NAME_ME;
}
}
writer.finish().await?;
match status {
HandshakeStatus::Nok => Err(HandshakeError::OngoingHandshake),
HandshakeStatus::NotAllowed => Err(HandshakeError::NotAllowed),
_ => Ok(()),
}
}
async fn send_challenge(
&mut self,
peer_flags: DistributionFlags,
) -> Result<(), HandshakeError> {
let mut writer = self.connection.handshake_message_writer();
if peer_flags.contains(DistributionFlags::HANDSHAKE_23) {
writer.write_u8(b'N')?;
writer.write_u64(self.local_node.flags.bits())?;
writer.write_u32(self.local_challenge.0)?;
writer.write_u32(self.local_node.creation.get())?;
writer.write_u16(self.local_node.name.len() as u16)?;
writer.write_all(self.local_node.name.to_string().as_bytes())?;
} else {
writer.write_u8(b'n')?;
writer.write_u16(5)?;
writer.write_u32(self.local_node.flags.bits() as u32)?;
writer.write_u32(self.local_challenge.0)?;
writer.write_all(self.local_node.name.to_string().as_bytes())?;
}
writer.finish().await?;
Ok(())
}
async fn recv_complement(&mut self) -> Result<(), HandshakeError> {
let mut reader = self.connection.handshake_message_reader().await?;
let tag = reader.read_u8().await?;
if tag != b'c' {
return Err(HandshakeError::UnexpectedTag {
message: "send_complement",
tag,
});
}
let flags_high =
DistributionFlags::from_bits_truncate(u64::from(reader.read_u32().await?) << 32);
let creation = Creation::new(reader.read_u32().await?);
reader.finish().await?;
let peer = self.peer_node.as_mut().expect("unreachable");
peer.flags |= flags_high;
peer.creation = Some(creation);
Ok(())
}
async fn recv_challenge_reply(&mut self) -> Result<Challenge, HandshakeError> {
let mut reader = self.connection.handshake_message_reader().await?;
let tag = reader.read_u8().await?;
if tag != b'r' {
return Err(HandshakeError::UnexpectedTag {
message: "challenge_reply",
tag,
});
}
let peer_challenge = Challenge(reader.read_u32().await?);
let mut digest = Digest([0; 16]);
reader.read_exact(&mut digest.0).await?;
reader.finish().await?;
if self.local_challenge.digest(&self.cookie) != digest {
return Err(HandshakeError::CookieMismatch);
}
Ok(peer_challenge)
}
async fn send_challenge_ack(
&mut self,
peer_challenge: Challenge,
) -> Result<(), HandshakeError> {
let mut writer = self.connection.handshake_message_writer();
writer.write_u8(b'a')?;
writer.write_all(&peer_challenge.digest(&self.cookie).0)?;
writer.finish().await?;
Ok(())
}
}
/// Handshake status.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum HandshakeStatus {
/// The handshake will continue.
Ok,
/// The handshake will continue.
///
/// The client-side node is informed that the server-side node has another ongoing connection attempt
/// that will be shut down (simultaneous connect where the client-side node's name is
/// greater than the server-side node's name, compared literally).
OkSimultaneous,
/// The handshake will not continue.
///
/// The client-side already has an ongoing handshake, which it itself has initiated
/// (simultaneous connect where the server-side node's name is greater than the client-side node's).
Nok,
/// The connection is disallowed for some (unspecified) security reason.
NotAllowed,
/// A connection to the node is already active.
///
/// This either means that node the client-side node is confused or
/// that the TCP connection breakdown of a previous node with this name has not yet reached the server-side node.
///
/// The client-side node then decides whether to continue or not the handshake process.
Alive,
/// The handshake willl continue, but the client-side node requested a dynamic node name.
Named {
/// Dynamic node name that the server-side node generated.
///
/// Note that this name doesn't contain the host part.
name: String,
/// Node creation that the server-side node generated for the client node.
creation: Creation,
},
}
#[derive(Debug, Clone, Copy)]
struct Challenge(u32);
impl Challenge {
fn new() -> Self {
Self(rand::random())
}
fn digest(self, cookie: &str) -> Digest {
Digest(md5::compute(&format!("{}{}", cookie, self.0)).0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Digest([u8; 16]);
/// Possible errors during handshake.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum HandshakeError {
#[error("peer already has an ongoing handshake with this node")]
OngoingHandshake,
#[error("the connection is disallowed for some (unspecified) security reason")]
NotAllowed,
#[error("a connection to the node is already active")]
AlreadyActive,
#[error("unknown distribution protocol version {value:?}")]
UnknownProtocolVersion { value: u16 },
#[error("received an unknown status {status:?}")]
UnknownStatus { status: String },
#[error("received an unexpected tag {tag} for {message:?}")]
UnexpectedTag { message: &'static str, tag: u8 },
#[error("cookie mismatch")]
CookieMismatch,
#[error("the 'version' value of an old 'send_name' message must be 5, but got {value}")]
InvalidVersionValue { value: u16 },
#[error("{current:?} was unexpectedly executed before {depends_on:?}")]
PhaseError {
current: &'static str,
depends_on: &'static str,
},
#[error(transparent)]
NodeNameError(#[from] crate::node::NodeNameError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[cfg(test)]
mod tests {
use super::*;
use futures::StreamExt;
#[test]
fn client_side_handshake_works() {
let peer_name = "client_side_handshake_works";
smol::block_on(async {
let erl_node = crate::tests::TestErlangNode::new(peer_name)
.await
.expect("failed to run a test erlang node");
let peer_entry = crate::tests::epmd_client()
.await
.get_node(peer_name)
.await
.expect("failed to get node");
let peer_entry = peer_entry.expect("no such node");
let connection = smol::net::TcpStream::connect(("localhost", peer_entry.port))
.await
.expect("failed to connect");
let local_node = LocalNode::new("foo@localhost".parse().unwrap(), Creation::random());
let mut handshake =
ClientSideHandshake::new(connection, local_node, crate::tests::COOKIE);
let status = handshake
.execute_send_name(crate::LOWEST_DISTRIBUTION_PROTOCOL_VERSION)
.await
.expect("failed to execute send name");
assert_eq!(status, HandshakeStatus::Ok);
let (_, peer_node) = handshake
.execute_rest(true)
.await
.expect("failed to execute handshake");
assert_eq!(peer_entry.name, peer_node.name.name());
std::mem::drop(erl_node);
});
}
#[test]
fn server_side_handshake_works() {
smol::block_on(async {
let listener = smol::net::TcpListener::bind("0.0.0.0:0").await.unwrap();
let listening_port = listener.local_addr().unwrap().port();
let (tx, rx) = futures::channel::oneshot::channel();
let connection = smol::net::TcpStream::connect(("localhost", listening_port))
.await
.unwrap();
smol::spawn(async move {
let local_node =
LocalNode::new("foo@localhost".parse().unwrap(), Creation::random());
let mut handshake =
ClientSideHandshake::new(connection, local_node, crate::tests::COOKIE);
let _status = handshake
.execute_send_name(crate::LOWEST_DISTRIBUTION_PROTOCOL_VERSION)
.await
.unwrap();
let (connection, _) = handshake.execute_rest(true).await.unwrap();
let _ = tx.send(connection);
})
.detach();
let mut incoming = listener.incoming();
if let Some(connection) = incoming.next().await {
let local_node =
LocalNode::new("bar@localhost".parse().unwrap(), Creation::random());
let mut handshake =
ServerSideHandshake::new(connection.unwrap(), local_node, crate::tests::COOKIE);
let peer_name = handshake.execute_recv_name().await.unwrap();
assert!(peer_name.is_some());
handshake.execute_rest(HandshakeStatus::Ok).await.unwrap();
}
let _ = rx.await;
})
}
}