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
// standard
use std::clone::Clone;
use std::convert::TryInto;
use std::net::TcpStream;

// extern crates
use bson::doc;
use bson::spec::BinarySubtype;
use bson::{Binary, Bson};
use honk_rpc::honk_rpc::{ApiSet, ErrorCode, RequestCookie, Session};
use rand::rngs::OsRng;
use rand::RngCore;
use tor_interface::tor_crypto::*;

// internal crates
use crate::ascii_string::*;
use crate::gosling::*;

//
// Endpoint Server
//

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("HonkRPC method failed: {0}")]
    HonkRPCFailure(#[from] honk_rpc::honk_rpc::Error),

    #[error("server is in invalid state: {0}")]
    InvalidState(String),

    #[error("incorrect usage: {0}")]
    IncorrectUsage(String),

    #[error("client sent invalid request")]
    BadClient,
}

pub(crate) enum EndpointServerEvent {
    ChannelRequestReceived {
        client_service_id: V3OnionServiceId,
        requested_channel: AsciiString,
    },
    // endpoint server has acepted incoming channel request from identity client
    HandshakeCompleted {
        client_service_id: V3OnionServiceId,
        channel_name: AsciiString,
        stream: TcpStream,
    },
    // endpoint server has reject an incoming channel request
    HandshakeRejected {
        client_allowed: bool,
        client_requested_channel_valid: bool,
        client_proof_signature_valid: bool,
    },
}

#[derive(Debug, PartialEq)]
enum EndpointServerState {
    // valid/expected states
    WaitingForBeginHandshake,
    ValidatingChannelRequest,
    ChannelRequestValidated,
    WaitingForSendResponse,
    HandledSendResponse,
    HandshakeComplete,
    // failure state
    HandshakeFailed,
}

pub(crate) struct EndpointServer {
    // Session Data
    rpc: Option<Session<TcpStream>>,
    pub server_identity: V3OnionServiceId,
    allowed_client_identity: V3OnionServiceId,

    // State Machine Data
    state: EndpointServerState,
    begin_handshake_request_cookie: Option<RequestCookie>,
    client_identity: Option<V3OnionServiceId>,
    requested_channel: Option<AsciiString>,
    server_cookie: Option<ServerCookie>,
    handshake_succeeded: Option<bool>,

    // Verification flags

    // Client not on the block-list
    client_allowed: bool,
    // The requested endpoint is valid
    client_requested_channel_valid: bool,
    // The client proof is valid and signed with client's public key
    client_proof_signature_valid: bool,
}

impl EndpointServer {
    fn get_state(&self) -> String {
        format!("{{ state: {:?}, begin_handshake_request_cookie: {:?}, client_identity: {:?}, requested_channel: {:?}, server_cookie: {:?}, handshake_succeeded:{:?} }}", self.state, self.begin_handshake_request_cookie, self.client_identity, self.requested_channel, self.server_cookie, self.handshake_succeeded)
    }

    pub fn new(
        rpc: Session<TcpStream>,
        client_identity: V3OnionServiceId,
        server_identity: V3OnionServiceId,
    ) -> Self {
        // generate server cookie
        let mut server_cookie: ServerCookie = Default::default();
        OsRng.fill_bytes(&mut server_cookie);

        EndpointServer {
            rpc: Some(rpc),
            server_identity,
            allowed_client_identity: client_identity,
            state: EndpointServerState::WaitingForBeginHandshake,
            begin_handshake_request_cookie: None,
            requested_channel: None,
            client_identity: None,
            server_cookie: None,
            handshake_succeeded: None,
            client_allowed: false,
            // TODO: hookup this to event and callback
            client_requested_channel_valid: true,
            client_proof_signature_valid: false,
        }
    }

    pub fn update(&mut self) -> Result<Option<EndpointServerEvent>, Error> {
        if let Some(mut rpc) = std::mem::take(&mut self.rpc) {
            match rpc.update(Some(&mut [self])) {
                Ok(()) => {
                    self.rpc = Some(rpc);
                }
                Err(err) => {
                    self.rpc = Some(rpc);
                    return Err(err.into());
                }
            }
        }

        match(&self.state,
              self.begin_handshake_request_cookie,
              self.client_identity.as_ref(),
              self.requested_channel.as_ref(),
              self.server_cookie.as_ref(),
              self.handshake_succeeded) {
            (&EndpointServerState::WaitingForBeginHandshake,
             None, // begin_handshake_request_cookie
             None, // client_identity
             None, // requested_channel
             None, // server_cookie
             None) // handshake_succeeded
            => {},
            (&EndpointServerState::WaitingForBeginHandshake,
             Some(_begin_handshake_request_cookie),
             Some(client_identity),
             Some(requested_channel),
             None, // server_cookie
             None) // handshake_succeeded
            => {
                self.state = EndpointServerState::ValidatingChannelRequest;
                return Ok(
                        Some(
                            EndpointServerEvent::ChannelRequestReceived
                            {
                                client_service_id: client_identity.clone(),
                                requested_channel: requested_channel.clone()
                            }));
            },
            (&EndpointServerState::ValidatingChannelRequest,
             Some(_begin_handshake_request_cookie),
             Some(_client_identity),
             Some(_requested_channel),
             None, // server_cookie
             None) // handshake_succeeded
            => {},
            (&EndpointServerState::ChannelRequestValidated,
             Some(_begin_handshake_request_cookie),
             Some(_client_identity),
             Some(_requested_channel),
             Some(_server_cookie),
             None) // handshake_succeeded
            => {},
            (&EndpointServerState::WaitingForSendResponse,
             Some(_begin_handshake_request_cookie),
             Some(_client_identity),
             Some(_requested_channel),
             Some(_server_cookie),
             None) // handshake_succeeded
            => {},
            (&EndpointServerState::HandledSendResponse,
             Some(_begin_handshake_request_cookie),
             Some(client_identity),
             Some(requested_channel),
             Some(_server_cookie),
             Some(handshake_succeeded))
            => {
                self.state = EndpointServerState::HandshakeComplete;
                if handshake_succeeded {
                    let stream = std::mem::take(&mut self.rpc).unwrap().into_stream();
                    return Ok(Some(EndpointServerEvent::HandshakeCompleted{
                        client_service_id: client_identity.clone(),
                        channel_name: requested_channel.clone(),
                        stream}));
                } else {
                    return Ok(Some(EndpointServerEvent::HandshakeRejected{
                        client_allowed: self.client_allowed,
                        client_requested_channel_valid: self.client_requested_channel_valid,
                        client_proof_signature_valid: self.client_proof_signature_valid}));
                }
            },
            _ => {
                if self.state == EndpointServerState::HandshakeFailed {
                    return Err(Error::BadClient);
                } else {
                    return Err(Error::InvalidState(self.get_state()));
                }
            }
        }

        Ok(None)
    }

    pub fn handle_channel_request_received(
        &mut self,
        client_requested_channel_valid: bool,
    ) -> Result<(), Error> {
        match(&self.state,
              self.begin_handshake_request_cookie,
              self.client_identity.as_ref(),
              self.requested_channel.as_ref(),
              self.server_cookie.as_ref(),
              self.handshake_succeeded) {
            (&EndpointServerState::ValidatingChannelRequest,
             Some(_begin_handshake_request_cookie),
             Some(client_identity),
             Some(_requested_channel),
             None, // server_cookie
             None) // handshake_succeeded
            => {
                let mut server_cookie: ServerCookie = Default::default();
                OsRng.fill_bytes(&mut server_cookie);
                self.server_cookie = Some(server_cookie);
                self.client_allowed = *client_identity == self.allowed_client_identity;
                self.client_requested_channel_valid = client_requested_channel_valid;
                self.state = EndpointServerState::ChannelRequestValidated;
                Ok(())
            },
            _ => Err(Error::IncorrectUsage("handle_channel_request_received() may only be called after ChannelRequestReceived has been returned from update(), and it may only be called once".to_string()))
        }
    }
}

impl ApiSet for EndpointServer {
    fn namespace(&self) -> &str {
        "gosling_endpoint"
    }

    fn exec_function(
        &mut self,
        name: &str,
        version: i32,
        mut args: bson::document::Document,
        request_cookie: Option<RequestCookie>,
    ) -> Option<Result<Option<bson::Bson>, ErrorCode>> {
        let request_cookie = match request_cookie {
            Some(request_cookie) => request_cookie,
            None => {
                return Some(Err(ErrorCode::Runtime(
                    RpcError::RequestCookieRequired as i32,
                )))
            }
        };

        match
            (name, version,
             &self.state,
             self.client_identity.as_ref(),
             self.requested_channel.as_ref(),
             self.server_cookie.as_ref()) {
            // handle begin_handshake call
            ("begin_handshake", 0,
            &EndpointServerState::WaitingForBeginHandshake,
            None, // client_identity
            None, // requested_channel
            None) // server_cookie
            => {
                let valid_version = match args.remove("version") {
                    Some(Bson::String(value)) => value == GOSLING_PROTOCOL_VERSION,
                    _ => false,
                };
                if !valid_version {
                    self.state = EndpointServerState::HandshakeFailed;
                    return Some(Err(ErrorCode::Runtime(RpcError::BadVersion as i32)));
                }

                if let (
                    Some(Bson::String(client_identity)),
                    Some(Bson::String(channel_name))
                ) = (
                    args.remove("client_identity"),
                    args.remove("channel")
                ) {
                    // client_identiity
                    self.client_identity = match V3OnionServiceId::from_string(&client_identity) {
                        Ok(client_identity) => Some(client_identity),
                        Err(_) => {
                            self.state = EndpointServerState::HandshakeFailed;
                            return Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)));
                        }
                    };

                    let channel_name = match AsciiString::new(channel_name) {
                        Ok(channel_name) => channel_name,
                        Err(_) => {
                            self.state = EndpointServerState::HandshakeFailed;
                            return Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)));
                        }
                    };

                    // save cookie
                    self.begin_handshake_request_cookie = Some(request_cookie);

                    // save channel name
                    self.requested_channel = Some(channel_name);

                    None
                } else {
                    self.state = EndpointServerState::HandshakeFailed;
                    Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)))
                }
            },
            ("send_response", 0,
            &EndpointServerState::WaitingForSendResponse,
            Some(client_identity),
            Some(requested_channel),
            Some(server_cookie))
            => {
                if let (Some(Bson::Binary(Binary{subtype: BinarySubtype::Generic, bytes: client_cookie})),
                        Some(Bson::Binary(Binary{subtype: BinarySubtype::Generic, bytes: client_identity_proof_signature}))) =
                       (args.remove("client_cookie"),
                        args.remove("client_identity_proof_signature")) {
                    // client_cookie
                    let client_cookie : ClientCookie = match client_cookie.try_into() {
                        Ok(client_cookie) => client_cookie,
                        Err(_) => {
                            self.state = EndpointServerState::HandshakeFailed;
                            return Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)));
                        }
                    };

                    // client_identity_proof_signature
                    let client_identity_proof_signature : [u8; ED25519_SIGNATURE_SIZE] = match client_identity_proof_signature.try_into() {
                        Ok(client_identity_proof_signature) => client_identity_proof_signature,
                        Err(_) => {
                            self.state = EndpointServerState::HandshakeFailed;
                            return Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)));
                        }
                    };
                    let client_identity_proof_signature = match Ed25519Signature::from_raw(&client_identity_proof_signature) {
                        Ok(client_identity_proof_signature) => client_identity_proof_signature,
                        Err(_) => {
                            self.state = EndpointServerState::HandshakeFailed;
                            return Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)));
                        }
                    };

                    // convert client_identity to client's public ed25519 key
                    let client_identity_key = match Ed25519PublicKey::from_service_id(client_identity) {
                        Ok(client_identity_key) => client_identity_key,
                        Err(_) => {
                            self.state = EndpointServerState::HandshakeFailed;
                            return Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)));
                        }
                    };

                    // construct + verify client proof
                    let client_proof = build_client_proof(
                        DomainSeparator::GoslingEndpoint,
                        requested_channel,
                        client_identity,
                        &self.server_identity,
                        &client_cookie,
                        server_cookie,
                    );
                    self.client_proof_signature_valid =
                        client_identity_proof_signature.verify(&client_proof, &client_identity_key);

                    if self.client_allowed
                        && self.client_requested_channel_valid
                        && self.client_proof_signature_valid
                    {
                        self.handshake_succeeded = Some(true);
                        self.state = EndpointServerState::HandledSendResponse;
                        // success, return empty doc
                        Some(Ok(Some(Bson::Document(doc! {}))))
                    } else {
                        self.handshake_succeeded = Some(false);
                        self.state = EndpointServerState::HandledSendResponse;
                        Some(Err(ErrorCode::Runtime(RpcError::Failure as i32)))
                    }
                } else {
                    self.state = EndpointServerState::HandshakeFailed;
                    Some(Err(ErrorCode::Runtime(RpcError::InvalidArg as i32)))
                }
            },
            _ => {
                self.state = EndpointServerState::HandshakeFailed;
                Some(Err(ErrorCode::Runtime(RpcError::Failure as i32)))
            }
        }
    }

    fn next_result(&mut self) -> Option<(RequestCookie, Result<Option<bson::Bson>, ErrorCode>)> {
        match (
            &self.state,
            self.begin_handshake_request_cookie,
            self.server_cookie.as_ref(),
        ) {
            (
                &EndpointServerState::ChannelRequestValidated,
                Some(begin_handshake_request_cookie),
                Some(server_cookie),
            ) => {
                self.state = EndpointServerState::WaitingForSendResponse;
                Some((
                    begin_handshake_request_cookie,
                    Ok(Some(Bson::Document(doc! {
                        "server_cookie" : Bson::Binary(Binary{subtype: BinarySubtype::Generic, bytes: server_cookie.to_vec()}),
                    }))),
                ))
            }
            _ => None,
        }
    }
}