Skip to content

Commit

Permalink
Amend the check on IllegalAttachmentFileNameException
Browse files Browse the repository at this point in the history
  • Loading branch information
bhou committed May 3, 2024
1 parent 0dbdd3d commit 90c5e8e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.core.io.Resource;

import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
Expand Down Expand Up @@ -94,9 +95,10 @@ public Set<URI> saveAttachments(
final long attachmentSize = attachment.contentLength();
final String filename = attachment.getFilename();

if (filename != null && (filename.contains("/") || filename.contains("\\"))) {
throw new IllegalAttachmentFileNameException("Attachment filename " + filename + " is illegal. "
+ "Filenames should not contain / or \\.");
if (filename != null && ((filename.contains("/") || filename.contains("\\")
|| filename.equals(".") || filename.equals("..")))) {
throw new IllegalAttachmentFileNameException("Attachment filename " + filename + " is illegal. "
+ "Filenames should not be . or .., or contain /, \\.");
}

if (attachmentSize > this.attachmentServiceProperties.getMaxSize().toBytes()) {
Expand All @@ -113,6 +115,15 @@ public Set<URI> saveAttachments(
filename != null ? filename : UUID.randomUUID().toString()
);

if (filename != null) {
final File file = new File(String.valueOf(attachmentsBasePath), filename);
if (!file.getCanonicalPath().startsWith(String.valueOf(attachmentsBasePath))
|| file.getCanonicalPath().equals(String.valueOf(attachmentsBasePath))) {
throw new IllegalAttachmentFileNameException("Attachment filename " + filename + " is illegal. "
+ "Filenames should not be a relative path.");
}
}

Files.copy(inputStream, attachmentPath);

setBuilder.add(attachmentPath.toUri());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,30 @@ class LocalFileSystemAttachmentServiceImplSpec extends Specification {
then:
thrown(IllegalAttachmentFileNameException)
}
def "reject attachments with illegal filename is ."() {
Set<Resource> attachments = new HashSet<Resource>()
Resource attachment = Mockito.mock(Resource.class)
Mockito.doReturn(".").when(attachment).getFilename()
attachments.add(attachment)
when:
service.saveAttachments(null, attachments)
then:
thrown(IllegalAttachmentFileNameException)
}
def "reject attachments with illegal filename is .."() {
Set<Resource> attachments = new HashSet<Resource>()
Resource attachment = Mockito.mock(Resource.class)
Mockito.doReturn("..").when(attachment).getFilename()
attachments.add(attachment)
when:
service.saveAttachments(null, attachments)
then:
thrown(IllegalAttachmentFileNameException)
}
}

0 comments on commit 90c5e8e

Please sign in to comment.