@@ -11,7 +11,7 @@ use crate::netns::NetworkNamespace;
1111use crate :: sandbox;
1212use miette:: { IntoDiagnostic , Result } ;
1313use nix:: sys:: signal:: { self , Signal } ;
14- use nix:: unistd:: { Group , Pid , User } ;
14+ use nix:: unistd:: { Gid , Group , Pid , Uid , User } ;
1515use openshell_core:: policy:: { NetworkMode , SandboxPolicy } ;
1616use std:: collections:: HashMap ;
1717use std:: ffi:: CString ;
@@ -748,17 +748,36 @@ impl Drop for ProcessHandle {
748748 }
749749}
750750
751- /// Validate that the ` sandbox` user exists in this image.
751+ /// Validate that the configured sandbox identity exists in this image.
752752///
753- /// All sandbox images must include a `sandbox` user for privilege dropping.
754- /// This check runs at supervisor startup (inside the container) where we can
755- /// inspect `/etc/passwd`. If the user is missing, the sandbox fails fast
756- /// with a clear error instead of silently running child processes as root.
753+ /// When the identity is the literal `"sandbox"`, verifies the user exists
754+ /// in `/etc/passwd` (all sandbox images ship with one).
755+ ///
756+ /// When the identity is a numeric UID, skips the passwd lookup entirely —
757+ /// the kernel will use the resolved UID regardless of whether an entry
758+ /// exists in `/etc/passwd`. Logs an OCSF event confirming numeric UID usage.
759+ /// Non-numeric, non-"sandbox" values are rejected.
757760#[ cfg( unix) ]
758761pub fn validate_sandbox_user ( policy : & SandboxPolicy ) -> Result < ( ) > {
759- let user_name = policy. process . run_as_user . as_deref ( ) . unwrap_or ( "sandbox" ) ;
762+ let identity = policy. process . run_as_user . as_deref ( ) . unwrap_or ( "sandbox" ) ;
763+
764+ // Numeric UID — no passwd entry required; kernel resolves directly.
765+ if openshell_policy:: is_valid_sandbox_identity ( identity)
766+ && identity. parse :: < u32 > ( ) . is_ok ( )
767+ {
768+ openshell_ocsf:: ocsf_emit!(
769+ openshell_ocsf:: ConfigStateChangeBuilder :: new( openshell_ocsf:: ctx:: ctx( ) )
770+ . severity( openshell_ocsf:: SeverityId :: Informational )
771+ . status( openshell_ocsf:: StatusId :: Success )
772+ . state( openshell_ocsf:: StateId :: Enabled , "validated" )
773+ . message( format!( "Accepted numeric UID {identity} (no passwd entry required)" ) )
774+ . build( )
775+ ) ;
776+ return Ok ( ( ) ) ;
777+ }
760778
761- if user_name. is_empty ( ) || user_name == "sandbox" {
779+ // "sandbox" name — must exist in /etc/passwd.
780+ if identity == "sandbox" {
762781 match User :: from_name ( "sandbox" ) {
763782 Ok ( Some ( _) ) => {
764783 openshell_ocsf:: ocsf_emit!(
@@ -780,11 +799,34 @@ pub fn validate_sandbox_user(policy: &SandboxPolicy) -> Result<()> {
780799 return Err ( miette:: miette!( "failed to look up 'sandbox' user: {e}" ) ) ;
781800 }
782801 }
802+ } else if !identity. is_empty ( ) {
803+ // Non-numeric, non-sandbox string — attempt passwd lookup.
804+ // This catches cases where someone accidentally put "root" or similar.
805+ match User :: from_name ( identity) {
806+ Ok ( Some ( _) ) => {
807+ tracing:: warn!(
808+ identity,
809+ "non-sandbox user accepted via passwd entry; \
810+ consider using a numeric UID for UID-injected images"
811+ ) ;
812+ }
813+ Ok ( None ) => {
814+ return Err ( miette:: miette!(
815+ "unrecognized sandbox identity '{identity}'; \
816+ expected 'sandbox' or a numeric UID in range [{MIN_SANDBOX_UID}, {MAX_SANDBOX_UID}]"
817+ ) ) ;
818+ }
819+ Err ( e) => {
820+ return Err ( miette:: miette!( "failed to look up identity '{identity}': {e}" ) ) ;
821+ }
822+ }
783823 }
784824
785825 Ok ( ( ) )
786826}
787827
828+ pub use openshell_policy:: { MIN_SANDBOX_UID , MAX_SANDBOX_UID } ;
829+
788830/// Prepare a `read_write` path for the sandboxed process.
789831///
790832/// Returns `true` when the path was created by the supervisor and therefore
@@ -823,9 +865,13 @@ fn prepare_read_write_path(path: &Path) -> Result<bool> {
823865/// Creates `read_write` directories if they don't exist and sets ownership
824866/// on newly-created paths to the configured sandbox user/group. This runs as
825867/// the supervisor (root) before forking the child process.
868+ ///
869+ /// Accepts both name-based identities (resolved via `/etc/passwd`) and numeric
870+ /// UIDs/GIDs (passed directly to `chown` without a passwd lookup).
826871#[ cfg( unix) ]
827872pub fn prepare_filesystem ( policy : & SandboxPolicy ) -> Result < ( ) > {
828873 use nix:: unistd:: chown;
874+ use nix:: unistd:: { Gid , Uid } ;
829875
830876 let user_name = match policy. process . run_as_user . as_deref ( ) {
831877 Some ( name) if !name. is_empty ( ) => Some ( name) ,
@@ -841,27 +887,26 @@ pub fn prepare_filesystem(policy: &SandboxPolicy) -> Result<()> {
841887 return Ok ( ( ) ) ;
842888 }
843889
844- // Resolve user and group
845- let uid = if let Some ( name) = user_name {
846- Some (
847- User :: from_name ( name)
848- . into_diagnostic ( ) ?
849- . ok_or_else ( || miette:: miette!( "Sandbox user not found: {name}" ) ) ?
850- . uid ,
851- )
852- } else {
853- None
890+ // Resolve UID: numeric values are passed directly; names resolve via passwd.
891+ let uid = match user_name {
892+ Some ( name) if name. parse :: < u32 > ( ) . is_ok ( ) => {
893+ Some ( Uid :: from_raw ( name. parse ( ) . into_diagnostic ( ) ?) )
894+ }
895+ Some ( name) => User :: from_name ( name)
896+ . into_diagnostic ( ) ?
897+ . map ( |u| u. uid ) ,
898+ _ => None ,
854899 } ;
855900
856- let gid = if let Some ( name ) = group_name {
857- Some (
858- Group :: from_name ( name )
859- . into_diagnostic ( ) ?
860- . ok_or_else ( || miette :: miette! ( "Sandbox group not found: {name}" ) ) ?
861- . gid ,
862- )
863- } else {
864- None
901+ // Resolve GID: numeric values are passed directly; names resolve via group.
902+ let gid = match group_name {
903+ Some ( name ) if name . parse :: < u32 > ( ) . is_ok ( ) => {
904+ Some ( Gid :: from_raw ( name . parse ( ) . into_diagnostic ( ) ?) )
905+ }
906+ Some ( name ) => Group :: from_name ( name )
907+ . into_diagnostic ( ) ?
908+ . map ( |g| g . gid ) ,
909+ _ => None ,
865910 } ;
866911
867912 // Create missing read_write paths and only chown the ones we created.
@@ -914,27 +959,57 @@ pub fn drop_privileges(policy: &SandboxPolicy) -> Result<()> {
914959 return Ok ( ( ) ) ;
915960 }
916961
917- let user = if let Some ( name) = user_name {
918- User :: from_name ( name)
962+ // Resolve UID: numeric values are used directly; names resolve via passwd.
963+ let target_uid = match user_name {
964+ Some ( name) if name. parse :: < u32 > ( ) . is_ok ( ) => Uid :: from_raw (
965+ name. parse ( ) . into_diagnostic ( ) ?,
966+ ) ,
967+ Some ( name) => User :: from_name ( name)
919968 . into_diagnostic ( ) ?
920969 . ok_or_else ( || miette:: miette!( "Sandbox user not found: {name}" ) ) ?
921- } else {
922- User :: from_uid ( nix:: unistd:: geteuid ( ) )
923- . into_diagnostic ( ) ?
924- . ok_or_else ( || miette:: miette!( "Failed to resolve current user" ) ) ?
970+ . uid ,
971+ None => nix:: unistd:: geteuid ( ) ,
925972 } ;
926973
927- let group = if let Some ( name) = group_name {
928- Group :: from_name ( name)
974+ // Resolve group: if a numeric GID is configured use it directly.
975+ // Otherwise try name resolution, then fall back to current user's primary group.
976+ let target_gid = match group_name {
977+ Some ( name) if name. parse :: < u32 > ( ) . is_ok ( ) => Gid :: from_raw (
978+ name. parse ( ) . into_diagnostic ( ) ?,
979+ ) ,
980+ Some ( name) => Group :: from_name ( name)
929981 . into_diagnostic ( ) ?
930982 . ok_or_else ( || miette:: miette!( "Sandbox group not found: {name}" ) ) ?
931- } else {
932- Group :: from_gid ( user. gid )
983+ . gid ,
984+ None => match target_uid. as_raw ( ) {
985+ 0 => nix:: unistd:: getegid ( ) ,
986+ _ => Group :: from_gid (
987+ User :: from_uid ( target_uid)
988+ . into_diagnostic ( ) ?
989+ . ok_or_else ( || miette:: miette!( "Failed to resolve user from UID {target_uid}" ) ) ?
990+ . gid ,
991+ )
933992 . into_diagnostic ( ) ?
934- . ok_or_else ( || miette:: miette!( "Failed to resolve user primary group" ) ) ?
993+ . map_or_else ( nix:: unistd:: getegid, |g| g. gid ) ,
994+ } ,
935995 } ;
936996
937- if user_name. is_some ( ) {
997+ // Resolve the user record for initgroups (if name-based) or skip it (numeric UID).
998+ let user = if user_name. is_some ( ) {
999+ Some (
1000+ User :: from_uid ( target_uid)
1001+ . into_diagnostic ( ) ?
1002+ . ok_or_else ( || miette:: miette!( "Failed to resolve user record for UID {target_uid}" ) ) ?,
1003+ )
1004+ } else {
1005+ None
1006+ } ;
1007+
1008+ // Set supplementary groups only when we have a name-based identity.
1009+ // Numeric UIDs may not have a passwd entry, so initgroups would fail.
1010+ if let Some ( ref user) = user
1011+ && target_uid != nix:: unistd:: geteuid ( )
1012+ {
9381013 let user_cstr =
9391014 CString :: new ( user. name . clone ( ) ) . map_err ( |_| miette:: miette!( "Invalid user name" ) ) ?;
9401015 #[ cfg( any(
@@ -953,43 +1028,49 @@ pub fn drop_privileges(policy: &SandboxPolicy) -> Result<()> {
9531028 target_os = "redox"
9541029 ) ) ) ]
9551030 {
956- nix:: unistd:: initgroups ( user_cstr. as_c_str ( ) , group . gid ) . into_diagnostic ( ) ?;
1031+ nix:: unistd:: initgroups ( user_cstr. as_c_str ( ) , target_gid ) . into_diagnostic ( ) ?;
9571032 }
9581033 }
9591034
960- nix:: unistd:: setgid ( group. gid ) . into_diagnostic ( ) ?;
1035+ if target_gid != nix:: unistd:: getegid ( ) {
1036+ nix:: unistd:: setgid ( target_gid) . into_diagnostic ( ) ?;
1037+ }
9611038
9621039 // Verify effective GID actually changed (defense-in-depth, CWE-250 / CERT POS37-C)
9631040 let effective_gid = nix:: unistd:: getegid ( ) ;
964- if effective_gid != group . gid {
1041+ if effective_gid != target_gid {
9651042 return Err ( miette:: miette!(
9661043 "Privilege drop verification failed: expected effective GID {}, got {}" ,
967- group . gid ,
1044+ target_gid ,
9681045 effective_gid
9691046 ) ) ;
9701047 }
9711048
972- if user_name. is_some ( ) {
973- nix:: unistd:: setuid ( user. uid ) . into_diagnostic ( ) ?;
1049+ if let Some ( _user) = user {
1050+ if target_uid != nix:: unistd:: geteuid ( ) {
1051+ nix:: unistd:: setuid ( target_uid) . into_diagnostic ( ) ?;
1052+ }
9741053
9751054 // Verify effective UID actually changed (defense-in-depth, CWE-250 / CERT POS37-C)
9761055 let effective_uid = nix:: unistd:: geteuid ( ) ;
977- if effective_uid != user . uid {
1056+ if effective_uid != target_uid {
9781057 return Err ( miette:: miette!(
9791058 "Privilege drop verification failed: expected effective UID {}, got {}" ,
980- user . uid ,
1059+ target_uid ,
9811060 effective_uid
9821061 ) ) ;
9831062 }
9841063
9851064 // Verify root cannot be re-acquired (CERT POS37-C hardening).
9861065 // If we dropped from root, setuid(0) must fail; success means privileges
9871066 // were not fully relinquished.
988- if nix:: unistd:: setuid ( nix:: unistd:: Uid :: from_raw ( 0 ) ) . is_ok ( ) && user. uid . as_raw ( ) != 0 {
1067+ if nix:: unistd:: setuid ( Uid :: from_raw ( 0 ) ) . is_ok ( )
1068+ && target_uid. as_raw ( ) != 0
1069+ {
9891070 return Err ( miette:: miette!(
9901071 "Privilege drop verification failed: process can still re-acquire root (UID 0) \
9911072 after switching to UID {}",
992- user . uid
1073+ target_uid
9931074 ) ) ;
9941075 }
9951076 }
@@ -1403,7 +1484,7 @@ mod tests {
14031484 let current_user = User :: from_uid ( nix:: unistd:: geteuid ( ) )
14041485 . unwrap ( )
14051486 . expect ( "current user entry" ) ;
1406- let restricted_group = Group :: from_gid ( nix :: unistd :: Gid :: from_raw ( 0 ) )
1487+ let restricted_group = Group :: from_gid ( Gid :: from_raw ( 0 ) )
14071488 . unwrap ( )
14081489 . expect ( "gid 0 group entry" ) ;
14091490 if restricted_group. gid == nix:: unistd:: getegid ( ) {
@@ -1538,4 +1619,54 @@ mod tests {
15381619 Some ( PathBuf :: from( "/run/spire" ) )
15391620 ) ;
15401621 }
1622+
1623+ // ---- Numeric UID tests (Phase 2) ----
1624+
1625+ #[ test]
1626+ fn drop_privileges_accepts_numeric_uid ( ) {
1627+ // When running as non-root, a numeric UID/GID that matches the
1628+ // current process should succeed without any passwd lookup.
1629+ if nix:: unistd:: geteuid ( ) . is_root ( ) {
1630+ return ;
1631+ }
1632+
1633+ let uid_raw = nix:: unistd:: geteuid ( ) . as_raw ( ) ;
1634+ let gid_raw = nix:: unistd:: getegid ( ) . as_raw ( ) ;
1635+
1636+ let policy = policy_with_process ( ProcessPolicy {
1637+ run_as_user : Some ( uid_raw. to_string ( ) ) ,
1638+ run_as_group : Some ( gid_raw. to_string ( ) ) ,
1639+ } ) ;
1640+
1641+ assert ! (
1642+ drop_privileges( & policy) . is_ok( ) ,
1643+ "should accept current process UID/GID as numeric strings"
1644+ ) ;
1645+ }
1646+
1647+ #[ test]
1648+ fn drop_privileges_numeric_uid_skips_initgroups ( ) {
1649+ // When running as non-root with a numeric user but group matches,
1650+ // initgroups should not be called (guard: target_uid != geteuid()).
1651+ if nix:: unistd:: geteuid ( ) . is_root ( ) {
1652+ return ;
1653+ }
1654+
1655+ let current_uid = nix:: unistd:: geteuid ( ) . as_raw ( ) ;
1656+
1657+ // Use a different group name that exists (the current one).
1658+ let current_group = Group :: from_gid ( nix:: unistd:: getegid ( ) )
1659+ . expect ( "should resolve current group" )
1660+ . expect ( "current group should exist" ) ;
1661+
1662+ let policy = policy_with_process ( ProcessPolicy {
1663+ run_as_user : Some ( current_uid. to_string ( ) ) , // numeric UID, no passwd entry needed
1664+ run_as_group : Some ( current_group. name ) , // name-based group
1665+ } ) ;
1666+
1667+ assert ! (
1668+ drop_privileges( & policy) . is_ok( ) ,
1669+ "should accept numeric UID with name-based group (initgroups guarded)"
1670+ ) ;
1671+ }
15411672}
0 commit comments