l2tp 0.4.0

High-level L2TP interface for Linux kernel
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
// SPDX-License-Identifier: MIT

#![cfg(target_os = "linux")]

use std::{
    net::{Ipv4Addr, SocketAddrV4},
    sync::atomic::{AtomicU32, Ordering},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use futures::StreamExt;
use l2tp::{
    Cookie, Encapsulation, IpEndpoint, L2SpecType, L2tpEvent, L2tpHandle,
    L2tpIfName, L2tpIfNameExt, L2tpVersion, PppSocket, PppUnit, PseudowireType,
    SessionConfig, SessionHandle, SessionId, SessionModify, TunnelConfig,
    TunnelHandle, TunnelId, TunnelSocket, UdpEndpoint, blocking,
};

static ID_COUNTER: AtomicU32 = AtomicU32::new(0);

fn runtime() -> tokio::runtime::Runtime {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap_or_else(|e| panic!("failed to build tokio runtime: {e}"))
}

fn next_id_base() -> u32 {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64;
    let pid = std::process::id() as u64;
    let seq = ID_COUNTER.fetch_add(1, Ordering::Relaxed) as u64;
    let mixed = now ^ (pid << 16) ^ seq;
    1_000_000_000u32.wrapping_add((mixed as u32) % 500_000_000)
}

fn is_eexist(err: &l2tp::Error) -> bool {
    err.kind() == Some(std::io::ErrorKind::AlreadyExists)
}

fn udp_loopback(version: L2tpVersion) -> TunnelConfig {
    let base = next_id_base();
    let base = if version == L2tpVersion::V2 {
        // Keep both IDs nonzero and leave room for the peer's ID.
        base % (u32::from(u16::MAX) - 1) + 1
    } else {
        base
    };
    TunnelConfig::new(
        TunnelId(base),
        TunnelId(base.wrapping_add(1)),
        Encapsulation::Udp {
            local: UdpEndpoint::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)),
            remote: UdpEndpoint::V4(SocketAddrV4::new(
                Ipv4Addr::LOCALHOST,
                17012,
            )),
            udp_csum: false,
            udp_zero_csum6_tx: false,
            udp_zero_csum6_rx: false,
        },
    )
    .unwrap_or_else(|e| panic!("TunnelConfig::new failed: {e}"))
    .with_version(version)
}

/// Creates an unmanaged tunnel, retrying the random identifiers on EEXIST.
async fn create_unmanaged(
    handle: &L2tpHandle,
    make: impl Fn() -> TunnelConfig,
) -> (TunnelConfig, l2tp::TunnelHandle) {
    for _ in 0..16 {
        let config = make();
        match handle.create_unmanaged_tunnel(config.clone()).await {
            Ok(tunnel) => return (config, tunnel),
            Err(e) if is_eexist(&e) => continue,
            Err(e) => panic!("create_unmanaged_tunnel failed: {e}"),
        }
    }
    panic!("could not allocate unique tunnel id after retries");
}

#[test]
#[ignore = "requires CAP_NET_RAW/root (SO_BINDTODEVICE)"]
fn privileged_bind_to_device_on_loopback() {
    let local = UdpEndpoint::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0));
    let remote = UdpEndpoint::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9999));
    let device = L2tpIfName::new("lo").unwrap_or_else(|e| panic!("{e}"));

    let socket = TunnelSocket::udp(&local, &remote, None)
        .unwrap_or_else(|e| panic!("failed to create UDP tunnel socket: {e}"));
    socket
        .bind_to_device(&device)
        .unwrap_or_else(|e| panic!("SO_BINDTODEVICE failed: {e}"));
    // Disconnecting clears SO_BINDTODEVICE; binding again restores it.
    socket
        .disconnect()
        .unwrap_or_else(|e| panic!("disconnect failed: {e}"));
    assert!(socket.peer_addr_udp().is_err());
    let unbound = TunnelSocket::from_fd(
        socket
            .try_clone_fd()
            .unwrap_or_else(|e| panic!("dup failed: {e}")),
    )
    .unwrap_or_else(|e| panic!("from_fd failed: {e}"));
    assert!(
        unbound.local_addr_udp().is_ok(),
        "the local address survives the disconnect"
    );
    socket
        .bind_to_device(&device)
        .unwrap_or_else(|e| panic!("SO_BINDTODEVICE failed again: {e}"));
    socket
        .reconnect_udp(&remote)
        .unwrap_or_else(|e| panic!("reconnect failed: {e}"));
    // An adopted descriptor reads the bound device back.
    let adopted = TunnelSocket::from_fd(socket.into_fd())
        .unwrap_or_else(|e| panic!("from_fd failed: {e}"));
    drop(adopted);
}

#[test]
#[ignore = "requires CAP_NET_ADMIN/root and kernel l2tp generic-netlink support"]
fn privileged_unmanaged_tunnel_lifecycle_over_genl() {
    runtime().block_on(async {
        let handle = L2tpHandle::new()
            .await
            .unwrap_or_else(|e| panic!("L2tpHandle::new failed: {e}"));
        for version in [L2tpVersion::V3, L2tpVersion::V2] {
            let (config, tunnel) =
                create_unmanaged(&handle, || udp_loopback(version)).await;
            let info = tunnel
                .get()
                .await
                .unwrap_or_else(|e| panic!("tunnel get failed: {e}"));
            assert_eq!(info.tunnel_id, config.tunnel_id());
            assert_eq!(info.peer_tunnel_id, config.peer_tunnel_id());
            assert_eq!(info.version, version);

            // Opening an existing tunnel yields a non-owning handle.
            let opened = handle
                .open_tunnel(config.tunnel_id())
                .await
                .unwrap_or_else(|e| panic!("open_tunnel failed: {e}"));
            assert!(!opened.auto_delete());
            drop(opened);

            tunnel
                .delete()
                .await
                .unwrap_or_else(|e| panic!("delete failed: {e}"));
            assert!(handle.get_tunnel(config.tunnel_id()).await.is_err());
        }
    });
}

#[test]
#[ignore = "requires CAP_NET_ADMIN/root and kernel l2tp_eth support"]
fn privileged_session_lifecycle_over_genl() {
    runtime().block_on(async {
        let handle = L2tpHandle::new()
            .await
            .unwrap_or_else(|e| panic!("L2tpHandle::new failed: {e}"));
        let (config, mut tunnel) = create_unmanaged(&handle, || {
            let base = next_id_base();
            TunnelConfig::new(
                TunnelId(base),
                TunnelId(base.wrapping_add(1)),
                Encapsulation::Ip {
                    local: IpEndpoint::V4(Ipv4Addr::LOCALHOST),
                    remote: IpEndpoint::V4(Ipv4Addr::LOCALHOST),
                },
            )
            .unwrap_or_else(|e| panic!("TunnelConfig::new failed: {e}"))
        })
        .await;
        tunnel.set_auto_delete(false);
        let tunnel_id = config.tunnel_id();
        let session_id = SessionId(tunnel_id.0.wrapping_add(2));
        let peer_session_id = SessionId(tunnel_id.0.wrapping_add(3));

        let session_config = SessionConfig {
            tunnel_id,
            session_id,
            peer_session_id,
            pseudowire_type: PseudowireType::Eth,
            l2spec_type: L2SpecType::None,
            cookie: Cookie::from([1, 2, 3, 4]),
            peer_cookie: Cookie::none(),
            recv_seq: false,
            send_seq: false,
            lns_mode: false,
            recv_timeout_ms: Some(2000),
            ifname: None,
        };

        let mut session = handle
            .create_session(session_config)
            .await
            .unwrap_or_else(|e| panic!("create_session failed: {e}"));
        session.set_auto_delete(false);
        // The index was captured from the registration broadcast and agrees
        // with the name while the interface still bears it.
        let ifindex =
            session.ifindex().expect("ethernet sessions have an index");
        assert_eq!(
            session
                .ifname()
                .unwrap()
                .index()
                .unwrap_or_else(|e| panic!("{e}")),
            ifindex
        );

        let info = session
            .get()
            .await
            .unwrap_or_else(|e| panic!("session get failed: {e}"));
        assert_eq!(info.tunnel_id, tunnel_id);
        assert_eq!(info.peer_tunnel_id, config.peer_tunnel_id());
        assert_eq!(info.session_id, session_id);
        assert_eq!(info.peer_session_id, peer_session_id);
        assert_eq!(info.pseudowire_type, PseudowireType::Eth);
        assert_eq!(info.cookie, Cookie::from([1, 2, 3, 4]));
        let ifname = info.ifname.expect("ethernet sessions have an interface");

        // The same session is reachable by its interface name.
        let by_name = handle
            .get_session_by_ifname(&ifname)
            .await
            .unwrap_or_else(|e| panic!("get_session_by_ifname failed: {e}"));
        assert_eq!(by_name.session_id, session_id);
        handle
            .modify_session_by_ifname(
                &ifname,
                SessionModify {
                    recv_seq: Some(true),
                    send_seq: Some(true),
                    lns_mode: Some(false),
                    recv_timeout_ms: Some(1500),
                },
            )
            .await
            .unwrap_or_else(|e| panic!("session modify failed: {e}"));
        let opened = handle
            .open_session_by_ifname(&ifname)
            .await
            .unwrap_or_else(|e| panic!("open_session_by_ifname failed: {e}"));
        assert!(!opened.auto_delete());
        assert_eq!(opened.ifname(), Some(&ifname));
        assert_eq!(opened.ifindex(), Some(ifindex));
        drop(opened);

        handle
            .delete_session_by_ifname(&ifname)
            .await
            .unwrap_or_else(|e| panic!("delete_session failed: {e}"));
        handle
            .delete_tunnel(tunnel_id)
            .await
            .unwrap_or_else(|e| panic!("delete_tunnel failed: {e}"));
    });
}

#[test]
#[ignore = "requires CAP_NET_ADMIN/root and kernel l2tp generic-netlink support"]
fn privileged_events_report_tunnel_lifecycle() {
    runtime().block_on(async {
        let handle = L2tpHandle::new()
            .await
            .unwrap_or_else(|e| panic!("L2tpHandle::new failed: {e}"));
        let mut events = handle
            .events()
            .await
            .unwrap_or_else(|e| panic!("events failed: {e}"));
        let (config, tunnel) =
            create_unmanaged(&handle, || udp_loopback(L2tpVersion::V3)).await;
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                let event = events
                    .next()
                    .await
                    .expect("the stream is open")
                    .expect("the event decodes");
                if matches!(
                    event,
                    L2tpEvent::TunnelCreated(info) if info.tunnel_id == config.tunnel_id()
                ) {
                    break;
                }
            }
        })
        .await
        .expect("a creation event for this tunnel arrives");
        tunnel
            .delete()
            .await
            .unwrap_or_else(|e| panic!("delete failed: {e}"));
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                let event = events
                    .next()
                    .await
                    .expect("the stream is open")
                    .expect("the event decodes");
                if matches!(
                    event,
                    L2tpEvent::TunnelDeleted(info) if info.tunnel_id == config.tunnel_id()
                ) {
                    break;
                }
            }
        })
        .await
        .expect("a deletion event for this tunnel arrives");
    });
}

/// A PPP session on a fresh unmanaged tunnel, with the `PPPoL2TP` socket
/// attached to it. The session handle has auto-delete disabled, because the
/// kernel deletes the session together with the socket.
async fn attached_ppp_session(
    handle: &L2tpHandle,
) -> (
    TunnelConfig,
    TunnelHandle,
    SessionId,
    SessionHandle,
    PppSocket,
) {
    let (config, tunnel) =
        create_unmanaged(handle, || udp_loopback(L2tpVersion::V3)).await;
    let session_id = SessionId(config.tunnel_id().0.wrapping_add(2));
    let peer_session_id = SessionId(config.tunnel_id().0.wrapping_add(3));
    let mut session = handle
        .create_session(SessionConfig::ppp(
            config.tunnel_id(),
            session_id,
            peer_session_id,
        ))
        .await
        .unwrap_or_else(|e| panic!("create_session failed: {e}"));
    session.set_auto_delete(false);

    let socket = PppSocket::connect(
        L2tpVersion::V3,
        config.tunnel_id(),
        config.peer_tunnel_id(),
        session_id,
        peer_session_id,
    )
    .unwrap_or_else(|e| panic!("PppSocket::connect failed: {e}"));
    (config, tunnel, session_id, session, socket)
}

#[test]
#[ignore = "requires CAP_NET_ADMIN/root and the kernel l2tp_ppp module"]
fn privileged_ppp_session_attaches_a_pppol2tp_socket() {
    runtime().block_on(async {
        let handle = L2tpHandle::new()
            .await
            .unwrap_or_else(|e| panic!("L2tpHandle::new failed: {e}"));
        let (config, tunnel, session_id, session, socket) =
            attached_ppp_session(&handle).await;
        let channel = socket
            .channel_index()
            .unwrap_or_else(|e| panic!("channel_index failed: {e}"));
        assert!(channel >= 0);
        // A second socket cannot attach to the same session.
        let err = PppSocket::connect(
            L2tpVersion::V3,
            config.tunnel_id(),
            config.peer_tunnel_id(),
            session_id,
            SessionId(session_id.0.wrapping_add(1)),
        )
        .err()
        .map(|e| e.raw_os_error());
        assert_eq!(err, Some(Some(libc::EEXIST)));

        // Releasing the PPPoL2TP socket deletes the session in the kernel.
        drop(socket);
        let err = handle
            .get_session(config.tunnel_id(), session_id)
            .await
            .expect_err("the session is gone with its socket");
        assert_eq!(err.raw_os_error(), Some(libc::ENODEV), "{err}");
        drop(session);
        tunnel.delete().await.unwrap_or_else(|e| panic!("{e}"));
    });
}

#[test]
#[ignore = "requires CAP_NET_ADMIN/root, the kernel l2tp_ppp module and \
            /dev/ppp"]
fn privileged_ppp_unit_connects_and_disconnects_a_channel() {
    runtime().block_on(async {
        let handle = L2tpHandle::new()
            .await
            .unwrap_or_else(|e| panic!("L2tpHandle::new failed: {e}"));
        let (_config, tunnel, _session_id, _session, socket) =
            attached_ppp_session(&handle).await;

        let unit = match PppUnit::new() {
            Ok(unit) => unit,
            // Without the device node (for example in a user namespace that
            // cannot create one) there is nothing to test.
            Err(e) if e.raw_os_error() == Some(libc::ENOENT) => {
                eprintln!("skipping: /dev/ppp is absent: {e}");
                drop(socket);
                tunnel.delete().await.unwrap_or_else(|e| panic!("{e}"));
                return;
            }
            Err(e) => panic!("PppUnit::new failed: {e}"),
        };
        assert!(unit.ifname().as_bytes().starts_with(b"ppp"));
        let link = unit
            .connect_channel(&socket)
            .unwrap_or_else(|e| panic!("connect_channel failed: {e}"));
        // Dropping the channel disconnects it, so it can be connected again.
        drop(link);
        let link = unit
            .connect_channel(&socket)
            .unwrap_or_else(|e| panic!("second connect_channel failed: {e}"));
        drop(link);
        drop(unit);
        drop(socket);
        tunnel.delete().await.unwrap_or_else(|e| panic!("{e}"));
    });
}

#[test]
#[ignore = "requires CAP_NET_ADMIN/root and kernel l2tp generic-netlink support"]
fn privileged_blocking_api_manages_a_tunnel() {
    let handle = blocking::L2tpHandle::new()
        .unwrap_or_else(|e| panic!("blocking::L2tpHandle::new failed: {e}"));
    let mut created = None;
    for _ in 0..16 {
        let config = udp_loopback(L2tpVersion::V3);
        match handle.create_unmanaged_tunnel(config.clone()) {
            Ok(tunnel) => {
                created = Some((config, tunnel));
                break;
            }
            Err(e) if is_eexist(&e) => continue,
            Err(e) => panic!("create_unmanaged_tunnel failed: {e}"),
        }
    }
    let (config, tunnel) = created.expect("a unique tunnel id");
    let info = tunnel.get().unwrap_or_else(|e| panic!("get failed: {e}"));
    assert_eq!(info.tunnel_id, config.tunnel_id());
    assert!(
        handle
            .list_tunnels()
            .unwrap_or_else(|e| panic!("{e}"))
            .iter()
            .any(|t| t.tunnel_id == config.tunnel_id())
    );
    tunnel
        .delete()
        .unwrap_or_else(|e| panic!("delete failed: {e}"));
    assert!(handle.get_tunnel(config.tunnel_id()).is_err());
}

#[test]
#[ignore = "requires kernel l2tp_ip and l2tp_ip6 support"]
fn privileged_managed_ip_sockets_report_their_peer() {
    for local in [
        IpEndpoint::V4(Ipv4Addr::LOCALHOST),
        IpEndpoint::v6(std::net::Ipv6Addr::LOCALHOST),
    ] {
        let id = next_id_base();
        let socket = TunnelSocket::ip(
            &local,
            &local,
            None,
            TunnelId(id),
            TunnelId(id.wrapping_add(1)),
        )
        .unwrap_or_else(|e| {
            panic!("create an L2TP/IP socket for {local}: {e}")
        });
        // IPv4 L2TP/IP sockets get no peer from the kernel; the socket
        // remembers it.
        assert_eq!(
            socket.peer_addr_ip().unwrap_or_else(|e| panic!("{e}")),
            local
        );
        let config = TunnelConfig::for_socket(
            TunnelId(id),
            TunnelId(id.wrapping_add(1)),
            &socket,
        )
        .unwrap_or_else(|e| panic!("describe the socket: {e}"));
        assert_eq!(
            *config.encapsulation(),
            Encapsulation::Ip {
                local: local.clone(),
                remote: local.clone()
            }
        );

        // After a disconnect the kernel still reports the old IPv6 peer;
        // the socket does not.
        socket
            .disconnect()
            .unwrap_or_else(|e| panic!("disconnect: {e}"));
        let err = socket.peer_addr_ip().expect_err("no peer after disconnect");
        assert_eq!(err.raw_os_error(), Some(libc::ENOTCONN), "{err}");
        assert!(
            TunnelConfig::for_socket(
                TunnelId(id),
                TunnelId(id.wrapping_add(1)),
                &socket
            )
            .is_err()
        );
        socket
            .reconnect_ip(&local)
            .unwrap_or_else(|e| panic!("reconnect: {e}"));
        assert_eq!(
            socket.peer_addr_ip().unwrap_or_else(|e| panic!("{e}")),
            local
        );
        drop(socket);
    }
}

#[cfg(feature = "cli")]
#[test]
#[ignore = "requires CAP_NET_ADMIN/root and kernel l2tp generic-netlink support"]
fn privileged_cli_tunnel_survives_process_exit() {
    let id = next_id_base();
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_l2tp"))
        .args([
            "tunnel",
            "create",
            "--tunnel-id",
            &id.to_string(),
            "--peer-tunnel-id",
            &(id + 1).to_string(),
            "--local",
            "127.0.0.1:0",
            "--remote",
            "127.0.0.1:17012",
        ])
        .output()
        .expect("run l2tp tunnel create");
    // A failed create (including EEXIST) gives us no ownership of this ID.
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    runtime().block_on(async {
        let handle = L2tpHandle::new().await.unwrap();
        let info = handle.get_tunnel(TunnelId(id)).await;
        // Clean up our tunnel before asserting that the lookup succeeded.
        let cleanup = handle.delete_tunnel(TunnelId(id)).await;
        assert_eq!(
            info.expect("tunnel must survive CLI exit").tunnel_id,
            TunnelId(id)
        );
        cleanup.expect("delete CLI-created tunnel");
    });
}