NginxЧÀÍÆ÷µÄ¿çÕ¾ÇëÇóαÔ죨CSRF£©ºÍ¿çÕ¾¾ç±¾¹¥»÷£¨XSS£©Ìá·À¼¼ÇÉ
nginxЧÀÍÆ÷µÄ¿çÕ¾ÇëÇóαÔ죨csrf£©ºÍ¿çÕ¾¾ç±¾¹¥»÷£¨xss£©Ìá·À¼¼ÇÉ
Ëæ×Å»¥ÁªÍøµÄѸÃÍÉú³¤£¬WebÓ¦ÓóÌÐò³ÉΪÁ˸÷ÈËÉúÑĺÍÊÂÇéÖеÄÖ÷Òª×é³É²¿·Ö¡£È»¶ø£¬WebÓ¦ÓóÌÐòÒ²ÃæÁÙ×ÅÇå¾²Íþв£¬ÆäÖпçÕ¾ÇëÇóαÔ죨CSRF£©ºÍ¿çÕ¾¾ç±¾¹¥»÷£¨XSS£©ÊÇ×î³£¼ûµÄÁ½ÖÖ¹¥»÷·½·¨¡£ÎªÁË°ü¹ÜWebÓ¦ÓóÌÐòµÄÇå¾²ÐÔ£¬ÎÒÃÇÐèÒªÔÚNginxЧÀÍÆ÷ÉϽÓÄÉÏìÓ¦µÄÌá·À²½·¥¡£
Ò»¡¢Ìá·À¿çÕ¾ÇëÇóαÔ죨CSRF£©¹¥»÷
¿çÕ¾ÇëÇóαÔì¹¥»÷ÊÇÖ¸¹¥»÷Õßͨ¹ýαװÕýµ±Óû§µÄÇëÇó£¬ÓÕʹÓû§ÔÚ²»ÖªÇéµÄÇéÐÎϾÙÐÐijЩ²Ù×÷£¬ÀýÈç·¢ËÍÓʼþ¡¢×ªÕË¡¢ÐÞ¸ÄÃÜÂëµÈ¡£ÎªÁ˱ÜÃâCSRF¹¥»÷£¬ÎÒÃÇ¿ÉÒÔÔÚNginxЧÀÍÆ÷ÉÏÌí¼ÓCSRFÁîÅÆÑéÖ¤µÄÖÐÐļþ¡£
ÒÔÏÂÊÇÒ»¸öʾÀý´úÂ룺
ÔÚNginxÉèÖÃÎļþÖУ¬Ìí¼ÓÒÔÏ´úÂ룺
location / { add_header X-Frame-Options "SAMEORIGIN"; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options "nosniff"; if ($request_method !~ ^(GET|HEAD|POST)$) { return 444; } if ($http_referer !~ ^(https?://(www.)?example.com)) { return 403; } if ($http_cookie !~ "csrf_token=([^;]+)(?:;|$)") { return 403; } # ÔÚ´Ë´¦¾ÙÐÐÆäËû´¦Àí }
µÇ¼ºó¸´ÖÆ
ÔÚWebÓ¦ÓóÌÐòÖУ¬ÌìÉúCSRFÁîÅƲ¢½«Æä°üÀ¨ÔÚÿ¸ö±íµ¥ÖУº
<form method="post" action="/submit"> <input type="hidden" name="csrf_token" value="{{ csrf_token }}"> <input type="submit" value="Ìá½»"> </form>
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖеÄcsrf_token¿ÉÒÔÊÇËæ»úÌìÉúµÄ×Ö·û´®£¬´æ´¢ÔÚÓû§»á»°ÖУ¬ÔÚÿ¸ö±íµ¥Ìá½»µÄʱ¼ä¶¯Ì¬ÌìÉú²¢Ìí¼ÓÔÚ±íµ¥ÖС£
¶þ¡¢Ìá·À¿çÕ¾¾ç±¾¹¥»÷£¨XSS£©
¿çÕ¾¾ç±¾¹¥»÷ÊÇÖ¸¹¥»÷ÕßÔÚÍøÒ³ÖÐǶÈë¶ñÒâ¾ç±¾£¬µ±Óû§»á¼û¸ÃÍøҳʱ£¬¶ñÒâ¾ç±¾»á±»Ö´ÐУ¬´Ó¶øµ¼ÖÂÓû§µÄÐÅÏ¢±»ÇÔÈ¡¡£ÎªÁ˱ÜÃâXSS¹¥»÷£¬ÎÒÃÇ¿ÉÒÔÔÚNginxЧÀÍÆ÷ÉÏÌí¼ÓX-XSS-ProtectionÍ·£¬ÒÔ¼°ÆäËûÏà¹ØµÄÇ徲ͷ¡£
ÒÔÏÂÊÇÒ»¸öʾÀý´úÂ룺
ÔÚNginxÉèÖÃÎļþÖУ¬Ìí¼ÓÒÔÏ´úÂ룺
location / { add_header X-Frame-Options "SAMEORIGIN"; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options "nosniff"; # ÔÚ´Ë´¦¾ÙÐÐÆäËû´¦Àí }
µÇ¼ºó¸´ÖÆ
ÉÏÊö´úÂëÖеÄadd_headerÖ¸Áî»áÔÚHTTPÏìÓ¦ÖÐÌí¼ÓÏìÓ¦µÄÍ·²¿ÐÅÏ¢£¬ÆäÖÐX-XSS-ProtectionÍ·²¿¿ÉÒÔ¿ªÆôä¯ÀÀÆ÷ÄÚÖõÄXSS¹ýÂËÆ÷£¬×èÖ¹¶ñÒâ¾ç±¾µÄÖ´ÐС£
ÔÚWebÓ¦ÓóÌÐòÖжÔÓû§ÊäÈë¾ÙÐкÏÊʵĹýÂ˺ÍתÒå´¦Àí£º
ÀýÈ磬¿ÉÒÔʹÓÃHTMLתÒ庯Êý¶ÔÓû§µÄÊäÈë¾ÙÐÐתÒ壬½«ÌØÊâ×Ö·ûת»»ÎªÊµÌå±àÂ룺
function escapeHtml(input) { return input.replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); }
µÇ¼ºó¸´ÖÆ
ÔÚÊä³öÓû§ÊäÈëµÄµØ·½£¬Å²Óøú¯Êý¶ÔÓû§µÄÊäÈë¾ÙÐÐתÒå´¦Àí¡£
×ÛÉÏËùÊö£¬Í¨¹ýÔÚNginxЧÀÍÆ÷ÉÏÌí¼ÓCSRFÁîÅÆÑéÖ¤ÖÐÐļþºÍÏìÓ¦µÄÇ徲ͷ£¬ÒÔ¼°ÔÚWebÓ¦ÓóÌÐòÖжÔÓû§ÊäÈë¾ÙÐкÏÊʵĴ¦Àí£¬¿ÉÒÔÓÐÓÃÌá·À¿çÕ¾ÇëÇóαÔìºÍ¿çÕ¾¾ç±¾¹¥»÷¡£ËäÈ»£¬Õâ½ö½öÊÇһЩ»ù±¾µÄÌá·À²½·¥£¬Õë¶Ô²î±ðµÄÓ¦Óó¡¾°»¹ÐèҪƾ֤ÏêϸÇéÐνÓÄÉÔ½·¢ÖÜÈ«ºÍ¸öÐÔ»¯µÄÇå¾²²½·¥¡£
ÒÔÉϾÍÊÇNginxЧÀÍÆ÷µÄ¿çÕ¾ÇëÇóαÔ죨CSRF£©ºÍ¿çÕ¾¾ç±¾¹¥»÷£¨XSS£©Ìá·À¼¼ÇɵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡