728x90

2.2. Local 포트 포워딩

 

SSH 포트 포워딩은 연결을 수립하는 주체가 누구냐에 따라 Local과 Remote로 구분할 수 있다. Local은 가장 이해하기 쉽고 직관적인 경우로, 늘 하던 것처럼 SSH Client -> SSH Server로 연결을 수립하는 경우이다. 이해를 위해 간단한 예시를 통해 Local 포트 포워딩을 사용해보자.

 

 

 

SSH Client는 SSH Server에 SSH로 접속할 수 있다. 그러나 Nginx 서버는 127.0.0.1:80으로 바인딩되어 있어 외부에서 접근할 수 없는 상황이다. SSH Client 에서 Nginx에 접근할 수 있도록 SSH 터널링 연결을 생성한다.

 

 

가장 많이 헷갈리는 것이 SSH 포트 포워딩 시 '무엇을 어떻게 입력할지' 인데, 위 그림으로 이해할 수 있다. SSH Client에서 ssh -L [로컬에서 사용할 포트]:[최종적으로 접근할 곳] [SSH Server 주소] 형식으로 입력한다. SSH 터널이 생성된 뒤에는 [로컬에서 사용할 포트] 를 이용해 [최종적으로 접근할 곳] 에 접근할 수 있다.

 

직접 해보자. 가장 먼저, SSH Server 에서는 Nginx 서버시 127.0.0.1:80 으로 바인딩되어 실행되고 있다.

 

1
2
[root@ssh-server ~] docker ps --format '{{.Names}}\t{{.Image}}\t{{.Ports}}'
vigilant_khorana        nginx   127.0.0.1:80->80/tcp
cs

 

SSH Client에서 아래의 명령어를 입력해 SSH 포트 포워딩을 실행한다. SSH Server의 주소는 192.168.1.201 이고, 해당 SSH Server에서 접근할 Endpoint는 127.0.0.1:80 (Nginx Server) 이며, SSH Client의 8585 포트로 해당 Endpoint에 접근할 것이다.

 

1
2
3
4
5
[root@ssh-client ~] ssh -8585:127.0.0.1:80 192.168.1.201
root@192.168.1.201's password:
 
 
Last login: Sun Sep 23 05:01:06 2018
[root@ssh-server ~]
cs

 

평상시와 똑같이 SSH 접속에 성공하였지만, SSH 터널이 생성된 상태이다. SSH Client에서 새로운 터미널을 생성한 뒤, 로컬호스트의 8585로 요청을 전송해보자.

 

1
2
3
4
5
6
7
8
9
10
11
[root@ssh-client ~] curl localhost:8585 -v
...
< HTTP/1.1 200 OK
< Server: nginx/1.15.3
< Date: Sun, 23 Sep 2018 09:06:43 GMT
< Content-Type: text/html
< Content-Length: 612
< Last-Modified: Tue, 28 Aug 2018 13:32:13 GMT
< Connection: keep-alive
< ETag: "5b854edd-264"
< Accept-Ranges: bytes
cs

 

요청이 제대로 전송되었고 응답 또한 수신하였다. SSH 터널링은 수립된 SSH 연결을 통해 구성되기 때문에 위에서 접속한 SSH 연결을 끊으면 SSH 터널 또한 종료된다.



 

https://blog.naver.com/PostView.naver?blogId=alice_k106&logNo=221364560794

728x90
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class BasicSecurity extends WebSecurityConfigurerAdapter {

    private final LoggingFilter loggingFilter;

    public BasicSecurity(LoggingFilter loggingFilter) {
        this.loggingFilter = loggingFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/token").authenticated()
            .antMatchers("/pin/unlock").permitAll()  // Explicitly allow /pin/unlock
            .anyRequest().permitAll()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();  // Disable CSRF for testing purposes

        // Add the logging filter before UsernamePasswordAuthenticationFilter
        http.addFilterBefore(loggingFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("....")
                .password("....")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(user);
    }
}

 

서비스에서 POST를 정의하고 나서 일부 API에만 security 를 적용했을 경우, 다른 POST 도 영향을 받는다.

따라서 해당하는 POST들은 기본적으로 Spring Security 의 영향을 받기 때문에 별도로 permitAll을 해준다고 하더라도 모든 제약사항이 풀리진 않는다.

 

따라서 public 적으로 노출되는 POST Mapping 에 대해서는 csrf에 대해서 disable 해주는 전략이 필요하다. 

 

하지만 CSRF 를 disable 하지 않고 보안까지 지키려면 어떻게 해야할까?

 

const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

fetch('http://localhost:8080/pin/unlock?uuid=o87a66240433494aa362ad88e69af9c5', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        [csrfHeader]: csrfToken
    },
    body: JSON.stringify({ /* your data */ })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

 

이렇게 던질때 csrf token 까지 냅다 던져주면 된다.

728x90

Dynamic SQL is one of the main features of MyBatis, and after the parameters defined in mapper are passed into the XML, MyBatis is dynamically parsed before the query. MyBatis provides us with two syntax to support dynamic SQL: #{} and ${}.

In the following statement, if the value of username is Zhangsan, there is no difference between the two ways:

SELECT * from user where name = #{name};
SELECT * from user where name = ${name};

After parsing, the results are

SELECT * from user where name = ' Zhangsan ';

However, #{} and ${} are not handled in the precompilation. #{} When preprocessing, the parameter part is used as a placeholder? Instead, it becomes the following SQL statement:

 

SELECT * from user where name =?;

The ${} is simply a string replacement, which in the dynamic parsing phase is parsed into

SELECT * from user where name = ' Zhangsan ';

Above, the parameter substitution of #{} occurs in the DBMS, and ${} occurs in the dynamic parsing process.

So, which way should we use in the process?

The answer is, prioritize the use of #{}. Because ${} can cause problems with SQL injection. Look at the following example:

  

SELECT * from ${tablename} where name = #{name}

In this example, if the table is named

User Delete user; --

After dynamic parsing, SQL is as follows:

select * from user; Delete user; --WHERE name =?;

-After the statement is commented out, and the original query user's statement into the query all user information + DELETE user table statements, will cause significant damage to the database, which may cause server downtime.

But the table name is passed in with the parameter, can only use ${}, the concrete reason may make a guess by oneself, to verify. This also reminds us of the problem of SQL injection being careful in this usage.

 

 

https://logical-code.tistory.com/25

 

Mybatis 에서 #{} 과 ${}의 차이

Mybatis 에서 #{} 과 ${}의 차이/* * [개정 이력] * 2017.12.01 내용 보충 */ 회사에 취직하고나서, 쿼리문을 작성하는데 이상한 점을 발견했다.바로 Mybatis 를 이용해 XML에 쿼리문을 작성하는데, 파라메터

logical-code.tistory.com

 

 

728x90

https://denodo1.tistory.com/322

 

Unrecognized token 'id': was expecting ('true', 'false' or 'null')

Request Body로 보내지는 JSON의 행방 불명문제api 테스트 시 Postman을 자주 사용하는데, 다음과 같이 JSON을 서버에 보내면,서버의 Request에서 JSON 정보를 찾을 수 없다.해결하지만 동일한 json 데이터를 p

denodo1.tistory.com

 

+ Recent posts