Restful api security design guide

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

Restful api security design guide

The full name of REST is REpresentational State Transfer, which indicates stateless transmission without session. Therefore, each request must carry authentication information. Rest is based on http and stateless. It is only an architectural method, so its security features must be implemented by ourselves and there is no ready-made architecture. We recommend that all requests be sent over https. The core concept of RESTful web services is "resources ". Resources can be represented by Uris. The client uses the methods defined in the HTTP protocol to send requests to these URIs. Of course, these accessed "Resources" may change their status. The HTTP request correspondence is as follows:
========================================================== ====================
HTTP Method behavior example
========================================================== ====================
GET gets information http://xx.com/api/orders for the resource
GET gets information http://xx.com/api/orders/123 for a particular resource
POST create new resource http://xx.com/api/orders
PUT update resource http://xx.com/api/orders/123
DELETE resource http://xx.com/api/orders/123
========================================================== ====================

The request data is generally expressed in json or xml format. json is recommended.

0x02 Identity Authentication

There are many identity authentication methods, including HTTP Basic, HTTP Digest, api key, Oauth, and JWK:

2.1 HTTP Basic

REST is stateless transmission, so each request must carry the identity authentication information. There are many identity authentication methods. The first method is http basic, this method is simple on the client and simple on the server. You only need to configure apache and other web servers, so it is quite convenient for simple services. However, this method is less secure, that is, simply put the username and password base64 encoding into the header.

Before base64 encoding: Basic admin: admin

Base64 encoded: Basic YWRtaW46YWRtaW4 =

Put it in the Header: Authorization: Basic YWRtaW46YWRtaW4 =

Because it is a simple base64 encoded storage, remember to pay attention to the use of ssl in this way, otherwise it will be streaking.

Some products are also based on this similar method. They do not use the basic mechanism of apache, but write their own authentication framework. The principle is the same. In a request, base64 decodes the Authorization field, verify the authentication information. Obviously there is a problem with this method. authentication information is equivalent to plain text transmission, and there is no brute force cracking protection function.

2.2 API KEY

The API Key is the user identity authentication after the service end to the client to allocate an API Key, similar to: http://example.com/api? Key = dfkaj134. The general process is as follows:

A simple design example is as follows:

Client:


Server:


The client registers with the server. The server sends the response api_key and security_key to the client. do not disclose the information when saving the file. Then, the client obtains a hash value sign based on the api_key, secrity_key, timestamps, and rest_uri algorithms, the url in the construction process is sent to the server.

After receiving the request, the server first verifies whether api_key exists and obtains the security_key of the api_key if it exists. Then, it verifies whether the timestamps exceed the time limit, which can be determined by the system, in this way, some replay attacks are prevented. The rest_api on the way obtains/rest/v1/interface/eth0 from the url, and finally calculates the sign value, verify the signature value with the sign value in the url. This design prevents data tampering.

Using this API Key design method, a timestamp is added to prevent partial replay, verification is added, data tampering is prevented, and user names and passwords are transmitted, of course, there will also be some overhead.

2.3 Oauth1.0a or oau22.

The OAuth Protocol is applicable to authorizing external applications to access resources on this site. The encryption mechanism is more secure than HTTP Digest identity authentication. The usage and configuration are both complex and will not be involved here.

2.4 JWT

JWT is a JSON Web Token used to send things that can pass digital signatures and authentication. It contains a compact, URL-safe JSON object, the server can resolve this value to verify whether it has operation permissions, validity, and other security checks. Because of its compact nature, it can be placed in the url or HTTP Authorization header. The specific algorithm is as follows:


0x03 authorization

After identity authentication, authorization is performed. Different access permissions are granted based on different identities. For example, admin users, common users, and auditor users all have different identities. Simple Example:

$ Roles = array ('admin' => array ('permit '=> array ('/^ (\/system \/(clouds | device) $ /'), // which URLs are allowed to access? The regular expression 'deny' => array ('/^ (\/system \/audit) $ /') // which URLs are prohibited from accessing the regular expressions), 'audit' => array ('permit '=> array ('/^ (\/system \/AUDIT) $/'), // The URL Regular Expression 'deny' => array ('/^ (\/system \/(clouds | device ). *) $ /')));
This is the processing of vertical permissions. If A parallel permission problem occurs, such as user A Obtaining user B's identity information or changing other user information, sensitive data interfaces must be judged by users. This step is generally implemented in specific logic implementation.

0x04 URL filtering

Before entering the logic processing, add URL parameter filtering, such as/site/{num}/policy to specify the num position as an integer. If it is not a parameter, an invalid parameter is directly returned, set a url list and reject requests that are not included in the url list. This prevents api leakage during development. Rest api interfaces generally use GET, POST, PUT, DELETE, and unimplemented methods, but direct return methods are not allowed. For POST and PUT methods, data is in json format, verify json before entering the logic. Invalid json format error is returned.

0x05 important functions encrypted transmission

In the first step, we recommend that you use SSL encrypted transmission and Encrypt transmission of important functions in the system, such as certificates, some data, and configured backup functions. At the same time, you must ensure that you have the relevant permissions, this step will be involved in authorization.

0x06 Speed Limit

Request rate limit: you can determine the number of requests for a certain period of time based on api_key or user, and update the data to the memory database (redis, memcached ), when the maximum number is reached, the user's request is not accepted, and the memory database key can be used to automatically expire at a specific time. APC can be used in php. Alternative PHP Cache (APC) is an open and free PHP opcode Cache. It aims to provide a free, open, and sound framework for caching and optimizing PHP intermediate code. Set X-Rate-Limit-Reset when returning: the number of seconds remaining in the current time period. The sample code of APC is as follows:

Route::filter('api.limit', function(){$key = sprintf('api:%s', Auth::user()->api_key);// Create the key if it doesn't existCache::add($key, 0, 60);// Increment by 1$count = Cache::increment($key);// Fail if hourly requests exceededif ($count > Config::get('api.requests_per_hour')){App::abort(403, 'Hourly request limit exceeded');}});

0x07 error handling

All requests that are illegal and cause system errors are recorded, and some important operations, such as logon and registration, are displayed through the log interface output. There is a unified error interface. for errors in the 400 series and 500 series, there are corresponding error codes and related message prompts, such as 401: unauthorized; 403: authenticated, however, you do not have the required permissions. If you do not know the url: {"result": "Invalid URL! "}, Invalid request parameter {" result ":" json format error "}, unsupported Method: {" result ":" Method Not Allowed "}, invalid parameter, etc. All of the above are single status codes, and there are multiple status codes, indicating that part of the code is successful and some characters are invalid. Example:
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": 200,             "MULTI_RESULT": "created successfully"        },{             "IP": "192.167.1.1",             "MASK": "255.255.0.0","MULTI_STATUS": 409,             "MULTI_RESULT": "invalid parameter"}]}]},

0x08 important ID opacity Processing

Some sensitive functions of the system, such as/user/1123, can obtain information of users with id = 1123. To prevent dictionary traversal attacks, you can perform url62 or uuid processing on the id, the id to be processed in this way is unique and character-safe.

0x09 Other considerations

(1) Request data. For POST and DELETE methods, the data adopts json format. Of course, it does not mean that the rest architecture does not support xml. Because xml is too bad to parse, json is sufficient for most applications, recently, json is becoming more and more popular, and the json format does not have xml security problems, such as xxe. Currently, the scanner can automatically scan data in json format.

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

(3) In logic implementation, parameter verification or escape operations are performed after json decoding. The first step is json format verification, and the second step is specific parameter verification, which can basically prevent most injection problems.

(4) SSL is used during transmission to ensure transmission security.

(5) secure storage, encrypted storage of important information, such as hash Storage of authentication information.

In short, try to use SSL.

Related Article

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.