diff --git a/files/link.go b/files/link.go index e420b978..42578906 100644 --- a/files/link.go +++ b/files/link.go @@ -16,6 +16,30 @@ import ( var link_path, _ = filepath.Abs("./config/links") +// Build the on-disk path for a link file. Link file names are always either a +// user ID or a UUID, so anything able to express a directory traversal is +// rejected before it reaches the filesystem. +func buildLinkPath(fileName string) (string, error) { + if fileName == "" || + strings.Contains(fileName, "/") || + strings.Contains(fileName, "\\") || + strings.Contains(fileName, "..") { + log.Println("Rejected share link file name containing path separators.") + return "", errors.New("Invalid share link.") + } + + share_link_path := filepath.Join(link_path, fileName+".json") + + // Guard against the joined path landing outside the link directory. The + // trailing separator matters: without it "./config/linksevil" would pass. + if !strings.HasPrefix(share_link_path, link_path+string(os.PathSeparator)) { + log.Println("Rejected share link file name resolving outside the link directory.") + return "", errors.New("Invalid share link.") + } + + return share_link_path, nil +} + // Save new link object to the correct path func SaveLink(link_object *models.WrapperrShareLink, plexAuth bool) error { @@ -30,11 +54,16 @@ func SaveLink(link_object *models.WrapperrShareLink, plexAuth bool) error { return err } - var link_object_path string + var fileName string if plexAuth { - link_object_path, _ = filepath.Abs(link_path + "/" + strconv.Itoa(link_object.UserID) + ".json") + fileName = strconv.Itoa(link_object.UserID) } else { - link_object_path, _ = filepath.Abs(link_path + "/" + link_object.Hash + ".json") + fileName = link_object.Hash + } + + link_object_path, err := buildLinkPath(fileName) + if err != nil { + return err } err = ioutil.WriteFile(link_object_path, file, 0644) @@ -73,7 +102,7 @@ func CheckLinkDir() error { } func DeleteLink(fileName string) error { - linkpath, err := filepath.Abs(link_path + "/" + fileName + ".json") + linkpath, err := buildLinkPath(fileName) if err != nil { log.Println("Failed to create path. Error: " + err.Error()) return errors.New("Failed to create path.") @@ -96,7 +125,7 @@ func GetLink(fileName string) (*models.WrapperrShareLink, error) { link_object := models.WrapperrShareLink{} - share_link_path, err := filepath.Abs(link_path + "/" + fileName + ".json") + share_link_path, err := buildLinkPath(fileName) if err != nil { return nil, err } @@ -143,11 +172,13 @@ func CleanOldShareableLinks() { linkObject, err := GetLink(fileNameParts[0]) if err != nil { log.Println("Failed to load " + item.Name() + ". Error: " + err.Error()) + continue } now := time.Now() linkTime, err := time.Parse("2006-01-02", linkObject.Date) if err != nil { log.Println("Failed to parse " + item.Name() + " datetime. Error: " + err.Error()) + continue } linkTime = linkTime.Add(7 * 24 * time.Hour) if linkTime.Before(now) { diff --git a/files/link_test.go b/files/link_test.go new file mode 100644 index 00000000..fe84333c --- /dev/null +++ b/files/link_test.go @@ -0,0 +1,71 @@ +package files + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestBuildLinkPathValid(t *testing.T) { + // The only file names ever written are a user ID or a UUID. + names := []string{ + "0", + "12345", + "1b4e28ba-2fa1-11d2-883f-0016d3cca427", + } + + for _, name := range names { + result, err := buildLinkPath(name) + if err != nil { + t.Errorf("buildLinkPath(%q) returned error: %v", name, err) + continue + } + + expected := filepath.Join(link_path, name+".json") + if result != expected { + t.Errorf("buildLinkPath(%q) = %q, expected %q", name, result, expected) + } + } +} + +func TestBuildLinkPathRejectsTraversal(t *testing.T) { + // Each of these escaped ./config/links when the path was built by string + // concatenation, because filepath.Abs resolves "../" instead of rejecting it. + names := []string{ + "", + "..", + "../admin", + "../../etc/passwd", + "..\\admin", + "/etc/passwd", + "12345/../../admin", + "foo/bar", + ".../...//admin", + } + + for _, name := range names { + result, err := buildLinkPath(name) + if err == nil { + t.Errorf("buildLinkPath(%q) = %q, expected an error", name, result) + } + } +} + +func TestBuildLinkPathStaysInLinkDir(t *testing.T) { + // A prefix check without a trailing separator would accept a sibling + // directory such as "./config/linksevil". + names := []string{"12345", "1b4e28ba-2fa1-11d2-883f-0016d3cca427"} + + for _, name := range names { + result, err := buildLinkPath(name) + if err != nil { + t.Errorf("buildLinkPath(%q) returned error: %v", name, err) + continue + } + + if !strings.HasPrefix(result, link_path+string(os.PathSeparator)) { + t.Errorf("buildLinkPath(%q) = %q, which is outside %q", name, result, link_path) + } + } +} diff --git a/routes/open.go b/routes/open.go index fdee9c3d..4772e871 100644 --- a/routes/open.go +++ b/routes/open.go @@ -30,6 +30,12 @@ var validThumbPath = regexp.MustCompile(`^/library/metadata/\d+/thumb(/\d+)?$`) var validServerHash = regexp.MustCompile(`^[a-f0-9]{16}$`) var validPosterFilename = regexp.MustCompile(`^[0-9]+\.jpg$`) +// validLinkUserID and validLinkUUID constrain the share link file name taken +// from the (unauthenticated) share link request. Links are saved as either a +// user ID or a UUID, so nothing else should ever reach the filesystem. +var validLinkUserID = regexp.MustCompile(`^[0-9]+$`) +var validLinkUUID = regexp.MustCompile(`^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$`) + // API route which retrieves the Wrapperr version and some minor details (application name, Plex-Auth...). func ApiGetWrapperrVersion(context *gin.Context) { configBool, err := files.GetConfigState() @@ -399,6 +405,18 @@ func ApiGetShareLink(context *gin.Context) { fileName = hash } + if config.PlexAuth && !validLinkUserID.MatchString(fileName) { + log.Println("Share link request contained an invalid user ID.") + context.JSON(http.StatusBadRequest, gin.H{"error": "Invalid shared link."}) + context.Abort() + return + } else if !config.PlexAuth && !validLinkUUID.MatchString(fileName) { + log.Println("Share link request contained an invalid hash.") + context.JSON(http.StatusBadRequest, gin.H{"error": "Invalid shared link."}) + context.Abort() + return + } + share_link_object, err := files.GetLink(fileName) if err != nil { log.Println("Failed to get link file. Error: " + err.Error())