Skip to content

dev: セキュリティ基盤強化・Linux互換syscall拡張#5

Merged
tas0dev merged 42 commits intotas0dev:devfrom
minto-dane:dev
Mar 4, 2026
Merged

dev: セキュリティ基盤強化・Linux互換syscall拡張#5
tas0dev merged 42 commits intotas0dev:devfrom
minto-dane:dev

Conversation

@minto-dane
Copy link
Contributor

@minto-dane minto-dane commented Mar 3, 2026

PR概要

本PRは minto-dane:dev から tas0dev:dev への 40 コミット統合で、カーネルのセキュリティ境界を中心に、Linux互換syscall実装の拡張、CI/CDの再現性向上、監査ドキュメント整備を一体で実施したものです。特に syscall 境界(user pointer検証、CR3切替、SMAP連携)、KPTI周辺、プロセス資源回収、IPC整合性、実行イメージ検証(ELF)を重点強化し、SECURITY_REVIEW.md で定義したリスク項目の実装閉塞を含めています。


目的

  • ユーザー入力境界(ポインタ/文字列/長さ)を fail-closed 化し、カーネル側の不正参照・権限逸脱を抑止
  • KPTI/SYSCALL境界の堅牢化(CR3整合・stack取り扱い)により特権境界の破壊面を縮小
  • Linux互換syscallの実装範囲を拡大し、ユーザーランド実行互換を改善
  • CI環境でのビルド不整合(target不足等)を解消し、再現性を確保

主な変更内容

1) セキュリティ基盤・カーネル境界の強化

1-1. user pointer / user memory access 経路の強化

  • validate_user_ptr による境界チェック + 実マップ確認を syscall 横断で適用
  • with_user_memory_access 経路で KPTI/SMAP 前提の安全なユーザーメモリアクセスを統一
  • user C文字列取得を共通化(read_user_cstring)し、文字列境界の重複実装を解消

1-2. KPTI/SYSCALL境界の強化

  • SYSCALLエントリでの stack 取り扱いを強化(per-CPU GS基盤接続)
  • kernel/user CR3 切替の整合性を syscall/割り込み経路で維持
  • SYSRET 直前の canonical address 検証(CVE-2012-0217 緩和)を保持

1-3. 権限分離と実行認可

  • I/O port syscall に PrivilegeLevel 判定(Core/Service限定)を適用
  • .service 起動認可で manager PID の存在/状態/権限を検証

1-4. メモリ保護

  • user stack に NX を適用
  • kernel .text 保護方針の維持・見直し
  • kernel stack guard の強化(検知性・保護性の改善)
  • munmap / page table destroy 経路で frame 解放連携を強化

1-5. 実行イメージ検証(ELF)

  • EM_X86_64 検証の明示
  • p_offset + p_filesz など境界計算を checked 系で防御
  • p_vaddr/p_memsz 取り扱いの整合性強化
  • ASLR seed にハードウェア乱数(RDRAND)混合

1-6. 例外・ログ露出面の縮小

  • invalid opcode 例外時の過剰ダンプを整理し、情報露出面を削減

2) Linux互換syscall拡張・整合

  • mmap / munmap / brk / wait / futex / arch_prctl / clock_gettime / getcwd などの実装・改善
  • signal系未実装 syscall の返値を明示化し、偽成功挙動を抑制
  • clone は現状 fork 経路中心であり、完全な clone(2) は今後の拡張対象

3) プロセス/IPC/スケジューラ整合

  • zombie回収時の資源解放連携(page table/frame)
  • IPCでの宛先検証強化(誤配送・孤立メッセージ対策)
  • スケジューラ/コンテキスト切替経路の安全性・一貫性改善

4) CI/CD・ビルド再現性

  • .github/workflows/ci.yml 新規追加/整備
  • .github/workflows/security.yml 追加(Dependency Review + cargo-audit)
  • rust-toolchain.toml へ target 追記
  • builders/newlib.rs で環境差分に対するビルドフォールバックを改善
  • builder側でカスタムtarget(json) 取り扱いを改善

5) ドキュメント・運用面

  • SECURITY_REVIEW.md を追加
    • 現在のコードベースに元ずいた脅威モデル、信頼境界、セキュリティ不変条件(INV-1..INV-8)が含まれる
  • std-todo.md を実装現況に合わせて更新

claude and others added 14 commits March 2, 2026 16:52
Thorough static analysis of the entire SwiftCore kernel codebase covering
5 Critical, 6 High, 8 Medium, and 8 Low/Informational security findings.

Key vulnerabilities documented:
- CRIT-01: All syscalls dereference user pointers without validation
  (allows arbitrary kernel memory read/write)
- CRIT-02: Unrestricted I/O port access for all user processes
  (direct hardware control, potential privilege escalation)
- CRIT-03: fork() shares page table without Copy-on-Write
  (no process memory isolation)
- CRIT-04: ELF loader missing bounds checks on p_offset/p_filesz
  (integer overflow → buffer over-read → kernel panic/corruption)
- CRIT-05: ELF segment vaddr not restricted to user space
- HIGH-02: Use-after-free race in fs::read() FD table
- HIGH-06: All physical memory mapped WRITABLE including kernel .text
- Plus physical memory leak (no frame deallocation), missing NX on stack,
  no ASLR, debug code left in production, etc.

Includes phased remediation roadmap with priority matrix.

https://claude.ai/code/session_01BCuX95Hca83hHE3nbTUiKs
## Critical 修正
- CRIT-01: validate_user_ptr() を syscall/mod.rs に追加し、io.rs/ipc.rs/
  process.rs/fs.rs/exec.rs の全syscallハンドラでユーザー空間ポインタを検証。
  カーネルアドレス (>= 0x0000_7FFF_FFFF_FFFF) へのアクセスを完全に拒否する。
- CRIT-02: io_port.rs に caller_has_port_privilege() を追加。
  Service/Core 権限のプロセス以外からの I/O ポートアクセスを EPERM で拒否。
- CRIT-04: exec.rs の ELF セグメント読み込みで checked_add を使用し
  src_off + filesz のオーバーフロー・範囲外アクセスを防止。
- CRIT-05: exec.rs の ELF ローダーで p_vaddr + p_memsz が
  ユーザー空間の上限 (USER_SPACE_END) を超えないことを検証。

## High 修正
- HIGH-02: fs.rs::read() でロックを解放せずに FileHandle にアクセスするよう修正。
  close() との競合による use-after-free を防止。
- HIGH-03: process.rs の brk() と mmap() にユーザー空間アドレス範囲チェックを追加。
  カーネルアドレスへのページマップを拒否する。

## Medium 修正
- MED-03: mem/user.rs の alloc_user_stack() にNO_EXECUTEフラグを追加。
  スタック上のシェルコード実行を防止する。
- MED-05: syscall_entry.rs の update_kernel_rsp() / init_syscall() で
  Ordering::Relaxed を Ordering::SeqCst に変更。メモリ順序を保証する。
- MED-07: elf/loader.rs の parse_elf_header() に e_machine == EM_X86_64 (0x3E)
  の検証を追加。非x86-64 ELFファイルを拒否する。
- MED-08: exec.rs の ELF プログラムヘッダ走査で phentsz == 0 チェックと
  checked_mul/checked_add によるオーバーフロー防止を実装。

## Low 修正
- LOW-01: idt.rs の generic_interrupt_handler() でスレーブPICへの不正なEOI送信を
  削除。マスターPICのみに EOI を送りスプリアス割り込みを防止。
- LOW-06: task/context.rs の switch_to_thread_from_isr() からコンテキストスイッチ
  毎に GDT・ユーザーコード・スタック内容をダンプするデバッグコードを削除。
  情報漏洩リスクとパフォーマンス低下を解消。

https://claude.ai/code/session_014Fnt78JQY3gMLB7Piy6V7k
## Critical 修正
- C-2: IRQ1(キーボード)ハンドラを IDT ベクタ33に登録。未登録のままでは
  キーストロークのたびに #GP → システム停止が発生していた。
- C-3: CVE-2012-0217 対策。SYSRETQ 前にユーザー RSP の正規アドレスチェック
  (SAR 47ビット)を追加。非正規アドレス検出時はプロセスを終了させる。
- C-7: init/fs.rs の EXT2 パス解析に ".." / "." チェックを追加し
  ディレクトリトラバーサルを防止。

## High 修正
- H-1: interrupt/syscall.rs の重複 STAR/LSTAR/FMASK MSR 初期化関数を
  interrupt/mod.rs のエクスポートから除去。syscall_entry::init_syscall() に一本化。
- H-15: ata.rs の identify コマンド後 DRQ 待ちループに 1_000_000 回の
  タイムアウトを追加。無限ループによるハングを防止。
- H-16: ata.rs の write_lba28() でスレーブドライブ選択ビットが常に
  0xE0 (マスタ) になっていたバグを修正。DriveType::Slave では 0xF0 を使用。
- H-17: sleep_until() の永眠バグ修正。sleep_thread() でSleeping状態にした後
  yield_now() を呼ぶと現スレッドが2度とスケジュールされず wake_thread() が
  実行されなかった。ビジーウェイトループに変更して正常動作に修正。

## Medium 修正
- MED-27: exec.rs でエントリポイントが 0 の ELF を EINVAL で拒否。
  以前はアドレス 0 にジャンプしてページフォルト等を引き起こしていた。
- MED-32: init/mod.rs で割り込み有効化 (sti) を PIT/スケジューラ/タイマー
  初期化の後に移動。初期化前にタイマー割り込みが発火する競合状態を解消。
- time.rs の clock_gettime() に validate_user_ptr() (16バイト) を追加。

## Low 修正
- L-1: cpu.rs の enable_sse() で CR4 ビット20 (SMEP) とビット21 (SMAP) を
  セット。カーネルモードでのユーザーページ実行/アクセスを禁止し、
  ret2usr 攻撃と誤ったユーザーメモリアクセスを防止する。

https://claude.ai/code/session_014Fnt78JQY3gMLB7Piy6V7k
…ro-div

- cpu.rs: Enable EFER.NXE before SSE/FPU init so NO_EXECUTE PTEs are honoured
- mem/allocator.rs: Add NO_EXECUTE flag to kernel heap pages (W^X enforcement)
- init/fs.rs: Guard inode() against inodes_per_group==0 divide-by-zero (#30);
  guard data_block_number() against block_size==0 divide-by-zero
- task/thread.rs+mod.rs: Export thread_id_exists(u64)->bool for IPC validation
- syscall/ipc.rs: Reject send() to non-existent thread to prevent ghost-message
  injection / IPC mailbox DoS (#14)
- syscall/types.rs+mod.rs+task.rs: Add GetThreadPrivilege syscall (527) that
  returns 0=Core / 1=Service / 2=User for a given thread ID (#22)
- user/sys.rs+task.rs: Mirror GetThreadPrivilege in user-space swiftlib
- services/disk/main.rs: Reject IPC requests from User-level processes using
  the new GetThreadPrivilege syscall (#22)

https://claude.ai/code/session_014Fnt78JQY3gMLB7Piy6V7k
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
…bilities

Harden ELF/exec boundary handling and close remaining high-priority review findings
- Updated SECURITY_REVIEW.md with additional security checks and mitigations.
- Implemented frame recycling in the BitmapFrameAllocator to prevent double-free vulnerabilities.
- Added checks for usable frame addresses during deallocation.
- Introduced a mechanism to protect kernel text pages from being writable.
- Enhanced exec system calls to restrict service execution to authorized processes only.
- Improved error handling in file system and process management system calls.
- Implemented user range checks in memory management functions to prevent invalid access.
- Added unmap functionality in paging to properly release memory.
- Refactored thread management to include guard bytes for kernel stacks.
…udit-4Hrsd

Enhance security architecture and address critical vulnerabilities
@tas0dev tas0dev self-requested a review March 3, 2026 02:13
@tas0dev tas0dev added bug Something isn't working good first issue Good for newcomers labels Mar 3, 2026
@tas0dev
Copy link
Owner

tas0dev commented Mar 3, 2026

まずビルドが通るようになってからパッチを送信するようにしてください。

jin@jin-pc:~/Documents/SwiftCore/src/services/disk$ cargo build
   Compiling disk v0.1.0 (/home/jin/Documents/SwiftCore/src/services/disk)
error[E0308]: mismatched types
   --> src/ata.rs:319:47
    |
319 |         let lba_top = (((lba >> 24) & 0x0F) | drive_sel) as u8;
    |                                               ^^^^^^^^^ expected `u64`, found `u8`

error[E0277]: no implementation for `u64 | u8`
   --> src/ata.rs:319:45
    |
319 |         let lba_top = (((lba >> 24) & 0x0F) | drive_sel) as u8;
    |                                             ^ no implementation for `u64 | u8`
    |
    = help: the trait `BitOr<u8>` is not implemented for `u64`
help: the following other types implement trait `BitOr<Rhs>`
   --> /home/jin/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/bit.rs:278:9
    |
278 |         impl const BitOr for $t {
    |         ^^^^^^^^^^^^^^^^^^^^^^^ `u64` implements `BitOr`
...
291 | bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
    | ------------------------------------------------------------------------ in this macro invocation
    |
   ::: /home/jin/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/internal_macros.rs:22:9
    |
 22 |         impl const $imp<$u> for &$t {
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&u64` implements `BitOr<u64>`
...
 33 |         impl const $imp<&$u> for $t {
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `u64` implements `BitOr<&u64>`
...
 44 |         impl const $imp<&$u> for &$t {
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&u64` implements `BitOr`
    = note: this error originates in the macro `bitor_impl` (in Nightly builds, run with -Z macro-backtrace for more info)

Some errors have detailed explanations: E0277, E0308.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `disk` (bin "disk") due to 2 previous errors

@minto-dane minto-dane closed this Mar 3, 2026
@tas0dev tas0dev reopened this Mar 3, 2026
tas0dev
tas0dev previously requested changes Mar 3, 2026
Copy link
Owner

@tas0dev tas0dev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

修正してほしい箇所を送信しました。対応お願いします。

unsafe {
core::arch::asm!("lea {}, [rip]", out(reg) rip);
}
let page = Page::<Size4KiB>::containing_address(VirtAddr::new(rip & !0xfffu64));
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

現在のRIPを含む単一のページしかro化していないように見えます。カーネル.textセクション全体を対象にしない限り、HIGH-06の意図する「書き込み不可のテキストページ」は実現できません。
なので、リンカスクリプトに __text_start / __text_end シンボルを定義し、その範囲を反復処理する実装が必要だと思います。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__text_start / __text_end をリンカスクリプトに追加し、.text 全範囲をページ単位で走査して RO
化する実装に修正いたします

///
/// NXE (No-Execute Enable) を IA32_EFER MSR (0xC0000080) のビット11にセットする。
/// これにより PTE の bit 63 (NO_EXECUTE) が有効になり、データページでのコード実行を防ぐ。
unsafe fn enable_nxe() {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SMEP/SMAPはSSEと無関係なセキュリティ機能です。今は同一のCR4書き込みにまとめてしまっているので依存関係が不明瞭になっているようにかんじました。

enable_smep_smap()のような独立した関数に分離してinit()から明示的に呼び出すべきだと思います。

もしかしたら、CR4への書き込みを最小限にしたい(特権命令だから)のなら、計算過程はせめて関数を分けて、書き込みを一気に行うべきだと思います。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

、SMEP/SMAP は enable_smep_smap() に分離し、init() から明示的に呼び出す形に整理します(SSE 初期化から責務を分離する)。

@@ -58,16 +62,8 @@ pub fn clock_gettime(clk_id: u64, ts_ptr: u64) -> u64 {
/// # 戻り値
/// 成功時は0
pub fn sleep_until(ticks: u64) -> u64 {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

旧実装のスリープして起床させる方式をやめて、ループyieldに変えていますが、タイマー割り込みが他スレッドを起床させない場合、CPUのリソースを食い続けませんか?
スリープ中スレッドをスリーピング状態にしてスケジューラがスキップする、タイマー割り込みでwakeする実装が望ましくないですか?

なぜこのような実装にしたのですか??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

busy-yield 方式はCPU消費が大きいため取り下げ、スレッドを Sleeping に遷移させてタイマー割り込みで wake する方式へ戻します

return None;
}
let ptr = unsafe { &raw const KSTACK_POOL as *const _ as usize + off } as u64;
// ガード領域を確保してから実スタックを返す(論理ガード)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

オフセット確保はNEXT_KSTACK_OFFSET.fetch_addで既に安全に行われています。
KSTACK_POOL.lock()as_ptr()のためだけに取得されていますが、static SpinLock<[u8; N]>のアドレスは不変なため、ロックは不要です。
ロックを保持したままSome(ptr)を返すことで、他スレッドのスタック確保が不必要にブロックされると思います。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

KSTACK_POOL.lock() は不要だったため削除し、固定アドレス参照でスタック先頭を計算するように修正します


// 簡易ブロッキング: 子スレッドが消えるまで待機
loop {
for idx in 0..target_count {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

子プロセスが何らかの理由でゾンビ状態のまま残留したり、Terminatedにならないとき、呼び出し元スレッドが永久に抜けられないです。タイムアウトなどのエラー処理が必要だと思います。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wait にフェイルセーフのタイムアウトを追加し、一定時間で ETIMEDOUT を返すようにします

crate::debug!("Created user page table at {:#x}", new_pt_phys);

// ELFアーキテクチャ検証 (MED-07)
const EM_X86_64: u16 = 0x3E;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EM_X86_64を多重定義しすぎじゃ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EM_X86_64 はファイルスコープ定数に統一し、重複定義を解消します

}

// 送信先スレッドが実際に存在するか確認 (#14: ゴーストメッセージ注入防止)
if !crate::task::thread_id_exists(dest_thread_id) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

チェックとエンキューの間にスレッドが終了した場合、存在しないスレッド宛のメッセージが格納されてしまいます。
ゴーストメッセージの注入防止という意図は理解できますが、メッセージ送信のatomic性に関するコメントを追記してほしいです。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

存在チェックと enqueue が原子的でない点(チェック後終了で孤立メッセージが残り得る)をコメントで明記します

return crate::syscall::types::EINVAL;
}
};
let _ = vend;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vendってなんですか?なににつかっているんですか?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vend は不要変数だったため削除し、オーバーフローチェックは match のみで完結する形に整理します

if crate::task::add_process(proc).is_none() {
return crate::syscall::types::EINVAL;
}
if process_name.ends_with("core.service") || path.ends_with("core.service") {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

core.serviceが二度起動された場合、SERVICE_MANAGER_PIDが新しいPIDで上書きされる。
compare_exchangeを使って「一度だけ設定可能」にするか、二重起動を拒否するチェックを追加すべき。

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SERVICE_MANAGER_PID は compare_exchangeで一度だけ設定可能にし、二重起動は拒否するように修正します

minto-dane and others added 7 commits March 2, 2026 21:50
- Introduced `with_user_memory_access` function to safely access user memory during syscalls, ensuring proper CR3 switching for KPTI.
- Updated syscall implementations (write, read, log, send, recv, etc.) to utilize the new memory access function.
- Enhanced process management with `fork`, `wait`, and `exit` handling to support process termination and zombie state management.
- Added atomic operations for managing per-CPU state, including kernel CR3 and syscall kernel stack pointer.
- Improved ELF loading with ASLR for PIE binaries, enhancing security and memory layout randomness.
- Refactored task and thread management to track syscall context and ensure proper privilege level handling during context switches.
…ties

- Added panic-abort-tests to .cargo/config.toml for UEFI target.
- Enhanced build_apps and build_service functions to support JSON target specifications.
- Introduced host target tool fallback in build_newlib for improved compatibility.
- Added wake_due_sleepers function to manage sleeping threads in time.rs.
- Implemented timeout handling in process wait function.
- Updated linker script to define text section markers.
- Refactored ATA drive logic for improved clarity.
- Updated filesystem service configurations to include necessary build features.
Integrate security hardening changes while preserving current dev fixes and resolving conflicts in syscall exec/process.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
以下の修正を一括で適用し、セキュリティと安定性を強化しました。

[Security hardening]
- `validate_user_ptr` を強化し、canonical範囲チェックに加えて
  「現在プロセスのユーザーページテーブルで実際にマップ済みか」を検証するよう変更。
- `paging` にユーザーマッピング検証ヘルパを追加
  (`is_user_range_mapped_in_table` ほか) し、ユーザーポインタ検証の精度を向上。
- `munmap` 経路で `USER_ACCESSIBLE` なページのみを解放対象とし、
  共有カーネルマッピングの誤解放リスクを低減。
- `map_and_copy_segment_to` の `PageAlreadyMapped` 分岐で旧フレームを解放し、
  固定アドレス再マップ時の物理フレームリークを解消。
- 失敗時ロールバック用に `destroy_user_page_table` を追加し、
  fork/exec失敗経路のリソースリークを防止。

[Process / syscall correctness]
- `brk` 拡張時の開始ページ計算を見直し、既存ヒープページの破壊を回避。
- `fork` で `add_process` 後に失敗した場合のロールバックを実装
  (子プロセス削除 + 子ページテーブル破棄)。
- fork/clone のユーザーコンテキスト保存を syscall/int0x80 経路で統一。
- futex を待機キュー方式で安定化し、タイムアウト/cleanup連携を強化。

[IPC / FS isolation]
- IPC メッセージに宛先 `to` を保持し、受信時に宛先一致チェックを実施。
- TID を固定インデックス扱いしない参照に改善し、誤配送リスクを低減。
- `len > 0 && buf_ptr == 0` を `EFAULT` として拒否。
- FSハンドルに `owner_pid` を導入し、`read/seek/close/fstat` で所有者検証を追加。
  これにより他プロセスFD操作を拒否。

[Scheduler / task / percpu]
- current thread 管理を per-CPU 経路で整理し、割り込み境界での整合性を改善。
- context switch 付近の安全性を補強し、競合窓を最小化。

[Clippy cleanup / maintainability]
- `cargo clippy --all-targets --all-features` の指摘を反映:
  - `strip_prefix` 利用への置換
  - `matches!` 利用への置換
  - ループの iterator 化
  - `Default` 実装追加 (複数型)
  - 不要キャストの削減
  - unsafe API の `# Safety` ドキュメント補強
  - ほか軽微な可読性改善

[Validation]
- `cargo fmt --all`
- `cargo build -q`
- `cargo test -q`
- `cargo clippy --all-targets --all-features -q`

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@minto-dane
Copy link
Contributor Author

minto-dane commented Mar 3, 2026

Build should be fine now

minto-dane and others added 3 commits March 3, 2026 16:14
- unify syscall C-string reads

- tighten service manager authorization checks

- mix RDRAND into ASLR seeds

- add kernel stack guard corruption checks

- reduce invalid-opcode information exposure

- add consolidated SECURITY_REVIEW.md

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Fix CI newlib user-lib build failure (E0463: can't find crate for core) by installing the rust target required by builders/newlib.rs.

Also declare both targets in rust-toolchain.toml for local parity.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Mark completed/partial std enablement items based on current dev implementation and security hardening state.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@minto-dane minto-dane changed the title セキュリティアーキテクチャを強化し、重大な脆弱性に対処する dev: セキュリティ基盤強化・Linux互換syscall拡張 Mar 3, 2026
minto-dane and others added 3 commits March 3, 2026 17:00
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

本PRは SwiftCore カーネルのセキュリティ境界(syscall/user memory access/KPTI/SMAP など)を強化しつつ、Linux 互換 syscall の拡張、プロセス資源回収・IPC 整合性の改善、CI/CD と監査ドキュメント整備をまとめて取り込む統合PRです。

Changes:

  • syscall 境界の fail-closed 化(user pointer 検証、user memory access 統一、KPTI/CR3 切替、SYSRET 前検証など)
  • Linux 互換 syscall の実装拡充(mmap/munmap/brk/wait/futex/arch_prctl/clock_gettime/getcwd ほか)とプロセス/IPC 周辺の整合性改善
  • CI(build/test/security)追加・再現性改善、および SECURITY_REVIEW.md 等のドキュメント整備

Reviewed changes

Copilot reviewed 58 out of 58 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
std-todo.md dev 実装状況のステータス表を追加
src/user/task.rs GetThreadPrivilege 用のユーザー API 追加
src/user/sys.rs syscall 番号に GetThreadPrivilege を追加
src/services/fs/.cargo/config.toml build-std 設定を追加
src/services/disk/src/main.rs IPC 受信元の権限チェックを追加
src/services/disk/src/ata.rs DRQ wait のタイムアウト追加、Slave 対応など修正
src/services/disk/.cargo/config.toml build-std 設定を追加
src/linker.ld .text 範囲シンボル(__text_start/__text_end)を追加
src/core/util/fifo.rs Fifo に Default 実装を追加
src/core/task/usermode.rs Safety 要件を doc に明記
src/core/task/thread.rs syscall/KPTI 用スレッド状態・カーネルスタックガード等を追加
src/core/task/scheduler.rs syscall 中の tick 抑止、割り込み禁止区間での切替強化等
src/core/task/process.rs exit_code/zombie 回収 API 追加、reap に page table 破棄を接続
src/core/task/mod.rs 追加した task/process/thread API を re-export
src/core/task/ids.rs ProcessId/ThreadId の from_u64 と Default を追加
src/core/task/elf.rs ELF 検証強化、PIE の ASLR 強化、境界計算の checked 化
src/core/task/context.rs guard 検知、Safety doc、Default 実装等
src/core/syscall/types.rs GetThreadPrivilege の syscall 番号を追加
src/core/syscall/time.rs clock_gettime の user ptr 検証、sleep キュー実装
src/core/syscall/task.rs GetThreadPrivilege 実装、name 取得の user memory 安全化
src/core/syscall/syscall_entry.rs per-CPU GS ベース化、KPTI enter/leave、SYSRET 前チェック等
src/core/syscall/process.rs brk/mmap/munmap/wait/futex/arch_prctl 等の強化・実装拡張
src/core/syscall/mod.rs validate_user_ptr/read_user_cstring/with_user_memory_access の導入、dispatch 更新
src/core/syscall/ipc.rs 宛先スロット世代を用いた誤配送防止 + user ptr 検証
src/core/syscall/io_port.rs I/O ポート syscall の権限チェック追加
src/core/syscall/io.rs read/write/log の user ptr 検証と KPTI 経路の統一
src/core/syscall/fs.rs FD owner 分離、user ptr 検証、UAF 窓の抑止等
src/core/syscall/exec.rs .service 起動認可強化、ELF 検証、ASLR 強化等
src/core/syscall/console.rs console write の user ptr 検証
src/core/result.rs matches! での簡潔化
src/core/percpu.rs per-CPU 状態管理基盤(GS ベース等)を追加
src/core/panic.rs macro 内参照を $crate に修正
src/core/mem/user.rs ユーザースタックに NX 付与
src/core/mem/paging.rs user range mapped 検証、clone/destroy/unmap、kernel .text 保護等
src/core/mem/frame.rs フレーム再利用スタック導入、deallocate_frame 追加
src/core/mem/allocator.rs カーネルヒープを NX に、OOM 経路の簡潔化
src/core/lib.rs percpu モジュールを追加公開
src/core/kernel.rs core.service を service manager として登録する処理を追加
src/core/interrupt/timer.rs IRQ 入口/出口の KPTI 対応、sleep/futex タイムアウト wake
src/core/interrupt/spinlock.rs force_unlock の Safety doc、as_ptr 追加
src/core/interrupt/pic.rs EOI の Safety doc 追加
src/core/interrupt/mod.rs syscall モジュールの公開整理
src/core/interrupt/idt.rs IRQ1 ハンドラ追加、過剰ダンプ削除、EOI 送信方針修正
src/core/init/mod.rs PIT→scheduler→timer→割り込み enable の順に初期化順序を修正
src/core/init/fs.rs ext2 パースの除算パニック回避、path traversal 拒否等
src/core/elf/loader.rs e_machine 検証、型 alias 追加
src/core/cpu.rs NXE/SMEP/SMAP/RDRAND 等の有効化・検出を追加
src/boot/loader.rs boot_info 参照の安全化等
rust-toolchain.toml targets を追加
builders/services.rs json target spec の扱い改善、パース処理改善
builders/newlib.rs toolchain フォールバック等の改善
builders/apps.rs json target spec 使用時の -Z 付与
build.rs unwrap_or_else を使用してエラー処理を統一
SECURITY_REVIEW.md セキュリティモデル仕様(コード導出版)を追加
README.md docs 参照を追加
.github/workflows/security.yml dependency-review / cargo-audit を追加
.github/workflows/ci.yml build/test/fmt の CI を追加
.cargo/config.toml panic-abort-tests を追加、runner 設定の整形

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +31 to +36
let end = match ptr.checked_add(len) {
Some(e) => e,
None => return false, // 整数オーバーフロー
};
if ptr >= USER_SPACE_END || end > USER_SPACE_END {
return false;
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validate_user_ptr のユーザー空間境界判定が off-by-one になっています。end = ptr + len のまま ptr >= USER_SPACE_END / end > USER_SPACE_END をチェックすると、例えば ptr == USER_SPACE_END かつ len == 1(最終1バイト)を不正として扱ってしまいます。ptr + len - 1 の包含終端で評価する(len==0 は別扱い)か、比較条件をそれに合わせて修正してください。

Copilot uses AI. Check for mistakes.
Comment on lines +60 to +67
let mut bytes = Vec::with_capacity(max_len);
with_user_memory_access(|| {
for i in 0..max_len {
let addr = ptr.saturating_add(i as u64);
if !validate_user_ptr(addr, 1) {
return Err(EFAULT);
}
let b = unsafe { core::ptr::read(addr as *const u8) };
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

read_user_cstringwith_user_memory_access 内で 1バイトごとに validate_user_ptr(addr, 1) を呼んでおり、最大長まで O(n) 回のページテーブル走査になります。先に「最大 max_len までの連続範囲」がユーザーページテーブル上でマップされているかをまとめて検証(またはページ境界ごとに検証)してから読み取る形にすると、性能面と実装の単純さが改善します。

Copilot uses AI. Check for mistakes.
Comment on lines 9 to 14
.text : {
__text_start = .;
*(.text._start)
*(.text .text.*)
__text_end = .;
}
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

linker.ld__text_start / __text_end シンボルを定義していますが、src/core/mem/paging.rs 側でも同名の #[no_mangle] static __text_start/__text_end を追加しており、リンク時に多重定義になる可能性があります。どちらかに統一し、Rust 側は linker script のシンボルを extern "C" { static __text_start: u8; ... } として参照する形にするのが安全です。

Copilot uses AI. Check for mistakes.
Comment on lines +29 to +41
// COFF の .text$X セクション順序を使って、.text の先頭/末尾マーカーを置く。
#[used]
#[unsafe(no_mangle)]
#[unsafe(link_section = ".text$A")]
static __text_start: u8 = 0;
#[used]
#[unsafe(no_mangle)]
#[unsafe(link_section = ".text$Z")]
static __text_end: u8 = 0;

fn protect_kernel_text_pages(page_table: &mut OffsetPageTable<'static>) {
let text_start = core::ptr::addr_of!(__text_start) as u64;
let text_end = core::ptr::addr_of!(__text_end) as u64;
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__text_start / __text_end#[no_mangle] static として定義していますが、linker.ld 側でも同名シンボルを定義しているためリンク時の多重定義リスクがあります。また、このマーカーは .text$A/.text$Z セクションに配置されていますが、linker.ld.text 収集パターン(*(.text .text.*))に一致せず orphan section になり得ます。linker script の __text_start/__text_end を参照する方式に統一してください。

Suggested change
// COFF の .text$X セクション順序を使って、.text の先頭/末尾マーカーを置く。
#[used]
#[unsafe(no_mangle)]
#[unsafe(link_section = ".text$A")]
static __text_start: u8 = 0;
#[used]
#[unsafe(no_mangle)]
#[unsafe(link_section = ".text$Z")]
static __text_end: u8 = 0;
fn protect_kernel_text_pages(page_table: &mut OffsetPageTable<'static>) {
let text_start = core::ptr::addr_of!(__text_start) as u64;
let text_end = core::ptr::addr_of!(__text_end) as u64;
// リンカスクリプトで定義された .text セクションの先頭/末尾マーカーを参照する。
extern "C" {
/// .text セクションの先頭アドレス(linker.ld で定義)
static __text_start: u8;
/// .text セクションの末尾アドレス(linker.ld で定義)
static __text_end: u8;
}
fn protect_kernel_text_pages(page_table: &mut OffsetPageTable<'static>) {
let text_start = unsafe { &__text_start as *const u8 as u64 };
let text_end = unsafe { &__text_end as *const u8 as u64 };

Copilot uses AI. Check for mistakes.
Comment on lines +258 to +265
// CVE-2012-0217 緩和策: SYSRETQ 前にユーザー RSP の正規アドレスチェック
// Intel CPU では SYSRETQ 実行時にRSPが非正規アドレス(bit 63:47 が不一致)だと
// Ring 0 で #GP が発生し、攻撃者がRIPを制御できる (CVE-2012-0217)
// ユーザー空間の正規アドレス: bit 63:47 = 0b000...0 (0x0000_7FFF_FFFF_FFFF 以下)
"mov rax, r9",
"sar rax, 47", // 算術右シフト47bit: 正規なら全ビット0
"test rax, rax",
"jnz 2f", // 非正規アドレス → プロセスを終了
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CVE-2012-0217 緩和の canonicality チェック対象が r9(復帰先 user RSP)だけになっていますが、SYSRET の #GP 誘発で問題になるのは主に RCX(復帰先 user RIP)の非 canonical 値です。現状だと non-canonical RIP を防げないため、SYSRET 直前に RCX も canonical チェックし、非 canonical の場合は IRET 経路へフォールバック/プロセス終了などの処理を追加してください。

Copilot uses AI. Check for mistakes.
minto-dane and others added 12 commits March 3, 2026 19:53
- In `exec.rs`, adjusted the calculation of `stub_addr` to ensure it is derived from `stack_end_vaddr` and added error handling for overflow. Removed unnecessary heap size adjustments.
- Updated `std-todo.md` to reflect the current status of Rust `std` implementation on SwiftCore, including completed tasks and remaining priorities.
- Revised `todo.md` to include recent status updates on security features and syscall implementations, ensuring clarity on the project's progress and future tasks.
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Co-authored-by: minto-dane <205936182+minto-dane@users.noreply.github.com>
Harden critical memory-validation paths found in exhaustive manual review
@tas0dev tas0dev dismissed their stale review March 4, 2026 07:05

一度取り下げます

@tas0dev
Copy link
Owner

tas0dev commented Mar 4, 2026

いくつか気になる箇所はありますが大体大丈夫だと思うのでマージします。
ありがとうございました!

@tas0dev tas0dev merged commit 48e6094 into tas0dev:dev Mar 4, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working good first issue Good for newcomers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants