@@ -20,6 +20,7 @@ import (
2020 "fmt"
2121 "os"
2222 "os/exec"
23+ "path/filepath"
2324 "syscall"
2425
2526 "github.com/moby/sys/userns"
@@ -37,6 +38,7 @@ const (
3738)
3839
3940var ErrEmptyContainerID = errors .New ("container ID can not be empty" )
41+ var ErrInvalidID = errors .New ("invalid container id format" )
4042
4143// checkArgs checks the number of arguments provided in the command-line context
4244// against the expected number, based on the specified checkType.
@@ -69,8 +71,8 @@ func checkArgs(cmd *cli.Command, expected, checkType int) error {
6971
7072func getUnikontainer (cmd * cli.Command ) (* unikontainers.Unikontainer , error ) {
7173 containerID := cmd .Args ().First ()
72- if containerID == "" {
73- return nil , ErrEmptyContainerID
74+ if err := validateID ( containerID ); err != nil {
75+ return nil , err
7476 }
7577
7678 // We have already made sure in main.go that root is not nil
@@ -160,3 +162,53 @@ func prepareXDGRuntimeDir(root string) error {
160162 }
161163 return nil
162164}
165+
166+ // validateID validates the given ID string against the allowed characters.
167+ // source ref: https://github.com/opencontainers/runc/blob/main/libcontainer/factory_linux.go#L192
168+ // commit: https://github.com/opencontainers/runc/commit/b44da4c05f4972e19bb16a91aec2e3a0e089b516
169+
170+ // validateID checks if the supplied container ID is valid, returning
171+ // the ErrInvalidID in case it is not.
172+ //
173+ // The format of valid ID was never formally defined, instead the code
174+ // was modified to allow or disallow specific characters.
175+ //
176+ // Currently, a valid ID is a non-empty string consisting only of
177+ // the following characters:
178+ // - uppercase (A-Z) and lowercase (a-z) Latin letters;
179+ // - digits (0-9);
180+ // - underscore (_);
181+ // - plus sign (+);
182+ // - minus sign (-);
183+ // - period (.).
184+ //
185+ // In addition, IDs that can't be used to represent a file name
186+ // (such as . or ..) are rejected.
187+ func validateID (id string ) error {
188+ if len (id ) < 1 {
189+ return ErrEmptyContainerID
190+ }
191+
192+ // Allowed characters: 0-9 A-Z a-z _ + - .
193+ for i := range len (id ) {
194+ c := id [i ]
195+ switch {
196+ case c >= 'a' && c <= 'z' :
197+ case c >= 'A' && c <= 'Z' :
198+ case c >= '0' && c <= '9' :
199+ case c == '_' :
200+ case c == '+' :
201+ case c == '-' :
202+ case c == '.' :
203+ default :
204+ return ErrInvalidID
205+ }
206+
207+ }
208+
209+ if string (os .PathSeparator )+ id != filepath .Clean (string (os .PathSeparator )+ id ) {
210+ return ErrInvalidID
211+ }
212+
213+ return nil
214+ }
0 commit comments