glycin_utils/
instruction_handler.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
// Copyright (c) 2024 GNOME Foundation Inc.

use std::os::fd::{AsRawFd, FromRawFd};
use std::os::raw::{c_int, c_void};
use std::os::unix::net::UnixStream;
use std::sync::Mutex;

use nix::libc::{c_uint, siginfo_t};

use crate::dbus_editor_api::{void_editor_none, Editor, EditorImplementation};
use crate::dbus_loader_api::{Loader, LoaderImplementation};

pub struct Communication {
    _dbus_connection: zbus::Connection,
}

impl Communication {
    pub fn spawn_loader(decoder: impl LoaderImplementation + 'static) {
        futures_lite::future::block_on(async move {
            let _connection = Self::connect(Some(decoder), void_editor_none()).await;
            std::future::pending::<()>().await;
        })
    }

    pub fn spawn_loader_editor(
        loader: impl LoaderImplementation + 'static,
        editor: impl EditorImplementation + 'static,
    ) {
        futures_lite::future::block_on(async move {
            let _connection = Self::connect(Some(loader), Some(editor)).await;
            std::future::pending::<()>().await;
        })
    }

    async fn connect(
        loader: Option<impl LoaderImplementation + 'static>,
        editor: Option<impl EditorImplementation + 'static>,
    ) -> Self {
        env_logger::builder().format_timestamp_millis().init();

        log::debug!("Creating zbus connection to glycin");

        let unix_stream: UnixStream =
            unsafe { UnixStream::from_raw_fd(std::io::stdin().as_raw_fd()) };

        #[cfg(feature = "tokio")]
        let unix_stream =
            tokio::net::UnixStream::from_std(unix_stream).expect("wrapping unix stream works");

        let mut dbus_connection = zbus::connection::Builder::unix_stream(unix_stream)
            .p2p()
            .auth_mechanism(zbus::AuthMechanism::Anonymous);

        if let Some(loader) = loader {
            let instruction_handler = Loader {
                loader: Mutex::new(Box::new(loader)),
            };
            dbus_connection = dbus_connection
                .serve_at("/org/gnome/glycin", instruction_handler)
                .expect("Failed to setup loader handler");
        }

        if let Some(editor) = editor {
            let instruction_handler = Editor {
                editor: Mutex::new(Box::new(editor)),
            };
            dbus_connection = dbus_connection
                .serve_at("/org/gnome/glycin", instruction_handler)
                .expect("Failed to setup editor handler");
        }

        let _dbus_connection = dbus_connection
            .build()
            .await
            .expect("Failed to create private DBus connection");

        log::debug!("D-Bus connection to glycin created");
        Communication { _dbus_connection }
    }

    fn setup_sigsys_handler() {
        let mut mask = nix::sys::signal::SigSet::empty();
        mask.add(nix::sys::signal::Signal::SIGSYS);

        let sigaction = nix::sys::signal::SigAction::new(
            nix::sys::signal::SigHandler::SigAction(Self::sigsys_handler),
            nix::sys::signal::SaFlags::SA_SIGINFO,
            mask,
        );

        unsafe {
            if nix::sys::signal::sigaction(nix::sys::signal::Signal::SIGSYS, &sigaction).is_err() {
                libc_eprint("glycin sandbox: Failed to init syscall failure signal handler");
            }
        };
    }

    #[allow(non_camel_case_types)]
    extern "C" fn sigsys_handler(_: c_int, info: *mut siginfo_t, _: *mut c_void) {
        // Reimplement siginfo_t since the libc crate doesn't support _sigsys
        // information
        #[repr(C)]
        struct siginfo_t {
            si_signo: c_int,
            si_errno: c_int,
            si_code: c_int,
            _sifields: _sigsys,
        }

        #[repr(C)]
        struct _sigsys {
            _call_addr: *const c_void,
            _syscall: c_int,
            _arch: c_uint,
        }

        let info: *mut siginfo_t = info.cast();
        let syscall = unsafe { info.as_ref().unwrap()._sifields._syscall };

        let name = libseccomp::ScmpSyscall::from(syscall).get_name().ok();

        libc_eprint("glycin sandbox: Blocked syscall used: ");
        libc_eprint(&name.unwrap_or_else(|| String::from("Unknown Syscall")));
        libc_eprint(" (");
        libc_eprint(&syscall.to_string());
        libc_eprint(")\n");

        unsafe {
            libc::exit(128 + libc::SIGSYS);
        }
    }
}

#[allow(dead_code)]
pub extern "C" fn pre_main() {
    Communication::setup_sigsys_handler();
}

#[macro_export]
macro_rules! init_main_loader {
    ($loader:expr) => {
        /// Init handler for SIGSYS before main() to catch
        #[cfg_attr(target_os = "linux", link_section = ".ctors")]
        static __CTOR: extern "C" fn() = pre_main;

        fn main() {
            $crate::Communication::spawn_loader($loader);
        }
    };
}

#[macro_export]
macro_rules! init_main_loader_editor {
    ($loader:expr, $editor:expr) => {
        /// Init handler for SIGSYS before main() to catch
        #[cfg_attr(target_os = "linux", link_section = ".ctors")]
        static __CTOR: extern "C" fn() = pre_main;

        fn main() {
            $crate::Communication::spawn_loader_editor($loader, $editor);
        }
    };
}

fn libc_eprint(s: &str) {
    unsafe {
        libc::write(
            libc::STDERR_FILENO,
            s.as_ptr() as *const libc::c_void,
            s.len(),
        );
    }
}