REST API Security Design Guide

Source: Internet
Author: User
Tags apc compact http authorization header oauth representational state transfer

An introduction to the 0x01 rest API Rest is the full name of the representational state Transfer, which represents a representational stateless transport without a session, so each request has to have authentication information. Rest is based on HTTP protocol and is stateless. is just an architectural approach, so its security features need to be implemented on our own, there is no ready-made. It is recommended that all requests be sent over the HTTPS protocol. The core of RESTful Web Services Concepts is "resources". A resource can be represented by a URI. The client uses the methods defined by the HTTP protocol to send requests to these URIs, which of course may cause changes in the "resource" state of these accesses. The HTTP request correspondence relationship is as follows:
==========  =====================  ========================http method          Behavior                         example ==========  ========== ===========  ========================get         Get information about         a resource Http://xx.com/api/ordersGET         get information about a specific resource http. Xx.com/api/orders/123post        Create a new resource             Http://xx.com/api/ordersPUT         update the resource               http://xx.com/api/orders/ 123DELETE      Delete Resource               http://xx.com/api/orders/123==========  ====================== =================== ====

JSON is recommended for the requested data, which is generally expressed in JSON or XML format.

0X02 identity authentication contains many kinds, there are HTTP basic,http Digest,api key,oauth,jwk, and so on, the following simple explanation:

2.1 HTTP Basic

Rest because it is stateless transmission, so every request has to take the identity authentication information, authentication method, authentication method There are many kinds of, the first is HTTP basic, this way in the client requirements is simple, on the server implementation is very simple, Simply configure a Web server such as Apache can be implemented, so for simple service is very convenient. However, this approach is less secure and simply puts the username and password base64 into the header.

Base64 before: Basic ADMIN:ADMINBASE64 encoded: basic ywrtaw46ywrtaw4= placed in header: Authorization:basic ywrtaw46ywrtaw4=

It is because it is simple base64 encoded storage, remember to remember in this way must pay attention to the use of SSL, or it is bare-Ben.

In some products is also based on this similar way, but did not use the basic mechanism of Apache, but wrote the authentication framework itself, the principle is the same, in a request Base64 decoding authorization field, and authentication information to do the verification. Obviously there is a problem in this way, the authentication information is equivalent to the plaintext transmission, and there is no anti-brute force function.

2.2 API KEY

API key is the user authentication after the server to assign an API key to the client, similar to: http://example.com/api?key=dfkaj134 , the general process is as follows:

A simple design example is as follows:

Client side:

Server side:

Client side to the server to register, the server sends the response to the client Api_key and Security_key, note that the save does not leak, and then the clients according to Api_key,secrity_key,timestrap,rest_ URI uses the hmacsha256 algorithm to get a hash value sign, the URL of the construction route sent to the server.

After receiving the request, the server first verifies that the Api_key, exists, and then obtains the security_key of the Api_key, and then verifies that the timestrap exceeds the time limit, which can be determined by the system, thus preventing partial replay attacks, and rest_ on the way The API is obtained from the URL for/rest/v1/interface/eth0, and finally calculates the sign value, after the end and the URL of the sign value to do the check. This design prevents the data from being tampered with.

Through the design of this API key to prevent partial replay, add a check, prevent data tampering, while avoiding the transmission of usernames and passwords, of course, there will be some overhead.

2.3 oauth1.0a or Oauth2

The OAuth protocol is used to authorize access to resources on the site for external applications. The encryption mechanism is more secure than HTTP Digest identity authentication. The use and configuration are more complex and are not covered here.

2.4 JWT

JWT is a JSON Web Token that sends something digitally signed and authenticated, and contains a compact, URL-safe JSON object that the server can use to resolve the security checks for operational permissions and expiration. Because of its compact features, it can be placed in the URL or HTTP authorization header, the specific algorithm as

0X03 authorization after authentication is authorized, according to different identities, grant different access rights. such as admin users, ordinary users, auditor users are different identities. A simple example:
1 2 3 4 5 6 7 8 9 10 $roles = array( ‘ADMIN‘=>array( ‘permit‘=>array(‘/^((\/system\/(clouds|device)$/‘), // 允许访问哪些URL的正则表达式 ‘deny‘=>array(‘/^(\/system\/audit)$/‘) // 禁止访问哪些URL的正则表达式 ), ‘AUDIT‘=>array( ‘permit‘=>array(‘/^(\/system\/audit)$/‘),//允许访问的URL正则表达式 ‘deny‘=>array(‘/^((\/system\/(clouds|device).*)$/‘) ) );

The above is the processing of vertical permissions, if you encounter the problem of parallel permissions, such as User A to obtain User B's identity information or change other user information, for these sensitive data interfaces need to add to the user's judgment, this step is generally implemented in the specific logic implementation.

0x04 URL Filtering

Before entering the logical processing, add the parameters of the URL filter, such as the /site/{num}/policy qualification num position is an integer, etc., if not the parameters directly return illegal parameters, set a URL list, not not in the URL list of the request directly rejected, this can prevent the development of the API leak. The rest API interface generally uses GET,POST,PUT,DELETE, the non-implemented method is not allowed by the direct return method, the data for the Post,put method is in JSON format, and the JSON is validated before entering the logic, and the JSON format error is not returned illegally.

0X05 important functions encrypted transmission

The first step is to recommend the SSL encryption transmission, but also for the important functions of the system to do encrypted transmission, such as certificates, some data, configuration of the backup function, but also to ensure that the appropriate permissions, this step will be covered in the authorization.

0X06 Rate Limit

Request rate limit, according to Api_key or the user to determine the number of times the request, update the data to the in-memory database (redis,memcached), the maximum number is not accept the user's request, and this can also take advantage of the memory database key at a specific time automatically expire characteristics. In PHP you can use apc,alternative PHP cache (APC) as an open and free php opcode cache. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP's intermediate code. Set X-rate-limit-reset on return: The number of seconds remaining in the current time period, APC sample code is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 Route::filter(‘api.limit‘, function() { $key = sprintf(‘api:%s‘, Auth::user()->api_key); // Create the key if it doesn‘t exist Cache::add($key, 0, 60); // Increment by 1 $count = Cache::increment($key); // Fail if hourly requests exceeded if ($count > Config::get(‘api.requests_per_hour‘)) { App::abort(403, ‘Hourly request limit exceeded‘); } });
0x07 error handling for illegal, causing system errors and other requests are recorded, some important operations, such as login, registration and so on through the log interface output display. There is a unified error interface, for 400 series and 500 series of errors have corresponding error codes and related message prompts, such as 401: Unauthorized, 403: has been authenticated, but no corresponding permissions. If the URL is not recognized: {"result":"InvalidUrl! "}, Bad Request parameter {"result":"json format error"}, Disallowed methods: {"result":"Method Not Allowed"}, illegal parameters and so on. All of the above is a single status code, but also a multi-state code, indicating partial success, some of the characters are illegal. Examples are as follows:
http/1.1 207 Multi-statuscontent-type:application/json; charset= "UTF-8" content-length:xxxx    {"Opt_status": 207 "DATA": {    "ip_address": [{        "INTERFACE": "Eth0",        "Ip_list": [{             "IP": "192.168.1.1",             "MASK": "255.255.0.0", "Multi_status": $,             "Multi_result": " Created successfully "        },{             " IP ":" 192.167.1.1 ",             " MASK ":" 255.255.0.0 "," multi_status ": 409,             " multi_ RESULT ":" Invalid Parameter "}]}]},
0x08 Important ID Opaque processing in the system some sensitive functions, such as/user/1123 can obtain id=1123 user information, in order to prevent the dictionary traversal attack, ID can be url62 or UUID processing, so that the ID is unique, and the character is safe. 0x09 Other considerations (1) Request data, for the data in the Post,delete method in JSON format, of course, not to say that the rest schema does not support XML, because XML is too bad parsing, for most of the application JSON is enough, the recent trend is more and more popular JSON , and the JSON format does not have some security issues with XML, such as XXe. Using the JSON format now prevents the scanner from scanning automatically.

(2) Return data uniform encoding format, unified return type, such as Content-type:application/json; charset= "UTF-8"

(3) In the logic implementation, the JSON decoding after the parameter validation or escape operation, the first step JSON format verification, the second step of the specific parameter verification can basically prevent most of the injection problem.

(4) in the transmission process, the use of SSL to ensure the security of transmission.

(5) Storage security, important information encryption storage, such as authentication information hash save.

In short, use SSL as much as possible.

REFER:
http://blog.nsfocus.net/rest-api-design-safety/
http://drops.wooyun.org/web/9737

REST API Security Design Guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.