Skip to content

Commit 4eb30fc

Browse files
committed
code optimization: use securejoin.SecureJoin and CleanPath
Signed-off-by: Lifubang <[email protected]>
1 parent 4fae8fc commit 4eb30fc

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

libcontainer/factory_linux.go

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"runtime/debug"
1212
"strconv"
1313

14+
"github.com/cyphar/filepath-securejoin"
1415
"github.com/opencontainers/runc/libcontainer/cgroups"
1516
"github.com/opencontainers/runc/libcontainer/cgroups/fs"
1617
"github.com/opencontainers/runc/libcontainer/cgroups/systemd"
@@ -195,7 +196,10 @@ func (l *LinuxFactory) Create(id string, config *configs.Config) (Container, err
195196
if err := l.Validator.Validate(config); err != nil {
196197
return nil, newGenericError(err, ConfigInvalid)
197198
}
198-
containerRoot := filepath.Join(l.Root, id)
199+
containerRoot, err := securejoin.SecureJoin(l.Root, id)
200+
if err != nil {
201+
return nil, err
202+
}
199203
if _, err := os.Stat(containerRoot); err == nil {
200204
return nil, newGenericError(fmt.Errorf("container with id exists: %v", id), IdInUse)
201205
} else if !os.IsNotExist(err) {
@@ -233,7 +237,10 @@ func (l *LinuxFactory) Load(id string) (Container, error) {
233237
if err := l.validateID(id); err != nil {
234238
return nil, err
235239
}
236-
containerRoot := filepath.Join(l.Root, id)
240+
containerRoot, err := securejoin.SecureJoin(l.Root, id)
241+
if err != nil {
242+
return nil, err
243+
}
237244
state, err := l.loadState(containerRoot, id)
238245
if err != nil {
239246
return nil, err
@@ -343,7 +350,11 @@ func (l *LinuxFactory) StartInitialization() (err error) {
343350
}
344351

345352
func (l *LinuxFactory) loadState(root, id string) (*State, error) {
346-
f, err := os.Open(filepath.Join(root, stateFilename))
353+
stateFilePath, err := securejoin.SecureJoin(root, stateFilename)
354+
if err != nil {
355+
return nil, err
356+
}
357+
f, err := os.Open(stateFilePath)
347358
if err != nil {
348359
if os.IsNotExist(err) {
349360
return nil, newGenericError(fmt.Errorf("container %q does not exist", id), ContainerNotExists)
@@ -359,7 +370,7 @@ func (l *LinuxFactory) loadState(root, id string) (*State, error) {
359370
}
360371

361372
func (l *LinuxFactory) validateID(id string) error {
362-
if id == "." || !idRegex.MatchString(id) || utils.CleanPath(id) != id {
373+
if !idRegex.MatchString(id) || string(os.PathSeparator)+id != utils.CleanPath(string(os.PathSeparator)+id) {
363374
return newGenericError(fmt.Errorf("invalid id format: %v", id), InvalidIdFormat)
364375
}
365376

0 commit comments

Comments
 (0)