Repository navigation
Conversation
|
@tonycoco Could you fix the conflicts? Thanks for the contribution, I need to take a closer look but this seems fine. One thing to note is that changing the Users would need to build and specify their own kernel that includes SMB and/or NFS client capability. One possible alternative/workaround would be if the public homebrew recipe (which isn't managed by the Containerization project maintainers, incidentally) were capable of building and installing a default kernel from using a more expansive config that it embeds. |
476a9c0 to
b2d6e10
Compare
|
@jglogan Merge conflicts are now fixed. I have commits for the kernel and upstream kata as well in the loop but at least this unlocks the container side of things. I also have some changes to the Reference: apple/containerization#681 Tracking: |
|
@tonycoco Thanks! I'll let @dcantah handle apple/containerization#681 as he's already working with you on it. |
|
Looks good and also kata-containers/kata-containers#12374 has been merged! |
|
@jglogan this change is ready to go |
f3ea0d3 to
90cb0b3
Compare
|
cleaned up the commit and rebased |
266ffef to
7a61de3
Compare
ccba96d to
94e947c
Compare
|
Ping for activity again. Let me know if anything else is needed for the merge. |
94e947c to
ed0b4a9
Compare
|
Resolved merge conflicts in |
ed0b4a9 to
c790431
Compare
|
Any update on this? |
|
@tonycoco Thanks for the pings, and for your patience. I'll put this into the plan for this sprint. IIRC I said I wanted to test it locally (which I haven't done yet). I also need to do a little thinking about the architecture for the volume model. I don't think it means any changes to what your PR does, but what we might want to do is mark these options as experimental so that folks don't get wedded to a particular CLI shape. |
|
@tonycoco Could you create an issue describing the feature and use case(s), and add something to the description above indicating that this PR closes the issue? |
e16eea7 to
1dd7340
Compare
|
@jglogan made a few changes and rebased to latest on this. Ready for merge. |
1dd7340 to
bf153be
Compare
There was a problem hiding this comment.
@tonycoco See the review comments for this. I think most of this is workable, but the one thing that gives me concern is that this implementation can store a secret value (the SMB share password) as plain text in mount options on the volume and container (possible if someone creates a container using the client API and attaches an .smb Filesystem).
Before making code changes for this, could you propose a design here in the issue or PR comments for how we can retain the secret value securely (this would likely involve the keychain)? Requirements include:
- Keep the password out of both VolumeConfiguration.options and the persisted ContainerConfiguration
- Retrieve the secret server-side at bootstrap and not in Utility.swift on the client
- Reject password keys in Filesystem for the direct-API case
- Ensure the keychain item gets deleted with the volume
| destination: parsed.destination, | ||
| options: parsed.options | ||
| ) | ||
| } else { |
There was a problem hiding this comment.
Should we validate "local" here? Would there be any backward compatibility issues if we did?
We have the server side validation, but fail-fast would be cheap here.
There was a problem hiding this comment.
Good call. Switched the if/else if/else to a switch with explicit "smb", "nfs", and "local" cases and a throwing default.
No backward-compatibility concern that I can find: driver is a required (non-optional) key in VolumeConfiguration's decoder, and before this PR the server only ever persisted "local" since _create threw driverNotSupported for anything else. So every stored volume already has driver == "local".
| } | ||
|
|
||
| let journalConfig = try driverOpts["journal"].map { try Self.parseJournalConfig($0) } | ||
| let volume: VolumeConfiguration |
There was a problem hiding this comment.
Could you create a ContainerResource.MountOptionValidator as a package enum that ensures that keys and values are syntactically valid?
Perhaps a key validation regex like ^[A-Za-z][A-Za-z0-9_-]{0,63}$ and a value regex like ^[^,\s\p{Cc}]{0,1024}$? The principal thing we want to avoid is injecting commas into values, so the regex rejects them for now (if we need escaped commas in values, we can add that as a separate feature later).
For defense in depth, the validator should also be invoked for smb and nfs mounts in ContainerService.create and in RuntimeService.
An alternative we could look into is to represent the driver and mount options using a type that performs validation on init and deserialization so that we know the options are correct by construction. The one thing we'd need to do with this approach is ensure that we gracefully handle deserialization errors at startup - one invalid option on disk shouldn't break the whole app.
There was a problem hiding this comment.
Added ContainerResource.MountOptionValidator as a package enum with the key/value regexes you suggested (^[A-Za-z][A-Za-z0-9_-]{0,63}$ and ^[^,\s\p{Cc}]{0,1024}$). Options are checked in key order so errors are deterministic, and the violation message names the key but never echoes the value, since it may be a credential.
One refinement: share is validated as a mount source rather than a mount option. It's handed to mount(2) as its own argument and never joined into the comma-separated data string (resolvedMountOptions already filters it out), so the comma/whitespace rule doesn't buy anything there and would reject common Windows share names like //server/My Share. validateShare instead requires non-empty and no control characters (which would truncate or corrupt the C string), with a 4096-character cap. Everything else gets the strict rule.
It's invoked at all four points: VolumesService._create for smb/nfs, ContainersService.create for every mount (covers the direct-API case), RuntimeService.configureContainer before building the guest mount (rejects a tampered bundle with .invalidState, mirroring AttachmentNameValidator.validateStored), and the CLI. The server and runtime call sites go through a new Filesystem.validateMountOptions(), which checks the .smb/.nfs associated share as a source and mountOptions as options, so the validated set is exactly what resolvedMountOptions emits. It's a no-op for non-network types.
I went with validation-at-the-boundary rather than the validate-on-init type for now, since it keeps the Filesystem Codable path unchanged and avoids the "one bad option on disk breaks startup" problem you mentioned. Tests in MountOptionValidatorTests (including that share leniency doesn't leak into username=), plus service-level coverage in VolumesServiceTests and a Filesystem test in FilesystemSMBTests.
bf153be to
b81b40f
Compare
|
@jglogan Here's a proposed design for keeping the SMB password out of persisted state. It follows the existing registry-credential pattern ( Summary
Storage
Write path —
|
|
@jglogan Fixed up all the feedback sans the Keychain stuff. Let me know what you want to do there and I can write up another commit to get that in the same PR, or push it in a different one. |
9a8f643 to
db0078d
Compare
|
I implemented the Keychain stuff in 56e6fdd so you can see the shape, happy to rework any of it based on the questions below. Should be contained in that one commit. |
|
Also, the containerization |
jglogan
left a comment
There was a problem hiding this comment.
@tonycoco I've added comments for a few high priority items. A couple require work in advance of what you have here. The containerization fix will be easy; the XPC API fixes will be more involved but we need to get them in to facilitate other enhancements as well.
| } | ||
| do { | ||
| // Checks the share as a mount source and the remaining options as mount options. | ||
| try MountOptionValidator.validate(driverOpts) |
There was a problem hiding this comment.
This will handle the mount options that get set up on volume creation, but what happens if a user does:
container create -v my-smb-volume:/mnt/data:pass=my-secretThere was a problem hiding this comment.
Ahh ok. Parser.volume puts the third field of -v name:/dest:opts into Filesystem.options ([String]), which resolvedMountOptions appends after mountOptions without running through MountOptionValidator.
I've added MountOptionValidator.validatePerMountOptions(_:), which restricts Filesystem.options on .smb and .nfs mounts to only exact UTF-8 byte matches for "ro" and "rw" (and never echoes the offending value in the error message, in case it's pass=my-secret). I also updated Parser.volume to split per-mount options with omittingEmptySubsequences: false so an empty element in ro,,rw is preserved and rejected. This is enforced fail-fast in Utility.swift as well as in Filesystem.validateMountOptions(), ContainersService, and RuntimeService.
| /// | ||
| /// `pass` is an alias of `password`, and `credentials`/`cred` name a file of credentials. None of | ||
| /// them may appear in a stored volume or container configuration; the password is kept in the | ||
| /// credential store instead and added to the mount options only at bootstrap. |
There was a problem hiding this comment.
What do you think about an allow list of CIFS/NFS keys, so that we fail closed on any new option that carries a secret? It means that we'd need PRs to enable new options, but it's the safer choice.
In any case password2 and pass2 can also carry secrets in Linux: https://man7.org/linux/man-pages/man8/mount.cifs.8.html
There was a problem hiding this comment.
Yep. Failing closed with an explicit per-driver allowlist is much safer.
I've updated MountOptionValidator to:
- Add password2 and pass2 to secretKeys.
- Define explicit allowedSMBKeys and allowedNFSKeys sets (validateSMBOptions(_:allowPassword:) and validateNFSOptions(_:)), excluding secret keys and CIFS connection redirects (ip, addr, source, unc). password is accepted only at volume create time (allowPassword: true), where VolumesService strips it and stores it in the keychain before persisting VolumeConfiguration.
- Invoke the per-driver allowlists in VolumeCreate (CLI), VolumesService, Filesystem.validateMountOptions(), ContainersService, and RuntimeService.
| try await store.create(volume) | ||
| // Store the secret before the volume so a volume never exists without its credential. | ||
| // If the volume cannot then be stored, remove the credential again. | ||
| if let credential { |
There was a problem hiding this comment.
When an smb volume is created without a password, remove any existing keychain item for that volume name. If the delete fails, fail the create (today it's only logged), since a surviving item could be reused by the new volume.
There was a problem hiding this comment.
Yeah we can. if a previous volume's keychain cleanup failed or its directory was removed out of band, a new guest SMB volume created under the same name shouldn't inherit the stale credential.
Updated VolumesService._create so that when driver == "smb" and credential == nil, it calls try credentialStore.delete(volume: name) (which is a no-op on errSecItemNotFound) before store.create(volume).
| czConfig.mounts.append(mount.asMount) | ||
| // The SMB password is added only to the guest mount that is built here. `config` | ||
| // stays as stored, so the runtime never holds or reports the secret elsewhere. | ||
| czConfig.mounts.append(Self.applyMountCredential(from: mountCredentials, to: mount).asMount) |
There was a problem hiding this comment.
At present there's an issue where, when a mount error occurs, containerization can log the mount options, and the error thrown back to container also contains them, so we can leak sensitive information into the logs.
I'm going to fix the containerization side but we'll need to bump the containerization version here, or in a PR you can pick up in a rebase, once we've a new tag.
There was a problem hiding this comment.
Once the new containerization tag is cut or lands on main, I'll rebase and pick up the version bump here.
|
|
||
| case block(format: String, cache: CacheMode, sync: SyncMode) | ||
| case volume(name: String, format: String, cache: CacheMode, sync: SyncMode) | ||
| case smb(name: String? = nil, share: String, mountOptions: [String: String]) |
There was a problem hiding this comment.
This creates a compatibility where an existing client (say a GUI or socktainer) will break with a new version of container, if the user creates a SMB or NFS volume.
Rather than break things in this way, I'm going to have a crack at making a breaking change to the XPC client such that we can evolve enums (and to add a container API version), after which we'll be able to add these cases.
There was a problem hiding this comment.
Makes sense for existing XPC clients decoding Filesystem.FSType. I've pushed the credential and validation fixes here so this PR will be ready to rebase onto your XPC enum-evolution / API version changes once they land.
A server-side keychain write is fine, as long as you're handling the credential appropriately. Should we move from the legacy keychain to the data protection keychain at some point, we can revisit this.
Yep, that's consistent with the registry credential domain.
For a missing keychain item, fail bootstrap if the volume has a |
jglogan
left a comment
There was a problem hiding this comment.
I've added one more thing we need to do to protect the credentials.
| /// password (for example, a guest share). Any other failure to read the credential store | ||
| /// fails the bootstrap, since starting the container would otherwise fail later with a | ||
| /// less useful permission error from the guest. | ||
| private nonisolated func resolveMountCredentials(for config: ContainerConfiguration) throws -> [String: String] { |
There was a problem hiding this comment.
One other issue: the key as it stands allows a direct .smb(name: <existing volume>, share: <other server>) call to send a user's credential to another server.
An smb mount is derived from its volume. At container creation time, the caller can say which volume, where to mount it, and whether it's read-only.
So, at create for an SMB volume:
- A mount with a name must refer to an existing volume whose driver is smb. Otherwise reject.
- Its share and mountOptions must equal the volume's stored source and options. Otherwise reject, naming the destination and the field, never the value.
- Its per-mount options may contain only ro and rw, matched on exact bytes. Otherwise reject. This closes:
- secrets in the per-mount options (pass, password, pass2, password2)
- the connection redirects
ip=,addr=andsource= - overrides of the volume's
username,sec,versanddomain, since later options win. - an
,,escape with an empty element.
- A mount with no name is a direct smb mount. It never gets a credential, and any password in its options is rejected, as today.
Verify when building the mount at bootstrap:
- Before resolveMountCredentials, rebuild each named smb mount from the volume's current configuration, keeping only the container's ro or rw and its destination.
- The password is then released only for a mount built from the volume it belongs to. This is defense in depth against a damaged or edited stored config.
- Fail bootstrap if the volume is gone. Containers in use block volume deletion, so that shouldn't happen.
There was a problem hiding this comment.
looking up the credential by mount.volumeName alone would let a direct client API call pair an existing volume name with another server's share or override options.
I wired VolumesService into ContainersService and implemented both checks:
-
At
ContainersService.create(validateMounts):
- A named.smbmount must refer to an existing volume inVolumesServicewithdriver == "smb".
- Itsshare(andmount.source) andmountOptionsmust equal the volume's storedsourceandoptions; mismatches are rejected naming onlymount.destinationand"share"or"mountOptions", never the value.
- Its per-mountoptions(Filesystem.options) are checked withvalidatePerMountOptions, accepting only"ro"and"rw"on exact UTF-8 bytes.
- An unnamed.smbmount is validated against the allowlist with no secrets allowed and never receives a credential. -
At
ContainersService.bootstrap(prepareBootstrapMounts):
- BeforeresolveMountCredentials, each named.smbmount is verified againstVolumesService(failing bootstrap if the volume is gone or notsmb) and rebuilt from the volume's currentsourceandoptions, keeping onlymount.destinationand the container's validatedro/rwoptions (and updating the stored config atpathsoRuntimeServiceuses the rebuilt mount).
- Credentials are only resolved for mounts rebuilt from their volume.
56e6fdd to
d290a47
Compare
|
@jglogan I also updated if so, bootstrap now fails with |
|
@tonycoco Here are the remaining minor items.
|
Add experimental support for 'nfs' and 'smb' volume drivers in 'container volume create', allowing network shares to be mounted directly inside the guest Linux VM via kernel NFS and CIFS mounts without creating a host-side ext4 disk image. - Extend Filesystem.FSType with .nfs and .smb cases (including optional volume name for in-use volume tracking across delete, prune, and disk usage) and deterministic mount option resolution - Map .nfs to Mount.any(type: "nfs") and .smb to Mount.any(type: "cifs") in RuntimeService - Handle 'nfs' and 'smb' drivers in VolumesService._create, validating non-empty share options and rejecting unsupported size options - Add ContainerResource.MountOptionValidator with per-driver allowlists for SMB and NFS mount options and strict ro/rw validation for per-mount options across the CLI, VolumesService, ContainersService, and RuntimeService - Store SMB volume passwords in the macOS keychain under com.apple.container.volume keyed by volume name, keeping secrets out of persisted volume/container configurations and clearing any stale keychain entry when creating an unauthenticated SMB volume - Verify named SMB mounts against their stored volume at container creation, rebuild them from the volume configuration at bootstrap before resolving credentials, and fail bootstrap if a volume with a username has no keychain credential - Reject secret keys (password, pass, password2, pass2, credentials, cred) on direct client API mounts and NFS volumes - Add --password-stdin to 'container volume create' for SMB volumes so the password need not appear on the command line - Turn off keychain user interaction in the keychain credential store so a locked keychain or an access list mismatch fails with an error instead of showing a dialog while a service lock is held - Add unit tests and update volume and command reference documentation Closes apple#1911 Closes apple#1413
d290a47 to
70815ac
Compare
|
@jglogan Both are in the latest push.
|
Add NFS and SMB volume drivers via direct guest mounts
Adds
--driver smband--driver nfstocontainer volume create. Both drivers are experimental: they mount network shares directly inside the Linux guest through the kernel's CIFS and NFS clients, so there is no host-side mount hop and no block image.How it works
VolumesServicestores the share and driver options as volume metadata. Atcontainer run, the client resolves the volume into aFilesystem.smborFilesystem.nfsmount, whichRuntimeServicetranslates into a.anyguest mount of typecifsornfs.A new
ContainerResource.MountOptionValidatorchecks that option keys match^[A-Za-z][A-Za-z0-9_-]{0,63}$and values contain no commas, whitespace, or control characters, so a value can't inject extra mount options. It runs in the CLI,VolumesService,ContainersService.create(for filesystems attached directly through the client API), andRuntimeServicebefore the guest mount is built. Thesharevalue is validated separately as a mount source — it is passed tomount(2)as its own argument and never joined into the options string — so share names containing spaces work.SMB passwords
The SMB password is stored in the macOS keychain under
com.apple.container.volume, keyed by volume name. It is never written toVolumeConfiguration, the container bundle, or shown byvolume inspect/volume list.ContainersServicereads it from the keychain at bootstrap and passes it to the runtime in the bootstrap message; the runtime adds it only to the in-memory guest mount. The keychain item is removed when the volume is deleted. A password requiresusername; without either, the share is mounted as a guest.The recommended way to supply the password is
--password-stdin, which keeps it off the command line.--opt password=remains for scripts; the docs note that it is visible throughpsand shell history.The keychain store never shows a dialog. It is called while the API server holds the locks that serialize container and volume operations, so it turns off keychain user interaction (
SecKeychainSetUserInteractionAllowed(false), process-wide, on first use). A locked keychain, or an access list that does not trust the running API server, then fails the operation with an error instead of blocking on a prompt.Secret keys (
password,pass,credentials,cred) are rejected for filesystems attached directly through the client API and for NFS volumes, and the runtime refuses to start a container whose stored configuration carries one.Design discussion: #1428 (comment)
Usage
SMB:
NFS:
Boolean mount flags such as
nolockormfsymlinksare passed as--opt nolock=with an empty value and serialized as bare flags.Kernel requirement
The guest kernel needs
CONFIG_CIFS(SMB) andCONFIG_NFS_FS(NFS). The default kernel, Kata 3.32.0, includes both (CIFS via kata-containers/kata-containers#12374), and the containerization example config has CIFS enabled as of apple/containerization#681. If you use a custom kernel, verify these options are set; without them the mount fails withENODEV.Known limitations / follow-ups
,,), which can be added later.Mountfailure message includes the mount data string, so a wrong SMB password is echoed in the mount error. Follow-up in apple/containerization to redactpassword=.container volume update; to change a password, delete and recreate the volume.Type of Change
Motivation and Context
Closes #1911
Closes #1413
Testing