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
// standard
#[cfg(test)]
use std::net::{SocketAddr, TcpListener, TcpStream};

// extern crates
#[cfg(test)]
use bson::doc;
use data_encoding::HEXLOWER;
#[cfg(test)]
use honk_rpc::honk_rpc::Session;
use num_enum::TryFromPrimitive;
use tor_interface::tor_crypto::*;

// internal crates
use crate::ascii_string::*;
#[cfg(test)]
use crate::endpoint_client::*;
#[cfg(test)]
use crate::endpoint_server::*;
#[cfg(test)]
use crate::identity_client::*;
#[cfg(test)]
use crate::identity_server::*;

#[derive(Debug, Eq, PartialEq, TryFromPrimitive)]
#[repr(i32)]
/// cbindgen:ignore
pub(crate) enum RpcError {
    // bad gosling version
    BadVersion,
    // cookie required
    RequestCookieRequired,
    // invalid or missing arguments
    InvalidArg,
    // generic runtime error
    Failure,
}

pub(crate) const GOSLING_PROTOCOL_VERSION: &str = "0.1.0";

pub(crate) const CLIENT_COOKIE_SIZE: usize = 32usize;
pub(crate) const SERVER_COOKIE_SIZE: usize = 32usize;

pub(crate) type ClientCookie = [u8; CLIENT_COOKIE_SIZE];
pub(crate) type ServerCookie = [u8; SERVER_COOKIE_SIZE];
pub(crate) type ClientProof = Vec<u8>;

pub(crate) enum DomainSeparator {
    GoslingIdentity,
    GoslingEndpoint,
}

impl From<DomainSeparator> for &[u8] {
    fn from(sep: DomainSeparator) -> &'static [u8] {
        match sep {
            DomainSeparator::GoslingIdentity => b"gosling-identity",
            DomainSeparator::GoslingEndpoint => b"gosling-endpoint",
        }
    }
}

pub(crate) fn build_client_proof(
    domain_separator: DomainSeparator,
    request: &AsciiString,
    client_service_id: &V3OnionServiceId,
    server_service_id: &V3OnionServiceId,
    client_cookie: &ClientCookie,
    server_cookie: &ServerCookie,
) -> ClientProof {
    let mut client_proof: ClientProof = Default::default();

    client_proof.extend_from_slice(domain_separator.into());
    client_proof.push(0u8);
    client_proof.extend_from_slice(request.as_bytes());
    client_proof.push(0u8);
    client_proof.extend_from_slice(client_service_id.to_string().as_bytes());
    client_proof.push(0u8);
    client_proof.extend_from_slice(server_service_id.to_string().as_bytes());
    client_proof.push(0u8);
    client_proof.extend_from_slice(HEXLOWER.encode(client_cookie).as_bytes());
    client_proof.push(0u8);
    client_proof.extend_from_slice(HEXLOWER.encode(server_cookie).as_bytes());

    client_proof
}

//
// Tests
//

#[cfg(test)]
fn identity_test(
    client_blocked: bool,
    client_requested_endpoint: &str,
    client_requested_endpoint_valid: bool,
    server_challenge: bson::document::Document,
    client_response: bson::document::Document,
    server_expected_response: bson::document::Document,
    should_fail: bool,
) -> anyhow::Result<()> {
    // test sockets
    let socket_addr = SocketAddr::from(([127, 0, 0, 1], 0u16));
    let listener = TcpListener::bind(socket_addr)?;
    let socket_addr = listener.local_addr()?;

    let stream1 = TcpStream::connect(socket_addr)?;
    stream1.set_nonblocking(true)?;
    let (stream2, _socket_addr) = listener.accept()?;
    stream2.set_nonblocking(true)?;

    // client setup
    let client_ed25519_private = Ed25519PrivateKey::generate();

    // server setup
    let server_ed25519_private = Ed25519PrivateKey::generate();
    let server_ed25519_public = Ed25519PublicKey::from_private_key(&server_ed25519_private);
    let server_service_id = V3OnionServiceId::from_public_key(&server_ed25519_public);

    let client_requested_endpoint = match AsciiString::new(client_requested_endpoint.to_string()) {
        Ok(ascii) => ascii,
        Err(_) => {
            assert!(should_fail);
            return Ok(());
        }
    };

    // rpc setup
    let client_rpc = Session::new(stream1);
    let mut ident_client = IdentityClient::new(
        client_rpc,
        server_service_id.clone(),
        client_requested_endpoint.clone(),
        client_ed25519_private,
        X25519PrivateKey::generate(),
    )
    .unwrap();

    let server_rpc = Session::new(stream2);
    let mut ident_server = IdentityServer::new(server_rpc, server_service_id.clone());

    let mut failure_ocurred = false;
    let mut server_complete = false;
    let mut client_complete = false;
    while !server_complete && !client_complete {
        if !server_complete {
            match ident_server.update() {
                Ok(Some(IdentityServerEvent::EndpointRequestReceived {
                    client_service_id,
                    requested_endpoint,
                })) => {
                    println!(
                        "server challenge send: client_service_id {}, requested_endpoint: {}",
                        client_service_id.to_string(),
                        requested_endpoint
                    );
                    let client_allowed = !client_blocked;
                    ident_server.handle_endpoint_request_received(
                        client_allowed,
                        client_requested_endpoint_valid,
                        server_challenge.clone(),
                    )?;
                }
                Ok(Some(IdentityServerEvent::ChallengeResponseReceived { challenge_response })) => {
                    println!("server challenge repsonse received");
                    ident_server.handle_challenge_response_received(
                        challenge_response == server_expected_response,
                    )?;
                }
                Ok(Some(IdentityServerEvent::HandshakeCompleted {
                    endpoint_private_key: _,
                    endpoint_name,
                    client_service_id,
                    client_auth_public_key: _,
                })) => {
                    assert!(endpoint_name == client_requested_endpoint);
                    println!(
                        "server complete! client_service_id : {}",
                        client_service_id.to_string()
                    );
                    server_complete = true;
                }
                Ok(Some(IdentityServerEvent::HandshakeRejected {
                    client_allowed,
                    client_requested_endpoint_valid,
                    client_proof_signature_valid,
                    client_auth_signature_valid,
                    challenge_response_valid,
                })) => {
                    println!("server complete! client request rejected");
                    println!(" client_allowed: {}", client_allowed);
                    println!(
                        " client_requested_endpoint_valid: {}",
                        client_requested_endpoint_valid
                    );
                    println!(
                        " client_proof_signature_valid: {}",
                        client_proof_signature_valid
                    );
                    println!(
                        " client_auth_signature_valid: {}",
                        client_auth_signature_valid
                    );
                    println!(" client_response_valid: {}", challenge_response_valid);
                    server_complete = true;
                    failure_ocurred = true;
                }
                Ok(None) => {}
                Err(err) => {
                    println!("server failure: {:?}", err);
                    server_complete = true;
                    failure_ocurred = true;
                }
            }
        }

        if !client_complete {
            match ident_client.update() {
                Ok(Some(IdentityClientEvent::ChallengeReceived { endpoint_challenge })) => {
                    println!(
                        "client challenge request received: endpoint_challenge: {}",
                        endpoint_challenge
                    );
                    ident_client.send_response(client_response.clone())?;
                }
                Ok(Some(IdentityClientEvent::HandshakeCompleted {
                    identity_service_id,
                    endpoint_service_id,
                    endpoint_name,
                    client_auth_private_key: _,
                })) => {
                    assert!(identity_service_id == server_service_id);
                    assert!(endpoint_name == client_requested_endpoint.clone().to_string());
                    println!(
                        "client complete! endpoint_server : {}",
                        endpoint_service_id.to_string()
                    );
                    client_complete = true;
                }
                Ok(None) => {}
                Err(err) => {
                    println!("client failure: {:?}", err);
                    client_complete = true;
                    failure_ocurred = true;
                }
            }
        }
    }

    assert!(failure_ocurred == should_fail);
    Ok(())
}

#[test]
fn test_identity_handshake() -> anyhow::Result<()> {
    println!("Sucessful ---");
    {
        let client_blocked: bool = false;
        let client_requested_endpoint: &str = "endpoint";
        let client_requested_endpoint_valid: bool = true;
        let server_challenge: bson::document::Document = doc!("msg": "Speak friend and enter");
        let client_response: bson::document::Document = doc!("msg": "Mellon");
        let server_expected_response: bson::document::Document = doc!("msg": "Mellon");
        let should_fail: bool = false;
        identity_test(
            client_blocked,
            client_requested_endpoint,
            client_requested_endpoint_valid,
            server_challenge,
            client_response,
            server_expected_response,
            should_fail,
        )?;
    }
    println!("Bad Endpoint ---");
    {
        let client_blocked: bool = false;
        let client_requested_endpoint: &str = "endpoint";
        let client_requested_endpoint_valid: bool = false;
        let server_challenge: bson::document::Document = doc!("msg": "Speak friend and enter");
        let client_response: bson::document::Document = doc!("msg": "Mellon");
        let server_expected_response: bson::document::Document = doc!("msg": "Mellon");
        let should_fail: bool = true;
        identity_test(
            client_blocked,
            client_requested_endpoint,
            client_requested_endpoint_valid,
            server_challenge,
            client_response,
            server_expected_response,
            should_fail,
        )?;
    }
    println!("Bad Challenge Response ---");
    {
        let client_blocked: bool = false;
        let client_requested_endpoint: &str = "endpoint";
        let client_requested_endpoint_valid: bool = true;
        let server_challenge: bson::document::Document = doc!("msg": "Speak friend and enter");
        let client_response: bson::document::Document = doc!("msg": "Friend?");
        let server_expected_response: bson::document::Document = doc!("msg": "Mellon");
        let should_fail: bool = true;
        identity_test(
            client_blocked,
            client_requested_endpoint,
            client_requested_endpoint_valid,
            server_challenge,
            client_response,
            server_expected_response,
            should_fail,
        )?;
    }
    println!("Blocked Client ---");
    {
        let client_blocked: bool = true;
        let client_requested_endpoint: &str = "endpoint";
        let client_requested_endpoint_valid: bool = true;
        let server_challenge: bson::document::Document = doc!("msg": "Speak friend and enter");
        let client_response: bson::document::Document = doc!("msg": "Mellon");
        let server_expected_response: bson::document::Document = doc!("msg": "Mellon");
        let should_fail: bool = true;
        identity_test(
            client_blocked,
            client_requested_endpoint,
            client_requested_endpoint_valid,
            server_challenge,
            client_response,
            server_expected_response,
            should_fail,
        )?;
    }
    println!("Non-ASCII endpoint ---");
    {
        let client_blocked: bool = false;
        let client_requested_endpoint: &str = "𝕦𝕥𝕗𝟠";
        let client_requested_endpoint_valid: bool = true;
        let server_challenge: bson::document::Document = doc!("msg": "Speak friend and enter");
        let client_response: bson::document::Document = doc!("msg": "Mellon");
        let server_expected_response: bson::document::Document = doc!("msg": "Mellon");
        let should_fail: bool = true;
        identity_test(
            client_blocked,
            client_requested_endpoint,
            client_requested_endpoint_valid,
            server_challenge,
            client_response,
            server_expected_response,
            should_fail,
        )?;
    }
    Ok(())
}

#[cfg(test)]
fn endpoint_test(
    should_fail: bool,
    client_allowed: bool,
    channel: &str,
    channel_allowed: bool,
) -> anyhow::Result<()> {
    // test sockets
    let socket_addr = SocketAddr::from(([127, 0, 0, 1], 0u16));
    let listener = TcpListener::bind(socket_addr)?;
    let socket_addr = listener.local_addr()?;

    let stream1 = TcpStream::connect(socket_addr)?;
    stream1.set_nonblocking(true)?;
    let (stream2, _socket_addr) = listener.accept()?;
    stream2.set_nonblocking(true)?;

    // server+client setup
    let server_ed25519_private = Ed25519PrivateKey::generate();
    let server_ed25519_public = Ed25519PublicKey::from_private_key(&server_ed25519_private);
    let server_service_id = V3OnionServiceId::from_public_key(&server_ed25519_public);

    let client_ed25519_private = Ed25519PrivateKey::generate();
    let client_ed25519_public = Ed25519PublicKey::from_private_key(&client_ed25519_private);
    let client_service_id = V3OnionServiceId::from_public_key(&client_ed25519_public);

    // ensure our client is in the allow list
    let allowed_client = if client_allowed {
        client_service_id.clone()
    } else {
        let ed25519_private = Ed25519PrivateKey::generate();
        let ed25519_public = Ed25519PublicKey::from_private_key(&ed25519_private);
        V3OnionServiceId::from_public_key(&ed25519_public)
    };

    let server_rpc = Session::new(stream1);

    let mut endpoint_server = EndpointServer::new(
        server_rpc,
        allowed_client.clone(),
        server_service_id.clone(),
    );

    let client_rpc = Session::new(stream2);

    let channel = match AsciiString::new(channel.to_string()) {
        Ok(channel) => channel,
        Err(_) => {
            assert!(should_fail);
            return Ok(());
        }
    };

    let mut endpoint_client = EndpointClient::new(
        client_rpc,
        server_service_id.clone(),
        channel.clone(),
        client_ed25519_private,
    );

    let mut failure_ocurred = false;
    let mut server_complete = false;
    let mut client_complete = false;
    while !server_complete && !client_complete {
        if !server_complete {
            match endpoint_server.update() {
                Ok(Some(EndpointServerEvent::ChannelRequestReceived {
                    client_service_id: ret_client_service_id,
                    requested_channel,
                })) => {
                    assert_eq!(ret_client_service_id, client_service_id);
                    assert!(requested_channel == channel);
                    endpoint_server.handle_channel_request_received(channel_allowed)?;
                }
                Ok(Some(EndpointServerEvent::HandshakeCompleted {
                    client_service_id: ret_client_service_id,
                    channel_name: ret_channel,
                    stream: _,
                })) => {
                    assert!(ret_client_service_id == client_service_id);
                    assert!(ret_channel == channel);
                    server_complete = true;
                }
                Ok(Some(EndpointServerEvent::HandshakeRejected {
                    client_allowed,
                    client_requested_channel_valid,
                    client_proof_signature_valid,
                })) => {
                    println!("handshake rejected: client_allowed: {}, client_requested_channel_valid: {}, client_proof_signature_valid: {}", client_allowed, client_requested_channel_valid, client_proof_signature_valid);
                    server_complete = true;
                    failure_ocurred = true;
                }
                Ok(None) => {}
                Err(err) => {
                    println!("server failure: {:?}", err);
                    server_complete = true;
                    failure_ocurred = true;
                }
            }
        }

        if !client_complete {
            match endpoint_client.update() {
                Ok(Some(EndpointClientEvent::HandshakeCompleted { stream: _ })) => {
                    client_complete = true;
                }
                Ok(None) => {}
                Err(err) => {
                    println!("client failure: {:?}", err);
                    client_complete = true;
                    failure_ocurred = true;
                }
            }
        }
    }

    println!("server_complete: {}", server_complete);
    println!("client_complete: {}", client_complete);

    assert!(should_fail == failure_ocurred);

    Ok(())
}

#[test]
fn test_endpoint_handshake() -> anyhow::Result<()> {
    println!("Success ---");
    {
        let should_fail = false;
        let client_allowed = true;
        let channel = "channel";
        let channel_allowed = true;
        endpoint_test(should_fail, client_allowed, channel, channel_allowed)?;
    }
    println!("Client Not Allowed ---");
    {
        let should_fail = true;
        let client_allowed = false;
        let channel = "channel";
        let channel_allowed = true;
        endpoint_test(should_fail, client_allowed, channel, channel_allowed)?;
    }
    println!("Channel Not Allowed ---");
    {
        let should_fail = true;
        let client_allowed = true;
        let channel = "channel";
        let channel_allowed = false;
        endpoint_test(should_fail, client_allowed, channel, channel_allowed)?;
    }
    println!("Client and Channel Not Allowed ---");
    {
        let should_fail = true;
        let client_allowed = false;
        let channel = "channel";
        let channel_allowed = false;
        endpoint_test(should_fail, client_allowed, channel, channel_allowed)?;
    }
    println!("Non-Ascii Channel ---");
    {
        let should_fail = true;
        let client_allowed = true;
        let channel = "𝕦𝕥𝕗𝟠";
        let channel_allowed = true;
        endpoint_test(should_fail, client_allowed, channel, channel_allowed)?;
    }

    Ok(())
}