-
Same Origin Policy & Cross Origin Resource Sharing개발/Web 2022. 6. 11. 22:14
*복습 자료라서 뻔한 내용은 생략
Summary.
1. The same-origin policy is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin (SOP)
+ same origin: scheme(protocol) + host + port (*not PATH)
ex) it prevents a malicious website on the Internet from running JS in a browser to read data from a third-party webmail service (which the user is signed into) or a company intranet (which is protected from direct access by the attacker by not having a public IP address) and relaying that data to the attacker
2. inherited origin
+ Scripts executed from pages with an about:blank or javascript: URL inherit the origin of the document containing that URL
ex) about:blank is often used as a URL of new, empty popup windows into which the parent script writes content (e.g. via the Window.open() mechanism). If this popup also contains JavaScript, that script would inherit the same origin as the script that created it
3. File Origin
+ Modern browsers usually treat the origin of files loaded using the file:/// schema as opaque origins. What this means is that if a file includes other files from the same folder (say), they are not assumed to come from the same origin, and may trigger CORS errors (브라우저마다 기준이 다름)
4. The same-origin policy controls interactions between two different origins, such as when you use XMLHttpRequest or an <img> element
- Cross-origin writes are typically allowed. Examples are links, redirects, and form submissions. Some HTTP requests require preflight.
- Cross-origin embedding is typically allowed. (Examples are listed below.)
- Cross-origin reads are typically disallowed, but read access is often leaked by embedding. For example, you can read the dimensions of an embedded image, the actions of an embedded script, or the availability of an embedded resource.
+ Cross-origin Embedding 예시는 아래와 같음
- JavaScript with <script src="…"></script>. Error details for syntax errors are only available for same-origin scripts.
- CSS applied with <link rel="stylesheet" href="…">. Due to the relaxed syntax rules of CSS, cross-origin CSS requires a correct Content-Type header. Restrictions vary by browser: Internet Explorer, Firefox, Chrome , Safari (scroll down to CVE-2010-0051) and Opera.
- Images displayed by <img>.
- Media played by <video> and <audio>.
- External resources embedded with <object> and <embed>.
- Fonts applied with @font-face. Some browsers allow cross-origin fonts, others require same-origin.
- Anything embedded by <iframe>. Sites can use the X-Frame-Options header to prevent cross-origin framing.
5. Cross-origin Access 막는 법
+ CSRF 토큰
+ Embedding 자체를 막기
6. JavaScript APIs like iframe.contentWindow, window.parent, window.open, and window.opener allow documents to directly reference each other. When two documents do not have the same origin, these references provide very limited access to Window and Location objects, as described in the next two sections.
+ To communicate between documents from different origins, use window.postMessage.
7. Access to data stored in the browser such as Web Storage and IndexedDB are separated by origin. Each origin gets its own separate storage, and JavaScript in one origin cannot read from or write to the storage belonging to another origin
+ Cookies use a separate definition of origins (Domain, Path, 등)
8. Use CORS to allow cross-origin access. CORS is a part of HTTP that lets servers specify any other hosts from which a browser should permit loading of content
+ Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources
+ CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request
ex) the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json
+ For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy
9. CORS 적용되는 Request 종류
- Invocations of the XMLHttpRequest or Fetch APIs, as discussed above.
- Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be loaded cross-origin and used by web sites that are permitted to do so.
- WebGL textures.
- Images/video frames drawn to a canvas using drawImage().
- CSS Shapes from images.
10. CORS는 Server에서 Access-Control-Allow-Origin or Headers 를 통해서 지원되는 Origin, Header를 알려주는 방식
+ Client에서 요청 시, Simple Request 조건을 충족하면 PreFlight 없이 바로 Request, 충족 안하면 Option Method로 PreFlight (Access-Control-Request-Origin or Headers + Origin 헤더) 후 허용될 경우에만 Actual Request
+ Simple Request 기준 참고 (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests)
+ CORS는 보안관련이므로 Error 문구도 범용 문구
// Request OPTIONS /doc HTTP/1.1 Host: bar.other Origin: https://foo.example Access-Control-Request-Method: POST Access-Control-Request-Headers: X-PINGOTHER, Content-Type // Response Access-Control-Allow-Origin: https://foo.example Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: X-PINGOTHER, Content-Type Access-Control-Max-Age: 86400
11. Access-Control-Allow- 관련 헤더 Best Practices
- The server must not specify the "*" wildcard for the Access-Control-Allow-Origin response-header value, but must instead specify an explicit origin; for example: Access-Control-Allow-Origin: https://example.com
- The server must not specify the "*" wildcard for the Access-Control-Allow-Headers response-header value, but must instead specify an explicit list of header names; for example, Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
- The server must not specify the "*" wildcard for the Access-Control-Allow-Methods response-header value, but must instead specify an explicit list of method names; for example, Access-Control-Allow-Methods: POST, GET
+ credential과 관련하여 wildcard를 피해야하는 이유
+ If a request includes a credential (most commonly a Cookie header) and the response includes an Access-Control-Allow-Origin: * header (that is, with the wildcard), the browser will block access to the response, and report a CORS error in the devtools console. But if a request does include a credential (like the Cookie header) and the response includes an actual origin rather than the wildcard (like, for example, Access-Control-Allow-Origin: https://example.com), then the browser will allow access to the response from the specified origin. Also note that any Set-Cookie response header in a response would not set a cookie if the Access-Control-Allow-Origin value in that response is the "*" wildcard rather an actual origin
12. By default, in cross-origin XMLHttpRequest or Fetch invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest object or the Request constructor when it is invoked
+ 즉, CORS 요청 시, Third Party Cookie 말고 Credential 관련 Cookie는 default로 빠짐 (클라이언트 req.withCredentials = true; 및 서버 Access-Control-Allow-Credentials 설정 필요)
+ CORS-preflight requests must never include credentials. The response to a preflight request must specify Access-Control-Allow-Credentials: true to indicate that the actual request can be made with credentials
Additional.
1. Internet Explorer는 Port가 달라도 same origin으로 인식하거나, Trust Zone이면 SOP 적용 안된다든지 Exception 있음
2. document.domain 값을 바꾸면 origin을 변경할 수 있지만 deprecated
3. If the server specifies a single origin (that may dynamically change based on the requesting origin as part of an allowlist) rather than the "*" wildcard, then the server should also include Origin in the Vary response header to indicate to clients that server responses will differ based on the value of the Origin request header
Access-Control-Allow-Origin: https://mozilla.org Vary: Origin
4. Access-Control 관련 Response Header 참고 링크
+ https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#the_http_response_headers
5. (다음에) React 로컬 개발 시, CORS 해결하는 법 정리하기
Reference.
'개발 > Web' 카테고리의 다른 글
Web Security (0) 2022.06.12 HTTP Messages & MIME types (0) 2022.06.12 Content Security Policy (0) 2022.06.11 HTTPS (0) 2022.06.11 HTTP (0) 2022.06.11