netget-tool 0.3.4

Network protocol stubbing toolkit: ~280 protocol servers and clients whose responses come from an LLM, a script, a static rule or a person.
Documentation
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
pub mod actions;
pub mod codec;
use crate::llm::actions::protocol_trait::ActionResult;
use crate::logging::emit::Log;
use crate::protocol::{Event, SpawnContext};
use crate::server::{
    accept_bounded::{accept_bounded, ConnectionLimiter, DEFAULT_MAX_CONNECTIONS},
    connection::ConnectionId,
};
use crate::state::{
    server::{ConnectionState, ConnectionStatus, ProtocolConnectionInfo},
    AccessLogOwner,
};
use anyhow::{bail, ensure, Context, Result};
use codec::*;
use serde::Deserialize;
use serde_json::{json, Value};
use std::{
    collections::BTreeMap,
    net::{IpAddr, SocketAddr},
    sync::Arc,
    time::Duration,
};
use tokio::{
    io::AsyncWriteExt,
    net::{
        tcp::{OwnedReadHalf, OwnedWriteHalf},
        TcpListener, TcpStream,
    },
};
struct Config {
    secret: Vec<u8>,
    overrides: BTreeMap<IpAddr, Vec<u8>>,
    io_timeout: Duration,
    handler_timeout: Duration,
    llm_fallback: bool,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ClientSecret {
    client_ip: IpAddr,
    shared_secret: String,
}
pub fn timeout(value: Option<u64>, default: u64) -> Result<Duration> {
    let seconds = value.unwrap_or(default);
    ensure!((1..=300).contains(&seconds), "timeout1..300seconds");
    Ok(Duration::from_secs(seconds))
}
pub struct TacacsServer;
impl TacacsServer {
    pub async fn spawn(mut ctx: SpawnContext) -> Result<SocketAddr> {
        let params = ctx
            .startup_params
            .as_ref()
            .context("TACACS shared_secret required")?;
        let secret = params.get_string("shared_secret")?;
        validate_secret(&secret)?;
        let mut overrides = BTreeMap::new();
        if let Some(values) = params.get_optional_array("client_secrets")? {
            ensure!(values.len() <= 64, "client secret capacity64");
            for value in values {
                ensure!(within_json_budget(value), "client secret JSON budget");
                let c: ClientSecret = serde_json::from_value(value.clone())?;
                validate_secret(&c.shared_secret)?;
                ensure!(
                    overrides
                        .insert(c.client_ip, c.shared_secret.into_bytes())
                        .is_none(),
                    "duplicate client IP secret"
                );
            }
        }
        let config = Arc::new(Config {
            secret: secret.into_bytes(),
            overrides,
            io_timeout: timeout(
                params.get_optional_u64("io_timeout_seconds")?,
                DEFAULT_IO_SECONDS,
            )?,
            handler_timeout: timeout(
                params.get_optional_u64("handler_timeout_seconds")?,
                DEFAULT_HANDLER_SECONDS,
            )?,
            llm_fallback: params
                .get_optional_bool("llm_fallback")?
                .unwrap_or(DEFAULT_LLM_FALLBACK),
        });
        ctx.startup_params = None;
        let listener = TcpListener::bind(
            ctx.socket_addr()
                .context("TACACS TCP bind address required")?,
        )
        .await?;
        let local = listener.local_addr()?;
        let state = ctx.state.clone();
        let sid = ctx.server_id;
        Log::new(Some(&ctx.status_tx)).info(format!("TACACS legacy listening on {local}"));
        state
            .clone()
            .spawn_server_task(sid, async move {
                let limiter = ConnectionLimiter::new(DEFAULT_MAX_CONNECTIONS);
                loop {
                    let (socket, peer, permit) = match accept_bounded(
                        &listener,
                        &limiter,
                        b"",
                        "TACACS",
                        Some(&ctx.status_tx),
                    )
                    .await
                    {
                        Ok(v) => v,
                        Err(_) => break,
                    };
                    let cid = ConnectionId::new(ctx.state.get_next_unified_id().await);
                    let now = crate::utils::clock::Instant::now();
                    ctx.state
                        .add_connection_to_server(
                            sid,
                            ConnectionState {
                                id: cid,
                                remote_addr: peer,
                                local_addr: local,
                                bytes_sent: 0,
                                bytes_received: 0,
                                packets_sent: 0,
                                packets_received: 0,
                                last_activity: now,
                                status: ConnectionStatus::Active,
                                status_changed_at: now,
                                protocol_info: ProtocolConnectionInfo::empty(),
                            },
                        )
                        .await;
                    let child = ctx.clone();
                    let cfg = config.clone();
                    ctx.state
                        .spawn_server_task(sid, async move {
                            let _permit = permit;
                            let secret = cfg.overrides.get(&peer.ip()).unwrap_or(&cfg.secret);
                            if session(&child, cid, socket, peer, secret, &cfg)
                                .await
                                .is_err()
                            {
                                decision(&child, cid, "fail_closed_session_error");
                            }
                            child
                                .state
                                .update_connection_status(sid, cid, ConnectionStatus::Closed)
                                .await;
                            child.state.remove_connection_from_server(sid, cid).await;
                            let _ = child.status_tx.send("__UPDATE_UI__".into());
                        })
                        .await;
                }
            })
            .await;
        Ok(local)
    }
}
fn decision(ctx: &SpawnContext, id: ConnectionId, tag: &str) {
    Log::new(Some(&ctx.status_tx)).info(format!("TACACS connection={id} decision={tag}"));
}
async fn read(
    ctx: &SpawnContext,
    id: ConnectionId,
    r: &mut OwnedReadHalf,
    secret: &[u8],
    cfg: &Config,
) -> Result<(Header, Vec<u8>)> {
    let packet = read_packet(r, secret, cfg.io_timeout).await?;
    ctx.state
        .update_connection_stats(
            ctx.server_id,
            id,
            Some((12 + packet.0.length) as u64),
            None,
            Some(1),
            None,
        )
        .await;
    Ok(packet)
}
async fn send(
    ctx: &SpawnContext,
    id: ConnectionId,
    w: &mut OwnedWriteHalf,
    h: Header,
    body: &[u8],
    secret: &[u8],
) -> Result<()> {
    let n = write_packet(w, h, body, secret).await?;
    ctx.state
        .update_connection_stats(ctx.server_id, id, None, Some(n as u64), None, Some(1))
        .await;
    Ok(())
}
fn error_body(kind: u8) -> Result<Vec<u8>> {
    match kind {
        1 => auth_reply_body(&AuthReply {
            status: AuthStatus::Error,
            no_echo: false,
            server_message: "Request could not be processed".into(),
            data: String::new(),
        }),
        2 => author_reply_body(&AuthorReply {
            status: AuthorStatus::Error,
            arguments: vec![],
            server_message: "Request could not be processed".into(),
            data: String::new(),
        }),
        3 => account_reply_body(&AccountReply {
            status: AccountStatus::Error,
            server_message: "Request could not be recorded".into(),
            data: String::new(),
        }),
        _ => Ok(vec![]),
    }
}
async fn fail(
    ctx: &SpawnContext,
    id: ConnectionId,
    w: &mut OwnedWriteHalf,
    h: Header,
    secret: &[u8],
    tag: &str,
) -> Result<()> {
    decision(ctx, id, tag);
    if let Ok(mut reply) = h.reply() {
        if !matches!(h.kind, 1..=3) {
            // RFC8907 section3.6: mirror unknown-type header, advance sequence, zero body.
            reply.flags = h.flags;
        }
        let body = error_body(h.kind)?;
        send(ctx, id, w, reply, &body, secret).await?;
    }
    Ok(())
}
async fn continuation(
    ctx: &SpawnContext,
    id: ConnectionId,
    r: &mut OwnedReadHalf,
    w: &mut OwnedWriteHalf,
    secret: &[u8],
    cfg: &Config,
    h: Header,
    status: AuthStatus,
    message: &str,
) -> Result<(Header, Continue)> {
    let reply = h.reply()?;
    let body = auth_reply_body(&AuthReply {
        status,
        no_echo: status == AuthStatus::GetPass,
        server_message: message.into(),
        data: String::new(),
    })?;
    send(ctx, id, w, reply, &body, secret).await?;
    let (next, body) = read(ctx, id, r, secret, cfg).await?;
    let valid = next.validate().is_ok()
        && next.version == h.version
        && next.kind == 1
        && next.session_id == h.session_id
        && reply.sequence.checked_add(1) == Some(next.sequence);
    if !valid {
        fail(ctx, id, w, next, secret, "fail_closed_continuation_header").await?;
        bail!("authentication correlation");
    }
    let response = match parse_continue(&body) {
        Ok(response) => response,
        Err(_) => {
            fail(ctx, id, w, next, secret, "fail_closed_continuation_body").await?;
            bail!("authentication continuation body");
        }
    };
    Ok((next, response))
}
async fn handler(
    ctx: &SpawnContext,
    id: ConnectionId,
    r: &mut OwnedReadHalf,
    cfg: &Config,
    event: Event,
    expected: &str,
) -> Result<Option<Value>> {
    let configured = ctx
        .state
        .get_event_handler_config(ctx.server_id)
        .await
        .is_some_and(|c| c.find_handler(event.id()).is_some());
    if !configured && !cfg.llm_fallback {
        let event_id = event.id().to_owned();
        ctx.state
            .record_access_log(
                AccessLogOwner::Server(ctx.server_id.as_u32()),
                "TACACS",
                Some(id.as_u32()),
                &event_id,
                event.data,
                vec![],
            )
            .await;
        return Ok(None);
    }
    let mut peek = [0; 1];
    let result = tokio::select! {
        value = tokio::time::timeout(
            cfg.handler_timeout,
            crate::llm::action_helper::call_llm(&ctx.llm_client, &ctx.state, ctx.server_id,
                Some(id), &event, &actions::TacacsProtocol),
        ) => value.context("handler deadline")??,
        _ = r.peek(&mut peek) => bail!("Peer closed or sent unexpected data while handling"),
    };
    chosen_reply(result, expected)
}

/// Consume handler values iteratively, including rejected nested results. No copy or
/// serialization occurs until all JSON and result-count budgets have passed.
pub fn chosen_reply(
    result: crate::llm::actions::executor::ExecutionResult,
    expected: &str,
) -> Result<Option<Value>> {
    let mut invalid = !result.failures.is_empty() || result.raw_actions.len() > 32;
    for value in result.raw_actions {
        invalid |= !within_json_budget(&value);
        crate::utils::json_budget::drop_iteratively(value);
    }
    let mut pending = result.protocol_results;
    let mut found = None;
    let mut seen = 0usize;
    while let Some(result) = pending.pop() {
        seen = seen.saturating_add(1);
        invalid |= seen > 64;
        match result {
            ActionResult::Multiple(items) => pending.extend(items),
            ActionResult::Custom { name, data } => {
                if name == expected && found.is_none() && within_json_budget(&data) {
                    found = Some(data);
                } else {
                    invalid = true;
                    crate::utils::json_budget::drop_iteratively(data);
                }
            }
            ActionResult::NoAction => {}
            _ => invalid = true,
        }
    }
    if invalid {
        if let Some(value) = found {
            crate::utils::json_budget::drop_iteratively(value);
        }
        bail!("handler failure, reply type/count or JSON budget");
    }
    Ok(found)
}

async fn session(
    ctx: &SpawnContext,
    id: ConnectionId,
    socket: TcpStream,
    peer: SocketAddr,
    secret: &[u8],
    cfg: &Config,
) -> Result<()> {
    let (mut r, mut w) = socket.into_split();
    let (mut h, body) = read(ctx, id, &mut r, secret, cfg).await?;
    if h.validate().is_err() || h.sequence != 1 {
        fail(ctx, id, &mut w, h, secret, "fail_closed_header").await?;
        return Ok(());
    }
    match h.kind {
        1 => {
            let start = match parse_start(&body) {
                Ok(s) => s,
                Err(_) => {
                    fail(
                        ctx,
                        id,
                        &mut w,
                        h,
                        secret,
                        "fail_closed_authentication_body",
                    )
                    .await?;
                    return Ok(());
                }
            };
            let expected_version = if start.method == AuthType::Ascii {
                0xc0
            } else {
                0xc1
            };
            if h.version != expected_version {
                fail(
                    ctx,
                    id,
                    &mut w,
                    h,
                    secret,
                    "fail_closed_authentication_version",
                )
                .await?;
                return Ok(());
            }
            if start.action != 1
                || start.service != Service::Login
                || !matches!(start.method, AuthType::Ascii | AuthType::Pap)
            {
                let denied = auth_reply_body(&AuthReply {
                    status: AuthStatus::Fail,
                    no_echo: false,
                    server_message: "Authentication flow unsupported".into(),
                    data: String::new(),
                })?;
                send(ctx, id, &mut w, h.reply()?, &denied, secret).await?;
                decision(ctx, id, "unsupported_authentication_fail");
                return Ok(());
            }
            let mut user = start.username.clone();
            let password = if start.method == AuthType::Ascii {
                for _ in 0..3 {
                    if !user.is_empty() {
                        break;
                    }
                    let (next, value) = continuation(
                        ctx,
                        id,
                        &mut r,
                        &mut w,
                        secret,
                        cfg,
                        h,
                        AuthStatus::GetUser,
                        "Username:",
                    )
                    .await?;
                    h = next;
                    if value.abort {
                        decision(ctx, id, "client_abort");
                        return Ok(());
                    }
                    username(&value.user_message)?;
                    user = value.user_message;
                }
                if user.is_empty() {
                    let denied = auth_reply_body(&AuthReply {
                        status: AuthStatus::Fail,
                        no_echo: false,
                        server_message: "Username required".into(),
                        data: String::new(),
                    })?;
                    send(ctx, id, &mut w, h.reply()?, &denied, secret).await?;
                    decision(ctx, id, "username_retry_fail");
                    return Ok(());
                }
                let (next, value) = continuation(
                    ctx,
                    id,
                    &mut r,
                    &mut w,
                    secret,
                    cfg,
                    h,
                    AuthStatus::GetPass,
                    "Password:",
                )
                .await?;
                h = next;
                if value.abort {
                    decision(ctx, id, "client_abort");
                    return Ok(());
                }
                value.user_message
            } else {
                if user.is_empty() {
                    fail(ctx, id, &mut w, h, secret, "fail_closed_pap_username").await?;
                    return Ok(());
                }
                start.password.unwrap_or_default()
            };
            let event = Event::new(
                &actions::AUTH_EVENT,
                json!({"request":{"username":user,"password":password,"method":start.method,"privilege_level":start.privilege_level,"port":start.port,"remote_address":start.remote_address,"source_addr":peer.to_string(),"session_id":h.session_id}}),
            );
            let reply =
                match handler(ctx, id, &mut r, cfg, event, "respond_tacacs_authentication").await {
                    Ok(Some(v)) => serde_json::from_value::<AuthReply>(v)?,
                    Ok(None) => AuthReply {
                        status: AuthStatus::Fail,
                        no_echo: false,
                        server_message: String::new(),
                        data: String::new(),
                    },
                    Err(_) => {
                        fail(
                            ctx,
                            id,
                            &mut w,
                            h,
                            secret,
                            "fail_closed_authentication_handler",
                        )
                        .await?;
                        return Ok(());
                    }
                };
            ensure!(
                matches!(
                    reply.status,
                    AuthStatus::Pass | AuthStatus::Fail | AuthStatus::Error
                ) && !reply.no_echo,
                "terminal authentication reply"
            );
            send(
                ctx,
                id,
                &mut w,
                h.reply()?,
                &auth_reply_body(&reply)?,
                secret,
            )
            .await?;
            decision(
                ctx,
                id,
                match reply.status {
                    AuthStatus::Pass => "authentication_pass",
                    AuthStatus::Fail => "authentication_fail",
                    _ => "authentication_error",
                },
            );
        }
        2 | 3 => {
            if h.version != 0xc0 {
                fail(ctx, id, &mut w, h, secret, "fail_closed_request_version").await?;
                return Ok(());
            }
            let (request, kind) = match parse_request(&body, h.kind == 3) {
                Ok(v) => v,
                Err(_) => {
                    fail(ctx, id, &mut w, h, secret, "fail_closed_request_body").await?;
                    return Ok(());
                }
            };
            let mut data = serde_json::to_value(&request)?;
            data["source_addr"] = json!(peer.to_string());
            data["session_id"] = json!(h.session_id);
            if let Some(kind) = kind {
                data["record_type"] = json!(kind);
            }
            let event = Event::new(
                if h.kind == 2 {
                    &actions::AUTHOR_EVENT
                } else {
                    &actions::ACCOUNT_EVENT
                },
                json!({"request":data}),
            );
            let observed = event.data.clone();
            let expected = if h.kind == 2 {
                "respond_tacacs_authorization"
            } else {
                "record_tacacs_accounting"
            };
            let value = match handler(ctx, id, &mut r, cfg, event, expected).await {
                Ok(v) => v,
                Err(_) => {
                    fail(ctx, id, &mut w, h, secret, "fail_closed_aaa_handler").await?;
                    return Ok(());
                }
            };
            let body = if h.kind == 2 {
                let reply = if let Some(v) = value {
                    serde_json::from_value::<AuthorReply>(v)?
                } else {
                    AuthorReply {
                        status: AuthorStatus::Fail,
                        arguments: vec![],
                        server_message: String::new(),
                        data: String::new(),
                    }
                };
                ensure!(reply.status != AuthorStatus::Follow, "FOLLOW excluded");
                decision(
                    ctx,
                    id,
                    match reply.status {
                        AuthorStatus::PassAdd | AuthorStatus::PassReplace => "authorization_pass",
                        AuthorStatus::Fail => "authorization_fail",
                        _ => "authorization_error",
                    },
                );
                author_reply_body(&reply)?
            } else {
                let reply = if let Some(v) = value {
                    serde_json::from_value::<AccountReply>(v)?
                } else {
                    AccountReply {
                        status: AccountStatus::Error,
                        server_message: String::new(),
                        data: String::new(),
                    }
                };
                ensure!(reply.status != AccountStatus::Follow, "FOLLOW excluded");
                if reply.status == AccountStatus::Success {
                    ctx.state.record_access_log(
                        AccessLogOwner::Server(ctx.server_id.as_u32()), "TACACS", Some(id.as_u32()),
                        "tacacs_accounting_recorded", observed,
                        vec![json!({"type":"record_tacacs_accounting","recorded_in_shared_access_log":true,"durable_storage":false})],
                    ).await;
                    decision(ctx, id, "accounting_recorded_success");
                } else {
                    decision(ctx, id, "accounting_error");
                }
                account_reply_body(&reply)?
            };
            send(ctx, id, &mut w, h.reply()?, &body, secret).await?;
        }
        _ => unreachable!(),
    }
    tokio::time::timeout(WRITE_TIMEOUT, w.shutdown())
        .await
        .context("shutdown deadline")??;
    Ok(())
}