Development Tip

REST API / 웹 서비스 보안을위한 모범 사례

yourdevel 2020. 9. 28. 10:15
반응형

REST API / 웹 서비스 보안을위한 모범 사례 [닫힌]


REST API 또는 서비스를 설계 할 때 보안 처리 (인증, 권한 부여, ID 관리)를 처리하기위한 확립 된 모범 사례가 있습니까?

SOAP API를 빌드 할 때 WS-Security를 ​​가이드로 사용하고 주제에 대한 많은 문헌이 있습니다. REST 엔드 포인트 보안에 대한 정보가 적습니다.

REST가 WS- *와 유사한 사양을 의도적으로 가지고 있지 않다는 것을 이해하지만 모범 사례 또는 권장 패턴이 나타났기를 바랍니다.

관련 문서에 대한 모든 토론이나 링크는 대단히 감사하겠습니다. 중요한 경우 .NET Framework v3.5를 사용하여 빌드 된 REST API / 서비스에 대해 POX / JSON 직렬화 된 메시지와 함께 WCF를 사용합니다.


Tweakt가 말했듯이 Amazon S3는 작업하기에 좋은 모델입니다. 요청 서명에는 실수 및 악의적 인 요청 재생을 방지하는 데 도움이되는 몇 가지 기능 (예 : 타임 스탬프 통합)이 있습니다.

HTTP Basic의 좋은 점은 거의 모든 HTTP 라이브러리가이를 지원한다는 것입니다. 물론 인터넷을 통해 일반 텍스트 암호를 보내는 것은 거의 보편적으로 나쁜 일이기 때문에이 경우 SSL이 필요합니다. 호출자가 자격 증명이 필요하다는 것을 이미 알고 있더라도 Digest는 nonce 값을 교환하기 위해 추가 왕복이 필요하기 때문에 SSL을 사용할 때 기본이 Digest보다 선호됩니다. Basic을 사용하면 호출자가 처음에 자격 증명을 간단히 보냅니다.

클라이언트의 ID가 설정되면 인증은 실제로 구현 문제 일뿐입니다. 그러나 기존 권한 부여 모델을 사용하여 다른 구성 요소에 권한을 위임 할 수 있습니다. 여기서도 Basic에 대한 좋은 점은 서버가 클라이언트 암호의 일반 텍스트 사본으로 끝나고 필요에 따라 인프라 내의 다른 구성 요소에 간단히 전달할 수 있다는 것입니다.


HTTP 이외의 REST에 대한 표준은 없습니다. 거기에 확립 된 REST 서비스가 있습니다. 나는 당신이 그들을 들여다보고 그들이 어떻게 작동하는지 느끼는 것이 좋습니다.

예를 들어, 자체 개발시 Amazon의 S3 REST 서비스에서 많은 아이디어를 빌 렸습니다. 그러나 요청 서명을 기반으로 한 고급 보안 모델을 사용하지 않기로 결정했습니다. 더 간단한 접근 방식은 SSL을 통한 HTTP 기본 인증입니다. 자신의 상황에 가장 적합한 것을 결정해야합니다.

또한 O'reilly의 RESTful Web Services 책을 적극 권장합니다 . 핵심 개념을 설명하고 몇 가지 모범 사례를 제공합니다. 일반적으로 제공하는 모델을 가져 와서 자신의 애플리케이션에 매핑 할 수 있습니다.


http api를 대상으로하는 토큰 기반 인증을위한 새로운 개방형 프로토콜 인 OAuth를 살펴볼 수도 있습니다 .

이 접근 방식에 의해 촬영과 매우 유사하다 플리커우유 기억 "나머지"API를 (편안한 API를 반드시 좋은 예,하지만 토큰 기반 접근 방식의 좋은 예).


Github 에는 훌륭한 체크리스트가 있습니다 .

입증

  • 인증, 토큰 생성, 암호 저장에서 바퀴를 재발 명하지 마십시오. 표준을 사용하십시오.

  • Max Retry로그인에서 사용 및 감옥 기능.

  • 모든 민감한 데이터에 암호화를 사용하십시오.

JWT (JSON 웹 토큰)

  • 무작위로 복잡한 키 (JWT 비밀)를 사용하여 토큰을 매우 어렵게 강제합니다.

  • 페이로드에서 알고리즘을 추출하지 마십시오. 백엔드 (HS256 또는 RS256)에서 알고리즘을 강제 실행합니다.

  • 토큰 만료 ( TTL, RTTL)를 최대한 짧게 만드십시오 .

  • 민감한 데이터를 JWT페이로드 에 저장하지 마십시오 . 쉽게 디코딩 할 수 있습니다.

OAuth

  • redirect_uri허용 된 URL 만 허용하려면 항상 서버 측의 유효성을 검사하십시오 .

  • 항상 토큰이 아닌 코드로 교환하십시오 (허용하지 마십시오 response_type=token).

  • 방지하기 위해 임의의 해시 상태 매개 변수를 사용하여 CSRFOAuth인증 프로세스.

  • 기본 범위를 정의하고 각 애플리케이션에 대한 범위 매개 변수의 유효성을 검증하십시오.

접속하다

  • DDoS / 무차별 대입 공격을 피하기 위해 요청을 제한 (스로틀 링)합니다.

  • MITM (Man In The Middle Attack)을 피하기 위해 서버 측에서 HTTPS 사용

  • 사용 HSTSSSL과 헤더는 SSL 스트립 공격을 방지 할 수 있습니다.

입력

  • GET(읽기), POST(만들기), PUT/PATCH(교체 / 업데이트), DELETE(레코드 삭제 ) 작업에 따라 적절한 HTTP 메서드를 사용하고 405 Method Not Allowed요청 된 메서드가 요청 된 리소스에 적합하지 않은 경우 응답 합니다.

  • 요청에 대한 유효성 검사 콘텐츠 형식 Accept헤더 (콘텐츠 협상) 만 지원되는 형식 (예를 들면 수 있도록 application/xml, application/json과 등) 및 응답을 406 Not Acceptable일치하지 않는 경우 응답.

  • 검증 content-type수락으로의 (예를 들어 데이터를 게시 application/x-www-form-urlencoded, multipart/form-data, application/json, 등).

  • 일반적인 취약점 (예 : XSS, SQL-Injection, 원격 코드 실행 등)을 피하기 위해 사용자 입력을 검증합니다.

  • URL에 민감한 데이터 (자격 증명, 암호, 보안 토큰 또는 API 키)를 사용하지 말고 표준 Authorization헤더를 사용하십시오 .

  • API Gateway 서비스를 사용하여 캐싱, Rate Limit정책 (예 : 할당량, 스파이크 방지, 동시 속도 제한) 을 활성화 하고 API 리소스를 동적으로 배포합니다.

가공

  • 인증 프로세스가 손상되지 않도록 모든 엔드 포인트가 인증 뒤에 보호되는지 확인하십시오.

  • 사용자 자신의 리소스 ID는 피해야합니다. / user / 654321 / orders 대신 / me / orders를 사용하십시오.

  • ID를 자동으로 늘리지 마십시오. 대신 UUID를 사용하십시오.

  • XML 파일을 구문 분석하는 경우 XXE (XML 외부 엔티티 공격)를 방지하기 위해 엔티티 구문 분석이 활성화되어 있지 않은지 확인하십시오.

  • XML 파일을 구문 분석하는 경우 지수 엔터티 확장 공격을 통해 Billion Laughs / XML 폭탄을 피하기 위해 엔터티 확장이 활성화되지 않았는지 확인하십시오.

  • 파일 업로드에 CDN을 사용하십시오.

  • 방대한 양의 데이터를 처리하는 경우 작업자 및 큐를 사용하여 가능한 한 백그라운드에서 처리하고 HTTP 차단을 피하기 위해 응답을 빠르게 반환합니다.

  • Do not forget to turn the DEBUG mode OFF.

Output

  • Send X-Content-Type-Options: nosniff header.

  • Send X-Frame-Options: deny header.

  • Send Content-Security-Policy: default-src 'none' header.

  • Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version etc.

  • Force content-type for your response, if you return application/json then your response content-type is application/json.

  • Don't return sensitive data like credentials, Passwords, security tokens.

  • Return the proper status code according to the operation completed. (e.g. 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc).


I'm kind of surprised SSL with client certificates hasn't been mentioned yet. Granted, this approach is only really useful if you can count on the community of users being identified by certificates. But a number of governments/companies do issue them to their users. The user doesn't have to worry about creating yet another username/password combination, and the identity is established on each and every connection so communication with the server can be entirely stateless, no user sessions required. (Not to imply that any/all of the other solutions mentioned require sessions)


Everyone in these answers has overlooked true access control / authorization.

If for instance your REST APIs / web services are about POSTing / GETing medical records, you may want to define access control policie about who can access the data and under which circumstances. For instance:

  • doctors can GET the medical record of a patient they have a care relationship with
  • no one can POST medical data outside practice hours (e.g. 9 to 5)
  • end-users can GET medical records they own or medical records of patients for whom they are the guardian
  • nurses can UPDATE the medical record of a patient that belongs to the same unit as the nurse.

In order to define and implement those fine-grained authorizations, you will need to use an attribute-based access control language called XACML, the eXtensible Access Control Markup Language.

The other standards here are for the following:

  • OAuth: id. federation and delegation of authorization e.g. letting a service act on my behalf on another service (Facebook can post to my Twitter)
  • SAML: identity federation / web SSO. SAML is very much about who the user is.
  • WS-Security / WS-* standards: these focus on the communication between SOAP services. They are specific to the application-level messaging format (SOAP) and they deal with aspects of messaging e.g. reliability, security, confidentiality, integrity, atomicity, eventing... None cover access control and all are specific to SOAP.

XACML is technology-agnostic. It can be applied to java apps, .NET, Python, Ruby... web services, REST APIs, and more.

The following are interesting resources:


I've used OAuth a few times, and also used some other methods (BASIC/DIGEST). I wholeheartedly suggest OAuth. The following link is the best tutorial I've seen on using OAuth:

http://hueniverse.com/oauth/guide/


One of the best posts I've ever come across regarding Security as it relates to REST is over at 1 RainDrop. The MySpace API's use OAuth also for security and you have full access to their custom channels in the RestChess code, which I did a lot of exploration with. This was demo'd at Mix and you can find the posting here.


Thanks for the excellent advice. We ended up using a custom HTTP header to pass an identity token from the client to the service, in preparation for integrating our RESTful API with the the upcoming Zermatt Identity framework from Microsoft. I have described the problem here and our solution here. I also took tweakt's advice and bought RESTful Web Services - a very good book if you're building a RESTful API of any kind.


OWASP(Open Web Application Security Project) has some cheat sheets covering about all aspects of Web Application development. This Project is a very valuable and reliable source of information. Regarding REST services you can check this: https://www.owasp.org/index.php/REST_Security_Cheat_Sheet


I would recommend OAuth 2/3. You can find more information at http://oauth.net/2/


I searched a lot about restful ws security and we also ended up with using token via cookie from client to server to authenticate the requests . I used spring security for authorization of requests in service because I had to authenticate and authorized each request based on specified security policies that has already been in DB.


The fact that the SOAP world is pretty well covered with security standards doesn't mean that it's secure by default. In the first place, the standards are very complex. Complexity is not a very good friend of security and implementation vulnerabilities such as XML signature wrapping attacks are endemic here.

As for the .NET environment I won't help much, but “Building web services with Java” (a brick with ~10 authors) did help me a lot in understanding the WS-* security architecture and, especially, its quirks.


REST itself offers no security standards, but things like OAuth and SAML are rapidly becoming the standards in this space. However, authentication and authorization are only a small part of what you need to consider. Many of the known vulnerabilities relating to web applications apply very much to REST apis. You have to consider input validation, session cracking, inappropriate error messages, internal employee vulnerabilities and so on. It is a big subject.


I want to add(in line with stinkeymatt), simplest solution would be to add SSL certificates to your site. In other words, make sure your url is HTTPS://. That will cover your transport security (bang for the buck). With RESTful url's, idea is to keep it simple (unlike WS* security/SAML), you can use oAuth2/openID connect or even Basic Auth (in simple cases). But you will still need SSL/HTTPS. Please check ASP.NET Web API 2 security here: http://www.asp.net/web-api/overview/security (Articles and Videos)


As @Nathan ended up with which is a simple HTTP Header, and some had said OAuth2 and client side SSL certificates. The gist of it is this... your REST API shouldn't have to handle security as that should really be outside the scope of the API.

Instead a security layer should be put on top of it, whether it is an HTTP Header behind a web proxy (a common approach like SiteMinder, Zermatt or even Apache HTTPd), or as complicated as OAuth 2.

The key thing is the requests should work without any end-user interaction. All that is needed is to ensure that the connection to the REST API is authenticated. In Java EE we have the notion of a userPrincipal that can be obtained on an HttpServletRequest. It is also managed in the deployment descriptor that a URL pattern can be secure so the REST API code does not need to check anymore.

In the WCF world, I would use ServiceSecurityContext.Current to get the current security context. You need to configure you application to require authentication.

There is one exception to the statement I had above and that's the use of a nonce to prevent replays (which can be attacks or someone just submitting the same data twice). That part can only be handled in the application layer.


For Web Application Security, you should take a look at OWASP (https://www.owasp.org/index.php/Main_Page) which provides cheatsheets for various security attacks. You can incorporate as many measures as possible to secure your Application. With respect to API security (authorization, authentication, identity management), there are multiple ways as already mentioned (Basic,Digest and OAuth). There are loop holes in OAuth1.0, so you can use OAuth1.0a (OAuth2.0 is not widely adopted due to concerns with the specification)


It's been a while but the question is still relevant, though the answer might have changed a bit.

An API Gateway would be a flexible and highly configurable solution. I tested and used KONG quite a bit and really liked what I saw. KONG provides an admin REST API of its own which you can use to manage users.

Express-gateway.io is more recent and is also an API Gateway.

참고URL : https://stackoverflow.com/questions/7551/best-practices-for-securing-a-rest-api-web-service

반응형