A, XSS

  • What is XSS? A cross site script attack is a code injection attack in which the attacker injects malicious code into the target website and executes the malicious code when the target logs in to the website. These scripts can obtain cookies,session tocken, Or other sensitive website information. The essence of an XSS attack is that the malicious code is unfiltered and mixed in with the normal code of the site, and the browser cannot recognize which scripts are trusted, causing the malicious script to be executed. Because it is executed on the user terminal, malicious code can directly obtain user information, and attackers use this information to pretend that users want to launch their own defined requests to the website
  • Attack types

    1, reflex type

    (1) Attack steps:

    A. The attacker constructs a special URL that contains malicious code

    B. When the user opens the URL with malicious code, the website server takes out the malicious code from the URL and splices it into HTML

    Is returned to the browser

    C. The browser parses and executes the response, and the malicious code is also executed

    D. Malicious code can steal user data and send it to the attacker’s website, or impersonate the user’s behavior and call the target

    Web site interface that performs attacker operations

    (2) Preventive measures

    A. Set the cookie to HtppOnly, so that the client cannot obtain the cookie information

    res.addHeader('Set-Cookie'."userid=XXX; path=/; HttpOnly")Copy the code

    B. Escape encodeURIComponent for URL query parameters and output them to the page

    app.get('/home', (req,res)=>{
      res.send(encodeURIComponent(req.query.type))
    })Copy the code

InnerHTML, outerHTML,appenChild, and other apis should be used carefully. Do not insert untrusted data into the page as HTML. A special data is constructed, the attacker, which contains malicious code, browsers, the malicious code c b, malicious code with users information sent to the attacker, or pretend to be the user behavior, calls the target web site interface Execute malicious operation (2), the preventive measure against the DOM XSS core is to escape the content of the input, Escape sensitive special character <>”‘

function encodeHtml(str) {
    return str.replace(/"/g, '" ') .replace(/'/g, '' ') .replace(//g, '> '); }Copy the code








(1) Attack steps: A. The attacker submits the malicious code to the database of the target website b. When the user opens the target website, the website server takes out the malicious code from the database and spells it in HTML for the viewer C. The user’s browser receives the user data and sends it to the attacker’s website, or impersonates the user. Call target site interface to perform malicious operations (2), preventive measures: to escape!! A. The front-end escapes special characters before submitting data to the server

B. The back end escapes special characters before storing them

C. The front end escapes special characters before retrieving data, stitching HTML, and rendering the page

  • Protection in addition to escape

    1. CSP: only resources in the same domain are allowed to be loaded: server set HTTP Content-security-policy, or set meta tag in front end, only resources in the same domain are allowed to be loaded. There are many configuration items

    <meta http-equiv="Content-Security-Policy" content="form-action 'self';">Copy the code

2, set the cookie to httpOnly, the client cannot use JS to obtain cookies

res.addHeader('Set-Cookie'."uid=xxx; path=/; HttpOnly")Copy the code

     

CSRF

  • CSRF is what? Cross-site-request-forgrey: Cross-site request forgery, in which an attacker induces users to enter malicious websites and send cross-site requests to the attacked websites by using the logged-in status of users. By using the victim’s registration certificate which has been obtained in the attacked website, the victim can be authenticated by the user in the background, so as to impersonate the user to perform malicious operations on the attacked website
  • The attacker induces the user to visit site B. 3. Site B sends A malicious request to site A, and the browser carries site A’s credentials by default, bypassing user authentication. 4.
  • Defense 1. Determine the source of the request: There is referer information in the header to determine whether the source is secure. 2. We then require that all user requests carry a Tocken that an attacker cannot obtain. The server separates the user from the CSRF attacker by verifying whether tocken is correct: a. Upon successful login, the server generates a TOCken and passes it to the user b. The user submits the request with the ToCken C. The server verifies whether toCken is correct
  • Third-party websites are not allowed to carry the sameSite cookie attribute, which may cause compatibility problems

HTTP protocol

Page input URL to page render, what happens?

  • User input http://www.baidu.com
  • The browser uses the DNS server to resolve urls into IP addresses
  • Setting up a TCP connection with an IP address is a three-way handshake and sending an HTTP request
  • After receiving the request, the server checks the database, reads the file, and returns an HTTP response
  • The browser parses HTML into dom
  • Parse the CSS to CSS-tree
  • Dom + CSS to generate render tree
  • Loading js files
  • Perform js

2. HTTP packet format

  • Request message format Method of line request: URL agreement/version number = > POST HTTP / 1.1 / form/save request header: accept: * / *, referer: localhost: 8080, connetction: Keep-alive blank request body: name=wky&age=18
  • Response packet Format Status line: Protocol/version status code Status Code Description Response header: Content-Type: text/ HTML; chartset=utf-8 Set-Cookie: name=XXX; path=/; HttpOnly access-control-allow-origin: localhost: 8080, access-control-allow-methods: GET,POST,DELETE,PUT, Access-Control-Max-Age: 8640, Access-Control-Allow-Headers: Cors-xss, cors-xss-test Blank line response body < HTML >…

GET and POST

  • Post is more secure than GET because get request parameters are exposed in the URL and are logged by the browser
  • Post can transfer more data via the Request Body
  • The URL has a length limit that affects get requests
  • Get requests can be cached by the browser, but POST can’t


  • 2XX Successful 200 OK: Indicates that the request sent from the client is processed correctly on the server
  • 3XX Redirection 301 Permanent Redirection 302 Temporary Redirection 304 Not modified The resource remains unchanged and is cached
  • 4XX client error 400 Bad Request, the request packet has a syntax error 401 403 Forbidden, The server denies the access to the resource request 404 Not found, the resource does not exist
  • 5XX server error 500 Initernal server error. An error occurs when the server is executing a request

Cors cross-domain configuration

  • Access-control-allow-origin: 192.168.1.110:8080 allows a domain to request resources. Set this parameter for simple requests and set the prerequest header for complex requests
  • Access-Control-Allow-Headers: XSS-TEST-1,XSS-TEST-2
  • Access-control-allow-method: allows certain method requests. By default, only GET and POST are allowed
  • Access-controll – max-age: 60*60*24, set this, prerequest will not send OPTION prerequest at this interval 3.2 Other Alternatives across domains
  • jsonp
  • webpack-dev-server

4. Browser cache

  • First load, HTTP request, sever normal return return header with strong cache description
  • 2, Cache-control: 3. Both of these headers are used by the back end to tell the browser how long the file will not expire. For example, if the file is requested again within 1h, the strong cache hits and the request is not sent. Use the file status code 200 from the memery cache
  • Negotiation cache 1. After an hour, the browser will not request the file directly, but will ask the backend whether the file has been modified, with if-modified-since: Date. The value is last-modify from the server header that requested the same resource last time. If the request header is received with if-modified-since, the request header is compared with the last modified time of the requested resource. If the request header is equal to the last modified time of the requested resource, the file is returned with the status code 304 not modified. Status code 200 OK 4. Etag has a higher priority. Etag is equivalent to a file fingerprint and is calculated based on the file index section, size, and last modification time. If the file contents remain unchanged, the fingerprint remains unchanged. The browser sends an if-none-match request header. After receiving the request, the server finds if-none-match in the request header and compares it with eTag to determine whether 200 or 304 is returned

Connection: What is keep-alive?

1. In early HTTP1.0, each HTTP request created a TCP connection, using a three-way handshake to create a TCP connection, a process that consumed resources and time. Add connection:keep-alive to the HTTP header. Do not close the connection when the response is complete. 2. Multiplexing is implemented in HTTP2.0, and all communication in the same domain is completed on a single connection

What are the new features of HTTP2.0

  • Connect: keep-alive: connect: keep-alive: connect: keep-alive If you want to concurrent multiple requests, you must use multiple TCP connections. To control resources, the browser limits TCP connection requests to a single domain name. Chrome limits TCP connection requests to six. In HTTP2.0, all communication is done on a single TCP connection in the same domain
  • Frame transfer: The smallest unit of message for HTTP2 data communication. Http2 transmits data in binary format, whereas HTTP1 uses text format, which is more efficient to parse
  • A server can actively push other resources while sending a page, rather than waiting for the browser to parse to the response location and initiate a request. For example, the server can actively push JS and CSS files to the client instead of waiting until the client parses the HTML to send the request
  • Header compression Http1 imposes an additional burden on the network by repeatedly carrying lengthy header information in request and response headers. In HTTP2.0, the same data is no longer sent with each request and response. Send only differential data to reduce header information

Why do you need HTTPS when you have HTTP

HTTPS is HTTP +SSL, a secure version of HTTP. HTTP data is transmitted in plaintext, so it is insecure to transmit sensitive information. HTTPS is born to solve HTTP insecurity

How to ensure HTTPS security

  • Symmetric encryption Both parties use the same secret key for encryption and decryption. This is called symmetric encryption.
  • Asymmetric encryption, public key + 1 private key = keys to 2, the data that is encrypted with the public key only the corresponding private key can decrypt, under the public key can be sent to the client, the private key is stored in the server, server 3 public key to the client, the issuance of the corresponding private key stored in the server 4 client USES the public key encryption and data to the server, the server using the corresponding private key for decryption
  • Middleman Problem: There is a middleman between the client and the server. The middleman replaces the public key sent by the server with his own public key, which can easily decrypt the client data. Solution: digital certificate to verify whether message digest has been tampered

4. User authentication

Common authentication modes are session, cookie, and Tocken

session/cookie

  • Principle 1. When the server receives the first access from the client, it generates a session on the server side, which records the user information and exposes the SID externally (signature: the SID is signed and encrypted using the secret key), for example, session={‘ XXXXXXX ‘:{userInfo: {}}}, usually stored in Redis. Res.setheader (‘ set-cookie ‘,’sid= XXXXXXX ‘); res.setheader (‘ set-cookie ‘,’sid= XXXXXXX ‘) The request header will carry the cookie information in this domain. 4. The server accepts the client’s request to resolve the SID, and then finds the corresponding session in Redis according to the SID to determine whether the request is legitimate

tocken

  • Principle 1. If the user logs in successfully, create a TOcken, which is encrypted with the JWT signature key and contains the user information. 2. The client receives the tocken, which is stored in localStorage, etc. 3. The server decodes through ToCken to obtain user information and realize authentication