Web Security Concepts
There are many security risks in WEB applications, such as hacking, tampering with web content, stealing internal data from the site, and, more seriously, embedding malicious code into the Web to make users vulnerable. Common security vulnerabilities include the following:
- XSS attacks: Inject scripts into Web pages, use JavaScript to steal user information, and induce user action.
- CSRF attack: Forge a user request for a malicious request to a Web site.
- Phishing attack: Use the site's jump links or images to make fishing traps.
- HTTP parameter pollution: using the Imperfect parameter format verification, the server is injected with the parameter injection attack.
- Remote code Execution: the user submits the execution command through the browser, because the server side does not filter on the execution function, resulting in the execution of the command without specifying an absolute path.
Security threats
XSS
The prevention
XSS (cross-site scripting cross-domain scripting attack) attacks are the most common Web attacks, with a focus on "cross-domain" and "client-side execution."
What can XSS do?
- Get page data
- Access to Cookies
- Hijack front-end logic
- Send Request
- Steal any data from the website
- Stealing user Data
- Steal user passwords and login status
Case
- Station cool, you can wear JS, import a picture, using SRC to fetch cookies, you can take the login state
- QQ Space
XSS attacks inject XSS
Reflected XSS
The main URL with parameters, sent to others, can be turned into a short URL
A reflective XSS attack, primarily due to the server receiving unsecured input from the client, triggers execution on the client side to initiate a Web attack. Like what:
Search for items on a shopping site, the search results will show the search keywords. Search keywords fill in <script>alert(‘handsome boy‘)</script>
, click Search. The page does not filter the keywords, this code will be executed directly on the page, pop alert.
Stored XSS
Storage-based XSS attacks, which are stored on the server by committing content with malicious scripts, initiate a Web attack when others see the content. Generally submitted content is edited by some rich text editor, it is easy to insert dangerous code.
JSONP XSS
JSONP's callback parameter is very dangerous, and he has two risks that could lead to XSS
1, callback parameters accidentally truncated JS code, special character single quotation marks, newline characters are at risk.
2, callback parameter malicious add tags (such as <script>
), causing XSS vulnerability.
How to prevent XSS
There are two types of attitudes to choose from: The first is pre-filtering, which escapes all user data and outputs directly at the front-end (template rendering) level. The second is that the data entered by the user is stored directly without escaping, and the front end is guaranteed to escape the data when it is used.
- 1, (@1 type @2) browser with self-defense, set x-xss-protection, but only to prevent HTML-related, but not every browser is supported, only support the reverse type
- 2, (@1 type @2) output untrusted variable to Div/body/attribute/javascript Tag/style before, to & < > "'/Escape, escape can be stored, or when displayed
- 3, (@1 type @2 type @3 type) try not to output the non-trusted variable in a specific place: Script/comment/attribute/tag/style, because there are too many strings to escape HTMl rules.
- 4. (@4 type) Rich text type, keep some labels and attributes by white list. The benefits are more comprehensive, but more troublesome, the blacklist is not comprehensive. You can use Cheerio to implement
- UrlEncode the untrusted variable before the URL parameter is output
- Filtering using the appropriate HTML filtering library
- Prevent dom-based XSS, see DOM based XSS prevention Cheat Sheet
- Turn on HttpOnly cookies to make the browser inaccessible to cookies
- CSP is also a solution
Whitelist XSS or the library that uses XSS
const cheerio = require(‘cheerio‘);const fs = require(‘fs‘);const html = fs.readFileSync(‘./html.html‘, ‘utf8‘);const $ = cheerio.load(html);const whiteList = { ‘img‘: [‘src‘] }console.log($.html());$(‘*‘).each((index, elem) => { if (!whiteList[elem.name]) { $(elem).remove(); return; } for(let attr in elem.attribs) { if (whiteList[elem.name].indexOf(attr) === -1){ $(elem).attr(attr, null) } }})console.log(‘d‘, $.html());
DS7
The Content Security Policy, referred to as CSP, is primarily used to define what resources the page can load and reduce the occurrence of XSS.
The essence of CSP is the white list system, where developers explicitly tell clients which external resources can be loaded and executed, equivalent to providing a whitelist. Its implementation and execution are all done by the browser, and developers only need to provide configuration.
Can filtering Html tags prevent XSS?
Please list the circumstances of the failure?
用户除了上传<script>alert(‘xss‘);</script>还可以使用图片 url 等方式来上传脚本进行攻击<table background="javascript:alert(/xss/)"></table>还可以通过各种编码转换 (URL 编码, Unicode 编码, HTML 编码, ESCAPE 等) 来绕过检查
Prevention of security threat CSRF
CSRF (Cross-site request forgery cross-site solicitation forgery, also known as One Click Attack
or Session Riding
, usually abbreviated as CSRF or XSRF, is a malicious exploitation of the site.
CSRF attacks can make malicious and bogus requests to websites, which seriously affect the security of the website. Therefore, the framework has built-in CSRF prevention scheme.
Harm
Generally speaking, there are some general precautions for CSRF attacks, and a brief introduction to several common precautions:
- Synchronizer Tokens: Renders token to the page by responding to the page, and submits it through the hidden field when the form form is submitted.
- Double Cookie Defense: Place token in a cookie, submit a cookie when submitting a POST request, and perform a comparison check with the token in the cookie on the header or body with the server.
- Custom Header: Trusts a request with a specific header (for example
X-Requested-With: XMLHttpRequest
). This scheme can be bypassed, so frameworks like rails and Django have given up on this precaution.
- Cookies can be set using Samesite to restrict the portability of cookies, but as long as Chrome supports it,
- Can referer head can judge is not from your own URL
The framework combines the above methods and provides a configurable CSRF prevention strategy.
- You can use the Image verification code
How to synchronize the CSRF check of a form using
When you synchronize the rendered page, add a URL query with the name to the form request, and the _csrf
value is so that the user submits the ctx.csrf
CSRF token when the form is submitted:
AJAX Requests
In the CSRF default configuration, tokens are set in the cookie, which can be taken from the cookie when the AJAX request is sent to the server in query, body, or header.
In JQuery:
var csrftoken = Cookies.get(‘csrfToken‘);function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));}$.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader(‘x-csrf-token‘, csrftoken); } },});
Session vs Cookie Storage
By default, the framework will present CSRF tokens in a Cookie to facilitate AJAX requests. However, all subdomains can have cookies set, so when our app is in a situation where it is not guaranteed that all subdomains are controlled, there may be a risk of CSRF attack in the cookie. The framework provides a configuration item that allows tokens to be stored in the Session.
Refresh CSRF Token
When CSRF token is stored in a Cookie, once a user switch occurs on the same browser, the new user will continue to use the old token (previously used by the user), which poses a security risk, so the CSRF token must be refreshed every time the user logs on .
Cookies
Homologous policy
Characteristics
The security policy of cookies
Signature Tamper-proof
Private Transformations (encryption)
Http-only
Secure
Same-site
Click Hijack
User hands-on operation, but users do not know, thereby stealing user funds (transfer consumption), access to user information
Web page iframe to operate the Web page, and then the target site is transparent to 0, so that the click button and the attacker's design background set to a stop
Click Hijack Defense
HTTP is a widely used protocol for Web applications and is responsible for the request and acquisition of content. However, content requests and fetches go through many intermediaries, mainly network links, browsers that act as content portals, router vendors, WiFi providers, communications operators, and, if you use proxies, FQ software will introduce more intermediaries. Because the path to HTTP requests, the parameters are plaintext by default, these intermediaries can monitor, hijack, and block HTTP requests.
Without HTTPS, carriers can jump directly to an ad when a user initiates a request, or directly change the search results into their own ads. If there is a BUG in the hijacked code, the user will not be able to use it directly, and a white screen appears.
Data leakage, request hijacking, content tampering, and so on, the core reason is that HTTP is a full-naked plaintext request, domain names, paths and parameters are clearly seen by the middle people. HTTPS does is to encrypt the request, making it more secure for the user. For themselves in addition to protect the interests of users, but also to avoid their own traffic is held hostage, in order to protect their own interests.
Although HTTPS is not completely secure, the organization that grasps the root certificate and the organizations that master the cryptographic algorithms can also attack in the form of an intermediary. However, HTTPS is the safest solution under the current architecture, and it dramatically increases the cost of a man-in-the-middle attack.
Password safe
The role of the password
Storage of passwords
Transmission of passwords
Alternatives to passwords
Biometric password issues
Security of password transmission
- HTTP Transport
- Frequency limit
- Front-end encryption has limited meaning
Sql/nosql Injection
Injection attacks are when some of the operations performed by the user are passed in, and the user can inject their malicious logic into the operation. When you use the eval, new Function, and other methods to execute a string that has user input, you may be injected into the attack. The XSS above is an injection attack. The previous section also mentions that node. JS's child_process.exec can be injected into the attack if some of the executed commands are part of user input, due to a call to bash parsing.
Prevention and control means
- Prefix table name/field name (avoid being guessed)
- Error hiding table information (avoid being seen, 12306 get up early on the problem)----turn off incorrect output
- Filtering key characters that can be spliced into SQL
- Escaping user input----escaping the data
- Verify the type of user input (avoid limit, order by, and so on)----check the data type
- Using parameterized queries
- Using ORM (Object Relational mapping)
Upload question
Upload files, re-access uploaded files, uploaded files are interpreted as a program (NODEJS Basic does not exist, PHP and other problems)
- Limit upload suffix
- File type checking
- File content Check
- Program output
- Permission control-Writable executable mutex
Ways to disclose information
- Error message out of control
- SQL injection
- Improper level of authority control
- Xss/csrf
OAuth can
Other security issues denial of service Dos
1. TCP半连接1. HTTP连接1. DNS
Massive distributed denial of service attack DDoS
- Flow rate up to dozens of G
- Distributed (broiler, agent)
- Very difficult to defend
Dos Attack defense
- Firewall
- Switch/router
- Flow Cleaning
- High Anti-IP
- Avoid heavy logic business
- Quick Fail Quick return
- Anti-avalanche mechanism
- Lossy services
- Cdn
Replay attack
The request was intercepted or bugged, then exploited by the attacker and re-sent
Harm
- Users have been spending multiple times
- User logon State stolen
- Multiple draw
Defense
- Encryption (HTTPS)
- Time stamp
- Token (session)
- Nonce
- Signature
Web Security Concepts