Қауіпсіздік: Бір тектік саясат және клиенттік жазбалардың қорғалуы
Same-origin policy
Қауіпсіздік: Сайттардың қауіпсіздігін қамтамасыз ететін "бір түбір" саясаты. Сайт деректеріне қолжеткізуді шектейді, құпия ақпаратты қорғайды. SEO үшін маңызды!
Ағылшыншамен салыстырыңыз: абзацты басыңыз — түпнұсқа терезеде ашылады. Абзац астындағы EN түймесі оны мәтін ішінде көрсетеді.
Мазмұны
Кіріспе
Клиенттік жағындағы скрипттер үшін қауіпсіздік шарасы Компьютерлік техникада бірдей бастапқы саясат (SOP) — веб-қосымшаның қауіпсіздік моделіндегі ұғым. Бұл саясатқа сәйкес, веб-браузер бірінші веб-беттегі скрипттерге екінші веб-беттегі деректерге қол жеткізуге рұқсат береді, бірақ егер екі веб-беттің де бастапқы орны бірдей болса ғана. Бастапқы орын – URI схемасы, хост атауы және порт нөмірінің комбинациясы ретінде анықталады. Бұл саясат бір беттегі қауіпті скрипттердің басқа веб-беттегі құпия деректерге осы беттің (DOM) арқылы қол жеткізуіне жол бермейді. Бұл механизм, есіп келе жатқан веб-қосымшалар үшін аса маңызды, себебі олар пайдаланушы сеанстарын сақтау үшін HTTP cookie-лерге көп көңіл бөледі, ал серверлер HTTP cookie ақпаратына сүйене отырып, құпия ақпаратты ашады немесе күйін өзгертетін әрекеттер жасайды. Деректердің құпиялылығы мен толықтығын жоғалтудың алдын алу үшін клиенттік жағынан байланыссыз сайттар ұсынатын мазмұн қатаң түрде бөлініп сақталуы керек. Бірдей бастапқы саясат тек скрипттерге ғана қолданылады. Яғни, суреттер, CSS және динамикалық түрде жүктелетін скрипттер сияқты ресурстарға тиісті HTML тегтері арқылы (шрифттер ерекше жағдай) бастапқы орынға қарамастан қол жеткізуге болады. Шабуылдар HTML тегтеріне бірдей бастапқы саясат қолданылмайтындығын пайдаланады.
Security measure for client side scriptingIn computing, the same origin policy (SOP) is a concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, host name, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's (DOM). This mechanism bears a particular significance for modern web applications that extensively depend on HTTPScookies to maintain authenticated user sessions, as servers act based on the HTTP cookie information to reveal sensitive information or take state changing actions. A strict separation between content provided by unrelated sites must be maintained on the client side to prevent the loss of data confidentiality or integrity. The same origin policy applies only to scripts. This means that resources such as images, CSS, and dynamically loaded scripts can be accessed across origins via the corresponding HTML tags (with fonts being a notable exception). Attacks take advantage of the fact that the same origin policy does not apply to HTML tags.
Тарих
Бірдей шығу тегі саясаты тұжырымдамасы 1995 жылы Netscape Navigator 2.02 бағдарламасында, Netscape 2.0 бағдарламасында JavaScript енгізілгеннен кейін көп ұзамай пайда болды. JavaScript веб-беттерде скрипттерді қолдануға және әсіресе Document Object Model (DOM) құжат объектісіне бағдарламалық түрде қол жеткізуге мүмкіндік берді. Бұл саясат бастапқыда DOM-ға қол жеткізуді қорғау мақсатымен жасалған, бірақ кейіннен жаһандық JavaScript объектісінің құпия бөліктерін қорғау үшін кеңейтілді.
The concept of same origin policy was introduced by Netscape Navigator 2.02 in 1995, shortly after the introduction of JavaScript in Netscape 2.0. JavaScript enabled scripting on web pages, and in particular programmatic access to the Document Object Model (DOM). The policy was originally designed to protect access to the DOM, but has since been broadened to protect sensitive parts of the global JavaScript object.
Іске асыру
Барлық заманауи браузерлер бірдей шығу саясатының қандай да бір түрін қолданады, себебі ол маңызды қауіпсіздіктің негізгі тасы болып табылады. Саясаттар міндетті түрде нақты талаптарға сәйкес келуі керек емес, бірақ көбінесе Microsoft Silverlight, Adobe Flash немесе Adobe Acrobat сияқты басқа веб-технологиялар үшін, сондай-ақ тікелей DOM манипуляциясынан өзгеше механизмдер үшін, мысалы XMLHttpRequest үшін, шамамен үйлесімді қауіпсіздік шекараларын анықтау мақсатында кеңейтіледі.
All modern browsers implement some form of the same origin policy as it is an important security cornerstone. The policies are not required to match an exact specification but are often extended to define roughly compatible security boundaries for other web technologies, such as Microsoft Silverlight, Adobe Flash, or Adobe Acrobat, or for mechanisms other than direct DOM manipulation, such as XMLHttpRequest.
Шығу тегін анықтау ережесі
URI-дың "шығу тегін" есептеу үшін қолданылатын алгоритм RFC 6454, 4-бөлімінде көрсетілген. Абсолюттік URI үшін шығу тегі үштік {схема, хост, порт}. Егер URI атау авторитеті ретінде иерархиялық элементті қолданбаса (RFC 3986, 3.2 бөлімін қараңыз) немесе URI абсолюттік URI болмаса, онда жаһандық бірегей идентификатор қолданылады. Екі ресурс бір шығу тегі деп есептеледі, егер және тек қана егер осы мәндердің барлығы бірдей болса. Мысалы, келесі кестеде "http://www.example.com/dir/page.html" URL-імен салыстыру нәтижелері көрсетілген:
The algorithm used to calculate the "origin" of a URI is specified in RFC 6454, Section 4. For absolute URIs, the origin is the triple {scheme, host, port}. If the URI does not use a hierarchical element as a naming authority (see RFC 3986, Section 3.2) or if the URI is not an absolute URI, then a globally unique identifier is used. Two resources are considered to be of the same origin if and only if all these values are exactly the same. To illustrate, the following table gives an overview of typical outcomes for checks against the URL "http://www. example. com/dir/page. html". + Compared URL Outcome Reason http://www. example. com/dir/page2. html Same scheme, host and port http://www. example. com/dir2/other. html Same scheme, host and port http://username:password@www. example. com/dir2/other. html Same scheme, host and port http://www. example. com:80/dir/other. html Most modern browsers implicitly assign the protocol's default port when omitted. http://www. example. com:81/dir/other. html Same scheme and host but different port https://www. example. com/dir/other. html Different scheme http://en. example. com/dir/other. html Different host http://example. com/dir/other. html Different host (exact match required) http://v2. www. example. com/dir/other. html Different host (exact match required) data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA= Different scheme
Unlike other browsers, Internet Explorer does not include the port in the calculation of the origin, using the Security Zone in its place.
+ Салыстырылатын URL Нәтиже Себебі
http://www.example.com/dir/page2.html Бірдей схема, хост және порт
http://www.example.com/dir2/other.html Бірдей схема, хост және порт
http://username:password@www.example.com/dir2/other.html Бірдей схема, хост және порт
http://www.example.com:80/dir/other.html Көптеген қазіргі браузерлер протоколдың әдепкі портын көрсетілмеген жағдайда автоматты түрде қосады.
http://www.example.com:81/dir/other.html Бірдей схема және хост, бірақ әртүрлі порт
https://www.example.com/dir/other.html Әртүрлі схема
http://en.example.com/dir/other.html Әртүрлі хост
http://example.com/dir/other.html Әртүрлі хост (нақты сәйкестік қажет)
http://v2.www.example.com/dir/other.html Әртүрлі хост (нақты сәйкестік қажет)
data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA= Әртүрлі схема
The algorithm used to calculate the "origin" of a URI is specified in RFC 6454, Section 4. For absolute URIs, the origin is the triple {scheme, host, port}. If the URI does not use a hierarchical element as a naming authority (see RFC 3986, Section 3.2) or if the URI is not an absolute URI, then a globally unique identifier is used. Two resources are considered to be of the same origin if and only if all these values are exactly the same. To illustrate, the following table gives an overview of typical outcomes for checks against the URL "http://www. example. com/dir/page. html". + Compared URL Outcome Reason http://www. example. com/dir/page2. html Same scheme, host and port http://www. example. com/dir2/other. html Same scheme, host and port http://username:password@www. example. com/dir2/other. html Same scheme, host and port http://www. example. com:80/dir/other. html Most modern browsers implicitly assign the protocol's default port when omitted. http://www. example. com:81/dir/other. html Same scheme and host but different port https://www. example. com/dir/other. html Different scheme http://en. example. com/dir/other. html Different host http://example. com/dir/other. html Different host (exact match required) http://v2. www. example. com/dir/other. html Different host (exact match required) data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA= Different scheme
Unlike other browsers, Internet Explorer does not include the port in the calculation of the origin, using the Security Zone in its place.
Басқа браузерлерден айырмашылығы, Internet Explorer шығу тегін есептеуде портты қамтымайды, оның орнына Қауіпсіздік аймағын пайдаланады.
The algorithm used to calculate the "origin" of a URI is specified in RFC 6454, Section 4. For absolute URIs, the origin is the triple {scheme, host, port}. If the URI does not use a hierarchical element as a naming authority (see RFC 3986, Section 3.2) or if the URI is not an absolute URI, then a globally unique identifier is used. Two resources are considered to be of the same origin if and only if all these values are exactly the same. To illustrate, the following table gives an overview of typical outcomes for checks against the URL "http://www. example. com/dir/page. html". + Compared URL Outcome Reason http://www. example. com/dir/page2. html Same scheme, host and port http://www. example. com/dir2/other. html Same scheme, host and port http://username:password@www. example. com/dir2/other. html Same scheme, host and port http://www. example. com:80/dir/other. html Most modern browsers implicitly assign the protocol's default port when omitted. http://www. example. com:81/dir/other. html Same scheme and host but different port https://www. example. com/dir/other. html Different scheme http://en. example. com/dir/other. html Different host http://example. com/dir/other. html Different host (exact match required) http://v2. www. example. com/dir/other. html Different host (exact match required) data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA= Different scheme
Unlike other browsers, Internet Explorer does not include the port in the calculation of the origin, using the Security Zone in its place.
Қайта қолдануға болатын аутентификация арқылы қайсыбір шығу тегі бар сезімтал жауаптарға оқуға рұқсат
Бірдей шығу саясаты аутентификацияланған сеанстарды әртүрлі домендерде қайта пайдаланудан қорғайды. Келесі мысал, бірдей шығу саясаты болмаған жағдайда туындауы мүмкін қауіпсіздік тәуекелін көрсетеді. Егер пайдаланушы банк сайтына кіріп, шығып кетпесе, содан кейін ол зиянды JavaScript коды бар басқа сайтқа өтеді, бұл код банк сайтынан деректерді сұрайды. Пайдаланушы әлі де банк сайтында авторизацияланғандықтан, зиянды код пайдаланушы банк сайтында жасай алатын кез келген әрекетті орындай алады. Мысалы, ол пайдаланушының соңғы транзакцияларының тізімін алуға, жаңа транзакция жасауға және т.б. мүмкіндік алады. Мұның себебі, әлемдік желінің бастапқы мағынасында, браузерлер банк сайтының доменіне сәйкес сеанстық cookie-лар мен авторизация сұранысының платформа деңгейіндегі түрлері сияқты аутентификация мәліметтерін банк сайтына жіберуі керек. Банк сайтының иелері, зиянды сайтқа кіретін пайдаланушылардың қалыпты браузерлері, зиянды сайттан жүктелген кодтың банк сессиясының cookie-сына немесе платформа деңгейіндегі авторизацияға қол жеткізбеуін күтеді. JavaScript банк сессиясының cookie-сына тікелей қол жеткізе алмайтын болса да, ол банк сайтының сессиясының cookie-і арқылы банк сайтына сұрауларды жіберуге және қабылдауға болады. Бірдей шығу саясаты қауіпсіздікке баса назар аударатын браузерлерге, пайдаланушылардың көпшілігі сәйкес браузерлерді пайдалануды таңдайды деген болжаммен, әртүрлі домендерден алынған жауаптарға оқуға рұқсат беруден бас тарту талабы ретінде енгізілді. Бұл саясат жазуға рұқсат бермейді. Жазу рұқсатының теріс пайдаланылуына қарсы тұру үшін мақсатты сайттардан қосымша CSRF қорғанысы қажет.
The same origin policy protects against reusing authenticated sessions across origins. The following example illustrates a potential security risk that could arise without the same origin policy. Assume that a user is visiting a banking website and doesn't log out. Then, the user goes to another site that has malicious JavaScript code that requests data from the banking site. Because the user is still logged in on the banking site, the malicious code could do anything the user could do on the banking site. For example, it could get a list of the user's last transactions, create a new transaction, etc. This is because, in the original spirit of a world wide web, browsers are required to tag along authentication details such as session cookies and platform level kinds of the Authorization request header to the banking site based on the domain of the banking site. The bank site owners would expect that regular browsers of users visiting the malicious site do not allow the code loaded from the malicious site access the banking session cookie or platform level authorization. While it is true that JavaScript has no direct access to the banking session cookie, it could still send and receive requests to the banking site with the banking site's session cookie. Same Origin Policy was introduced as a requirement for security minded browsers to deny read access to responses from across origins, with the assumption that the majority of users choose to use compliant browsers. The policy does not deny writes. Counteracting the abuse of the write permission requires additional CSRF protections by the target sites.
Бір шығу тегі бар тауарлар саясатын жеңілдету
Кейбір жағдайларда, бірдей шығу тегі саясаты тым шектеулі болып табылады, бұл көптеген субдомендерді пайдаланатын ірі веб-сайттар үшін мәселе тудырады. Алғашқыда, фрагмент идентификаторын немесе window.name қасиетін пайдалану сияқты бірнеше шешімдер әртүрлі домендерде орналасқан құжаттар арасында деректерді жіберу үшін қолданылды. Қазіргі заманғы браузерлер бірдей шығу саясатын бақыланатын түрде жеңілдету үшін бірнеше техниканы қолдайды:
In some circumstances, the same origin policy is too restrictive, posing problems for large websites that use multiple subdomains. At first, a number of workarounds such as using the fragment identifier or the window. name property were used to pass data between documents residing in different domains. Modern browsers support multiple techniques for relaxing the same origin policy in a controlled manner:
Деректерді бұрмалау
Netscape Navigator қысқа мерзімге ластануды тексеру мүмкіндігін қамтыды. Бұл мүмкіндік 1997 жылы Netscape 3-тің құрамына тәжірибелік режімде енгізілді. Мүмкіндік әдепкі бойынша өшірілген, бірақ пайдаланушы оны қосса, веб-сайттарға басқа доменге тиесілі терезелер мен фреймдердің JavaScript қасиеттерін оқуға талпынуға рұқсат беретін еді. Браузер содан кейін пайдаланушыдан осы қолжетімділікке рұқсат беру керек пе деп сұрайтын.
Netscape Navigator briefly contained a taint checking feature. The feature was experimentally introduced in 1997 as part of Netscape 3. The feature was turned off by default, but if enabled by a user it would allow websites to attempt to read JavaScript properties of windows and frames belonging to a different domain. The browser would then ask the user whether to permit the access in question.
document.domain қасиеттері
Егер екі терезеде (немесе фреймде) доменді бірдей мәнге орнататын скрипттер болса, осы екі терезе үшін бірдей шығу саясаты жеңілдетіледі және әр терезе екіншісімен өзара әрекеттесе алады. Мысалы, orders.example.com және catalog.example.com мекенжайларынан жүктелген құжаттардағы ынтымақтастық скрипттері өздерінің document.domain қасиеттерін “example.com” деп орнату арқылы құжаттардың бірдей шығу тегінен келгендей көрінуіне және әр құжаттың екіншісінің қасиеттерін оқуына мүмкіндік береді. Бұл қасиетті орнату портты null-ге орнатады, көптеген браузерлер бұл мәнді 80-ші порттан немесе тіпті белгіленбеген порттан әртүрлі түсінеді. Браузердің қол жеткізімділікке рұқсат беретініне көз жеткізу үшін екі беттің де document.domain қасиетін орнатыңыз. document.domain тұжырымы 1996 жылы шыққан Netscape Navigator 3-тің бір бөлігі ретінде енгізілді. Ол серверлерге файлды сұрауға болатын шығу тегінің тізімін нақты көрсетуге немесе wildcard пайдаланып, кез келген сайттың файлды сұрауына рұқсат беруге мүмкіндік береді. Firefox 3.5, Safari 4 және Internet Explorer 10 сияқты браузерлер осы басты XMLHttpRequest арқылы көлденең шығу HTTP сұраныстарын рұқсат ету үшін пайдаланады, әйтпесе олар бірдей шығу саясатымен тыйым салынар еді.
If two windows (or frames) contain scripts that set domain to the same value, the same origin policy is relaxed for these two windows, and each window can interact with the other. For example, cooperating scripts in documents loaded from orders. example. com and catalog. example. com might set their document. domain properties to “example. com”, thereby making the documents appear to have the same origin and enabling each document to read properties of the other. Setting this property implicitly sets the port to null, which most browsers will interpret differently from port 80 or even an unspecified port. To assure that access will be allowed by the browser, set the document. domain property of both pages. The document. domain concept was introduced as part of Netscape Navigator 3, released in 1996. It allows servers to use a header to explicitly list origins that may request a file or to use a wildcard and allow a file to be requested by any site. Browsers such as Firefox 3.5, Safari 4 and Internet Explorer 10 use this header to allow the cross origin HTTP requests with XMLHttpRequest that would otherwise have been forbidden by the same origin policy.
Құжаттар арасындағы хабарласу
Басқа бір техника, құжаттар аралық хабар алмасу, бір беттегі скриптке екінші беттегі скриптке, олардың бастапқы орнына қарамастан, мәтіндік хабарларды жіберуге мүмкіндік береді. Window нысанының postMessage әдісін шақыру сол терезенің "onmessage" оқиғасын асинхронды түрде ояту арқылы пайдаланушы анықтаған оқиғаларды өңдеушілерді іске қосады. Бір беттегі скрипт екінші беттегі әдістерге немесе айнымалыларға тікелей қол жеткізе алмайды, бірақ олар осы хабар алмасу техникасы арқылы қауіпсіз байланыс орната алады.
Another technique, cross document messaging allows a script from one page to pass textual messages to a script on another page regardless of the script origins. Calling the postMessage method on a Window object asynchronously fires an "onmessage" event in that window, triggering any user defined event handlers. A script in one page still cannot directly access methods or variables in the other page, but they can communicate safely through this message passing technique.
JSONP
HTML <script> элементтері басқа домендерден мазмұн алуға және орындауға рұқсат етілгендіктен, бір бет сол тектік саясатты (same origin policy) айналып өтіп, JSON деректерін басқа доменнен JSONP пайдалы жүктемесін қайтаратын ресурс арқылы жүктеу арқылы ала алады. JSONP пайдалы жүктемелері алдын ала анықталған функция шақыруымен оралған JSON деректерінен тұрады. Скрипт ресурсы браузерде жүктелгенде, оралған JSON деректерін өңдеу үшін белгіленген кері шақыру функциясы іске қосылады.
Since HTML <script> elements are allowed to retrieve and execute content from other domains, a page can bypass the same origin policy and receive JSON data from a different domain by loading a resource that returns a JSONP payload. JSONP payloads consist of an internal JSON payload wrapped by a pre defined function call. When the script resource is loaded by the browser, the designated callback function will be invoked to process the wrapped JSON payload.
Веб-сакеттер
Қазіргі заманғы браузерлер скриптке бірдей домендік саясатты қолданбастан WebSocket адресіне қосылуға мүмкіндік береді. Дегенмен, олар WebSocket URI пайдаланылған кезде оны анықтап, қосылыс сұраған скрипттің бастапқы доменін көрсететін Origin: аттрибутын сұранысқа қосады. Қайтаралық қауіпсіздікті қамтамасыз ету үшін WebSocket сервері осы аттрибуттың деректерін, жауап алуға рұқсат етілген бастапқы домендердің тізімімен салыстыруы тиіс.
Modern browsers will permit a script to connect to a WebSocket address without applying the same origin policy. However, they recognize when a WebSocket URI is used, and insert an Origin: header into the request that indicates the origin of the script requesting the connection. To ensure cross site security, the WebSocket server must compare the header data against an allowlist of origins permitted to receive a reply.
Бұрыш қалталары
Бірдей шығу тегі тексерулері мен байланысты механизмдердің мінез-құлқы, URL-деріне нақты анықталған хост атауы немесе порт тіркелмеген псевдо-протоколдар сияқты, бірқатар шектен шығу жағдайларында толық анықталмаған (мысалы, файл:, деректер: т.б.). Бұл тарихи түрде көптеген қауіпсіздік мәселелеріне әкеп соқты, мысалы, кез келген жергілікті сақталған HTML файлының дискідегі барлық басқа файлдарға қол жеткізуі немесе интернеттегі кез келген сайтпен байланыс орнату мүмкіндігі. Сонымен қатар, DNS қайта байланыстыру немесе серверлік проксилер сияқты шабуыл түрлері хост атауын тексеруді ішінара жоюға мүмкіндік береді, соның салдарынан қаскөй веб-беттер өздерінің "нақты" канондық шығу тегінен өзгеше мекенжайлар арқылы сайттармен тікелей өзара әрекеттесе алады. Мұндай шабуылдардың салдары өте нақты жағдайлармен шектеледі, себебі браузер әлі де шабуылшының сайтымен байланыс орнатып жатыр деп санайды, сондықтан үшінші тарап cookie-лары немесе басқа құпия ақпарат шабуылшыға берілмейді.
The behavior of same origin checks and related mechanisms is not well defined in a number of corner cases such as for pseudo protocols that do not have a clearly defined host name or port associated with their URLs (file:, data:, etc.). This historically caused a fair number of security problems, such as the generally undesirable ability of any locally stored HTML file to access all other files on the disk, or communicate with any site on the Internet. Lastly, certain types of attacks, such as DNS rebinding or server side proxies, permit the host name check to be partly subverted, and make it possible for rogue web pages to directly interact with sites through addresses other than their "true", canonical origin. The impact of such attacks is limited to very specific scenarios, since the browser still believes that it is interacting with the attacker's site, and therefore does not disclose third party cookies or other sensitive information to the attacker.
Шабуылдар
Тіпті бірдей шығу саясаты қолданылып тұрған кезде де (Cross Origin Resource Sharing арқылы жеңілдетілмесе), кейбір кросс-оригиналдық шабуылдар жасалуы мүмкін. WebRTC арқылы құрбаның ішкі IP-адресін анықтауға болады. Егер кросс-оригиналдық портқа қосылуға тырысылса, жауаптар бірдей шығу саясатына қарамастан оқуға болмайды, бірақ JavaScript жүктелу/қателік оқиғасы орын алса немесе уақыт бітсе, порттың ашық немесе жабық екендігі туралы шешім қабылдай алады. Бұл кросс-оригиналдық портты сканерлеуге мүмкіндік береді. Сонымен қатар, JavaScript кодтары сайттар аралық ақпарат ағыны сияқты техникаларды пайдаланып, браузердегі ұзақ жылдар бойы сақталған ақпараттың ағып кетуін пайдаланып, кросс-оригинал туралы ақпаратты анықтай алады.
Even when same origin policy is in effect (without being relaxed by Cross Origin Resource Sharing), certain cross origin attacks can be performed. WebRTC can be used to find out the internal IP address of a victim. If attempting to connect to a cross origin port, responses cannot be read in face of same origin policy, but a JavaScript can still make inferences on whether the port is open or closed by checking if the onload/onerror event fires, or if we get a timeout. This gives opportunities for cross origin portscanning. Further, JavaScript snippets can use techniques like cross site leaks to exploit long standing information leakages in the browser to infer information about cross origin.