Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] XSS 공격 대비 방어 코드 작성 #310

Merged
merged 5 commits into from
May 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package synk.meeteam.domain.recruitment.recruitment_post.dto.response;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import lombok.Builder;
Expand All @@ -10,6 +11,7 @@
import synk.meeteam.domain.recruitment.recruitment_role.entity.RecruitmentRole;
import synk.meeteam.domain.user.user.entity.User;
import synk.meeteam.global.util.Encryption;
import synk.meeteam.global.util.UnescapedFieldSerializer;

@Builder
@Schema(name = "GetRecruitmentPostResponseDto", description = "구인글 조회 Dto")
Expand Down Expand Up @@ -59,6 +61,7 @@ public record GetRecruitmentPostResponseDto(
@Schema(description = "구인 역할", example = "")
List<GetRecruitmentRoleResponseDto> recruitmentRoles,
@Schema(description = "상세 내용", example = "안녕하세요. 저는 팀원을...")
@JsonSerialize(using = UnescapedFieldSerializer.class)
String content,
@Schema(description = "댓글, 대댓글", example = "")
List<GetCommentResponseDto> comments
Expand Down
24 changes: 24 additions & 0 deletions src/main/java/synk/meeteam/global/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package synk.meeteam.global.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import synk.meeteam.global.util.HtmlCharacterEscapes;

@Slf4j
@RequiredArgsConstructor
@Configuration
public class WebMvcConfig {

private final ObjectMapper objectMapper;

@Bean
public MappingJackson2HttpMessageConverter jsonEscapeConverter() {
ObjectMapper copy = objectMapper.copy();
copy.getFactory().setCharacterEscapes(new HtmlCharacterEscapes());
return new MappingJackson2HttpMessageConverter(copy);
}
}
mikekks marked this conversation as resolved.
Show resolved Hide resolved
33 changes: 33 additions & 0 deletions src/main/java/synk/meeteam/global/util/HtmlCharacterEscapes.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package synk.meeteam.global.util;

import com.fasterxml.jackson.core.SerializableString;
import com.fasterxml.jackson.core.io.CharacterEscapes;
import com.fasterxml.jackson.core.io.SerializedString;
import org.apache.commons.lang3.StringEscapeUtils;

public class HtmlCharacterEscapes extends CharacterEscapes {

private final int[] asciiEscapes;

public HtmlCharacterEscapes() {
// 1. XSS 방지 처리할 특수 문자 지정
asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON();
asciiEscapes['<'] = CharacterEscapes.ESCAPE_CUSTOM;
asciiEscapes['>'] = CharacterEscapes.ESCAPE_CUSTOM;
asciiEscapes['\"'] = CharacterEscapes.ESCAPE_CUSTOM;
asciiEscapes['('] = CharacterEscapes.ESCAPE_CUSTOM;
asciiEscapes[')'] = CharacterEscapes.ESCAPE_CUSTOM;
asciiEscapes['#'] = CharacterEscapes.ESCAPE_CUSTOM;
asciiEscapes['\''] = CharacterEscapes.ESCAPE_CUSTOM;
}

@Override
public int[] getEscapeCodesForAscii() {
return asciiEscapes;
}

@Override
public SerializableString getEscapeSequence(int ch) {
return new SerializedString(StringEscapeUtils.escapeHtml4(Character.toString((char) ch)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package synk.meeteam.global.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UnescapedFieldSerializer extends JsonSerializer<String> {

@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// HTML escaping을 하지 않고 그대로 출력
gen.writeRawValue("\"" + value + "\"");
}
}

122 changes: 122 additions & 0 deletions src/test/java/synk/meeteam/global/xss/XssSpringBootTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package synk.meeteam.global.xss;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import synk.meeteam.domain.recruitment.recruitment_post.dto.request.CourseTagDto;
import synk.meeteam.domain.recruitment.recruitment_post.dto.request.CreateRecruitmentPostRequestDto;
import synk.meeteam.domain.recruitment.recruitment_post.dto.request.RecruitmentRoleDto;
import synk.meeteam.domain.recruitment.recruitment_post.dto.response.CreateRecruitmentPostResponseDto;
import synk.meeteam.domain.recruitment.recruitment_post.dto.response.GetRecruitmentPostResponseDto;


@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("test")
public class XssSpringBootTest {
private static final String RECRUITMENT_URL = "/recruitment/postings";

@Autowired
private TestRestTemplate restTemplate;

@Value("${jwt.access.header}")
private String accessHeader;

private String TOKEN = "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBY2Nlc3NUb2tlbiIsInBsYXRmb3JtSWQiOiI0SUlfbGZaY1Q2NW82MVRfZkh5d2hybzVJanlSTmpSZE1IVi1qNXJWMmtvIiwicGxhdGZvcm1UeXBlIjoiTkFWRVIiLCJpYXQiOjE3MDg1OTkyMTMsImV4cCI6MTgxNjU5OTIxM30.5kAEY2nJ3mNqlnhhFNV0_FVvXTD7JRTzTj6FjpresEA";

HttpHeaders headers;



@BeforeEach
void init() {
restTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory());

headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set(accessHeader, TOKEN);
}

@Test
public void escape문자로치환_구인글생성_성공_xss공격() {
HttpEntity request = new HttpEntity(headers);

String title = "<li>content</li>";
String expected = "&lt;li&gt;content&lt;/li&gt;";
CreateRecruitmentPostRequestDto requestDto = createRequestDto_title(title);
HttpEntity<CreateRecruitmentPostRequestDto> requestEntity = new HttpEntity<>(requestDto, headers);

ResponseEntity<CreateRecruitmentPostResponseDto> responseEntity = restTemplate.postForEntity(
RECRUITMENT_URL,
requestEntity, CreateRecruitmentPostResponseDto.class);

assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
CreateRecruitmentPostResponseDto body = responseEntity.getBody();
assertNotNull(body.recruitmentPostId());;

ResponseEntity<GetRecruitmentPostResponseDto> verifyResponseEntity = restTemplate.exchange(
RECRUITMENT_URL + "/{id}", HttpMethod.GET, request,
GetRecruitmentPostResponseDto.class, body.recruitmentPostId());

GetRecruitmentPostResponseDto verifyBody = verifyResponseEntity.getBody();
assertEquals(verifyBody.title(), expected);
}

@Test
public void escape문자로치환및LocalDate치환_구인글생성_성공_xss공격() {
HttpEntity request = new HttpEntity(headers);

String title = "<li>content</li>";
String expected = "&lt;li&gt;content&lt;/li&gt;";
CreateRecruitmentPostRequestDto requestDto = createRequestDto_title(title);
HttpEntity<CreateRecruitmentPostRequestDto> requestEntity = new HttpEntity<>(requestDto, headers);

ResponseEntity<CreateRecruitmentPostResponseDto> responseEntity = restTemplate.postForEntity(
RECRUITMENT_URL,
requestEntity, CreateRecruitmentPostResponseDto.class);

assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
CreateRecruitmentPostResponseDto body = responseEntity.getBody();
assertNotNull(body.recruitmentPostId());;

ResponseEntity<GetRecruitmentPostResponseDto> verifyResponseEntity = restTemplate.exchange(
RECRUITMENT_URL + "/{id}", HttpMethod.GET, request,
GetRecruitmentPostResponseDto.class, body.recruitmentPostId());

GetRecruitmentPostResponseDto verifyBody = verifyResponseEntity.getBody();
assertEquals(verifyBody.title(), expected);
assertEquals(verifyBody.deadline(), LocalDate.of(2024, 2, 22).toString());
}

private CreateRecruitmentPostRequestDto createRequestDto_title(String title) {
CourseTagDto courseTagDto = new CourseTagDto(true, "응소실", "김용혁");
List<RecruitmentRoleDto> recruitmentRoleDtos = new ArrayList<>();
recruitmentRoleDtos.add(new RecruitmentRoleDto(1L, 1, List.of(1L, 2L, 3L)));
recruitmentRoleDtos.add(new RecruitmentRoleDto(2L, 3, List.of(1L, 2L, 3L)));
recruitmentRoleDtos.add(new RecruitmentRoleDto(3L, 1, List.of(4L, 5L, 6L)));

return new CreateRecruitmentPostRequestDto("교내", "프로젝트", LocalDate.of(2024, 2, 22), LocalDate.of(2024, 3, 15),
LocalDate.of(2024, 5, 15), 1L, "온라인",
courseTagDto, List.of("웹개발", "AI", "대학생", "구인"), recruitmentRoleDtos, title, "사람구합니당!!");
}
}
Loading