starry-kernel 0.5.9

A Linux-compatible OS kernel built on ArceOS unikernel
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
use alloc::{sync::Arc, vec, vec::Vec};
use core::{ffi::c_char, mem::MaybeUninit};

use ax_config::ARCH;
use ax_errno::{AxError, AxResult};
use ax_fs::FS_CONTEXT;
use ax_task::current;
use linux_raw_sys::{
    general::{GRND_INSECURE, GRND_NONBLOCK, GRND_RANDOM},
    system::{new_utsname, sysinfo},
};
use starry_vm::{VmMutPtr, vm_read_slice, vm_write_slice};

use crate::task::{AsThread, processes};

/// Sentinel value meaning "don't change this ID" (userspace passes -1 as signed,
/// which becomes `u32::MAX` after the `as u32` cast in the dispatch table).
const NOCHG: u32 = u32::MAX;

pub fn sys_getuid() -> AxResult<isize> {
    let cred = current().as_thread().cred();
    Ok(cred.uid as isize)
}

pub fn sys_geteuid() -> AxResult<isize> {
    let cred = current().as_thread().cred();
    Ok(cred.euid as isize)
}

pub fn sys_getgid() -> AxResult<isize> {
    let cred = current().as_thread().cred();
    Ok(cred.gid as isize)
}

pub fn sys_getegid() -> AxResult<isize> {
    let cred = current().as_thread().cred();
    Ok(cred.egid as isize)
}

pub fn sys_getresuid(ruid: *mut u32, euid: *mut u32, suid: *mut u32) -> AxResult<isize> {
    let cred = current().as_thread().cred();
    ruid.vm_write(cred.uid)?;
    euid.vm_write(cred.euid)?;
    suid.vm_write(cred.suid)?;
    Ok(0)
}

pub fn sys_getresgid(rgid: *mut u32, egid: *mut u32, sgid: *mut u32) -> AxResult<isize> {
    let cred = current().as_thread().cred();
    rgid.vm_write(cred.gid)?;
    egid.vm_write(cred.egid)?;
    sgid.vm_write(cred.sgid)?;
    Ok(0)
}

// ── setresuid / setresgid ────────────────────────────────────────────

pub fn sys_setresuid(ruid: u32, euid: u32, suid: u32) -> AxResult<isize> {
    debug!("sys_setresuid <= ruid: {ruid}, euid: {euid}, suid: {suid}");
    let thread = current();
    let thread = thread.as_thread();
    let old = thread.cred();
    let mut new = (*old).clone();

    if old.has_cap_setuid() {
        // Privileged: arbitrary values allowed.
        if ruid != NOCHG {
            new.uid = ruid;
        }
        if euid != NOCHG {
            new.euid = euid;
        }
        if suid != NOCHG {
            new.suid = suid;
        }
    } else {
        // Unprivileged: each new value must be one of {uid, euid, suid}.
        let allowed = [old.uid, old.euid, old.suid];
        if ruid != NOCHG {
            if !allowed.contains(&ruid) {
                return Err(AxError::OperationNotPermitted);
            }
            new.uid = ruid;
        }
        if euid != NOCHG {
            if !allowed.contains(&euid) {
                return Err(AxError::OperationNotPermitted);
            }
            new.euid = euid;
        }
        if suid != NOCHG {
            if !allowed.contains(&suid) {
                return Err(AxError::OperationNotPermitted);
            }
            new.suid = suid;
        }
    }

    // fsuid always tracks euid.
    new.fsuid = new.euid;
    thread.set_cred(new);
    Ok(0)
}

pub fn sys_setresgid(rgid: u32, egid: u32, sgid: u32) -> AxResult<isize> {
    debug!("sys_setresgid <= rgid: {rgid}, egid: {egid}, sgid: {sgid}");
    let thread = current();
    let thread = thread.as_thread();
    let old = thread.cred();
    let mut new = (*old).clone();

    if old.has_cap_setgid() {
        if rgid != NOCHG {
            new.gid = rgid;
        }
        if egid != NOCHG {
            new.egid = egid;
        }
        if sgid != NOCHG {
            new.sgid = sgid;
        }
    } else {
        let allowed = [old.gid, old.egid, old.sgid];
        if rgid != NOCHG {
            if !allowed.contains(&rgid) {
                return Err(AxError::OperationNotPermitted);
            }
            new.gid = rgid;
        }
        if egid != NOCHG {
            if !allowed.contains(&egid) {
                return Err(AxError::OperationNotPermitted);
            }
            new.egid = egid;
        }
        if sgid != NOCHG {
            if !allowed.contains(&sgid) {
                return Err(AxError::OperationNotPermitted);
            }
            new.sgid = sgid;
        }
    }

    new.fsgid = new.egid;
    thread.set_cred(new);
    Ok(0)
}

// ── setuid / setgid ─────────────────────────────────────────────────

pub fn sys_setuid(uid: u32) -> AxResult<isize> {
    debug!("sys_setuid <= uid: {uid}");
    let thread = current();
    let thread = thread.as_thread();
    let old = thread.cred();
    let mut new = (*old).clone();

    if old.has_cap_setuid() {
        // Privileged: sets uid, euid, suid ALL (irreversible).
        new.uid = uid;
        new.euid = uid;
        new.suid = uid;
    } else {
        // Unprivileged: only sets euid, and only if uid matches uid or suid.
        if uid != old.uid && uid != old.suid {
            return Err(AxError::OperationNotPermitted);
        }
        new.euid = uid;
    }

    new.fsuid = new.euid;
    thread.set_cred(new);
    Ok(0)
}

pub fn sys_setgid(gid: u32) -> AxResult<isize> {
    debug!("sys_setgid <= gid: {gid}");
    let thread = current();
    let thread = thread.as_thread();
    let old = thread.cred();
    let mut new = (*old).clone();

    if old.has_cap_setgid() {
        new.gid = gid;
        new.egid = gid;
        new.sgid = gid;
    } else {
        if gid != old.gid && gid != old.sgid {
            return Err(AxError::OperationNotPermitted);
        }
        new.egid = gid;
    }

    new.fsgid = new.egid;
    thread.set_cred(new);
    Ok(0)
}

// ── setreuid / setregid ─────────────────────────────────────────────

pub fn sys_setreuid(ruid: u32, euid: u32) -> AxResult<isize> {
    debug!("sys_setreuid <= ruid: {ruid}, euid: {euid}");
    let thread = current();
    let thread = thread.as_thread();
    let old = thread.cred();
    let mut new = (*old).clone();

    if old.has_cap_setuid() {
        if ruid != NOCHG {
            new.uid = ruid;
        }
        if euid != NOCHG {
            new.euid = euid;
        }
    } else {
        // ruid can only be set to current uid or euid.
        if ruid != NOCHG {
            if ruid != old.uid && ruid != old.euid {
                return Err(AxError::OperationNotPermitted);
            }
            new.uid = ruid;
        }
        // euid can be set to current uid, euid, or suid.
        if euid != NOCHG {
            if euid != old.uid && euid != old.euid && euid != old.suid {
                return Err(AxError::OperationNotPermitted);
            }
            new.euid = euid;
        }
    }

    // Per setreuid(2) man page: "If the real user ID is set (i.e.,
    // ruid is not -1) or the effective user ID is set to a value not
    // equal to the previous real user ID, the saved set-user-ID will
    // be set to the new effective user ID."
    if ruid != NOCHG || (euid != NOCHG && new.euid != old.uid) {
        new.suid = new.euid;
    }

    new.fsuid = new.euid;
    thread.set_cred(new);
    Ok(0)
}

pub fn sys_setregid(rgid: u32, egid: u32) -> AxResult<isize> {
    debug!("sys_setregid <= rgid: {rgid}, egid: {egid}");
    let thread = current();
    let thread = thread.as_thread();
    let old = thread.cred();
    let mut new = (*old).clone();

    if old.has_cap_setgid() {
        if rgid != NOCHG {
            new.gid = rgid;
        }
        if egid != NOCHG {
            new.egid = egid;
        }
    } else {
        if rgid != NOCHG {
            if rgid != old.gid && rgid != old.egid {
                return Err(AxError::OperationNotPermitted);
            }
            new.gid = rgid;
        }
        if egid != NOCHG {
            if egid != old.gid && egid != old.egid && egid != old.sgid {
                return Err(AxError::OperationNotPermitted);
            }
            new.egid = egid;
        }
    }

    if rgid != NOCHG || (egid != NOCHG && new.egid != old.gid) {
        new.sgid = new.egid;
    }

    new.fsgid = new.egid;
    thread.set_cred(new);
    Ok(0)
}

pub fn sys_getgroups(size: usize, list: *mut u32) -> AxResult<isize> {
    debug!("sys_getgroups <= size: {size}");
    let cred = current().as_thread().cred();
    let ngroups = cred.groups.len();
    if size == 0 {
        return Ok(ngroups as isize);
    }
    if size < ngroups {
        return Err(AxError::InvalidInput);
    }
    if ngroups > 0 {
        vm_write_slice(list, &cred.groups)?;
    }
    Ok(ngroups as isize)
}

/// Linux limits supplementary groups to 65536 (`NGROUPS_MAX`).
const NGROUPS_MAX: usize = 65536;

pub fn sys_setgroups(size: usize, list: *const u32) -> AxResult<isize> {
    debug!("sys_setgroups <= size: {size}");
    let thread = current();
    let thread = thread.as_thread();
    let old = thread.cred();

    if !old.has_cap_setgid() {
        return Err(AxError::OperationNotPermitted);
    }
    if size > NGROUPS_MAX {
        return Err(AxError::InvalidInput);
    }

    let groups = if size > 0 {
        let mut buf: Vec<MaybeUninit<u32>> = vec![MaybeUninit::uninit(); size];
        vm_read_slice(list, &mut buf)?;
        // SAFETY: vm_read_slice filled all elements with data from user space.
        buf.into_iter()
            .map(|v| unsafe { v.assume_init() })
            .collect()
    } else {
        Vec::new()
    };

    let mut new = (*old).clone();
    new.groups = Arc::from(groups.into_boxed_slice());
    thread.set_cred(new);
    Ok(0)
}

const fn pad_str(info: &str) -> [c_char; 65] {
    let mut data: [c_char; 65] = [0; 65];
    // this needs #![feature(const_copy_from_slice)]
    // data[..info.len()].copy_from_slice(info.as_bytes());
    unsafe {
        core::ptr::copy_nonoverlapping(info.as_ptr().cast(), data.as_mut_ptr(), info.len());
    }
    data
}

const UTSNAME: new_utsname = new_utsname {
    sysname: pad_str("Linux"),
    nodename: pad_str("starry"),
    release: pad_str("10.0.0"),
    version: pad_str("10.0.0"),
    machine: pad_str(ARCH),
    domainname: pad_str("https://github.com/Starry-OS/StarryOS"),
};

pub fn sys_uname(name: *mut new_utsname) -> AxResult<isize> {
    name.vm_write(UTSNAME)?;
    Ok(0)
}

pub fn sys_sysinfo(info: *mut sysinfo) -> AxResult<isize> {
    // FIXME: Zeroable
    let mut kinfo: sysinfo = unsafe { core::mem::zeroed() };
    kinfo.procs = processes().len() as _;
    kinfo.mem_unit = 1;
    info.vm_write(kinfo)?;
    Ok(0)
}

pub fn sys_syslog(_type: i32, _buf: *mut c_char, _len: usize) -> AxResult<isize> {
    Ok(0)
}

bitflags::bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct GetRandomFlags: u32 {
        const NONBLOCK = GRND_NONBLOCK;
        const RANDOM = GRND_RANDOM;
        const INSECURE = GRND_INSECURE;
    }
}

pub fn sys_getrandom(buf: *mut u8, len: usize, flags: u32) -> AxResult<isize> {
    if len == 0 {
        return Ok(0);
    }
    let flags = GetRandomFlags::from_bits(flags).ok_or(AxError::InvalidInput)?;
    if flags.contains(GetRandomFlags::INSECURE) && flags.contains(GetRandomFlags::RANDOM) {
        return Err(AxError::InvalidInput);
    }

    debug!("sys_getrandom <= buf: {buf:p}, len: {len}, flags: {flags:?}");

    let path = if flags.contains(GetRandomFlags::RANDOM) {
        "/dev/random"
    } else {
        "/dev/urandom"
    };

    let f = FS_CONTEXT.lock().resolve(path)?;
    let mut kbuf = vec![0; len];
    let len = f.entry().as_file()?.read_at(&mut kbuf, 0)?;

    vm_write_slice(buf, &kbuf)?;

    Ok(len as _)
}

pub fn sys_seccomp(_op: u32, _flags: u32, _args: *const ()) -> AxResult<isize> {
    warn!("dummy sys_seccomp");
    Ok(0)
}

#[cfg(target_arch = "riscv64")]
pub fn sys_riscv_flush_icache() -> AxResult<isize> {
    riscv::asm::fence_i();
    Ok(0)
}