Xxlegend · 2015/10/18 15:08
0x01 Overview of REST APIS
REST, which stands for REpresentational State Transfer, represents REpresentational stateless Transfer that requires no session, so authentication information must accompany every request. Rest is based on the HTTP protocol and is stateless. It is just an architectural approach, so its security features need to be implemented by ourselves, there is no ready-made. You are advised to send all requests through HTTPS. At the heart of the RESTful Web services concept is “resources.” Resources can be represented by URIs. Clients send requests to these URIs using methods defined by the HTTP protocol, which of course may cause the state of the accessed “resource” to change. The mapping between HTTP requests is as follows:
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = HTTP method behavior sample = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = GET access to resources information http://xx.com/api/orders GET access to a particular resource information http://xx.com/api/orders/123 POST to create a new resource http://xx.com/api/orders PUT update http://xx.com/api/orders/123 DELETE DELETE resources http://xx.com/api/orders/123 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =Copy the code
The requested data is usually expressed in JSON or XML. Json is recommended.
0x02 Identity Authentication
There are many types of authentication, including HTTP Basic, HTTP Digest, API KEY, Oauth, AND JWK. The following are brief explanations:
2.1 HTTP Basic
REST is stateless transmission, so every request has to bring identity authentication information, identity authentication methods, there are many ways of identity authentication, the first is HTTP Basic, this way in the client requirements simple, in the server is also very simple, just configure apache and other Web servers can be realized. So it’s pretty convenient for a simple service. However, this approach is less secure and simply encodes the user name and password base64 into the header.
Base64 before encoding: Basic admin:admin After encoding: Basic YWRtaW46YWRtaW4= Add it to the Header: Authorization: Basic YWRtaW46YWRtaW4=Copy the code
Because it is simple Base64 encoded storage, it is important to remember that SSL must be used in this way, or you will run naked.
In some products, it is also based on this similar way, but instead of using Apache basic mechanism, it writes its own authentication framework. The principle is the same: Base64 decodes the Authorization field in a request, and then verifies with the authentication information. Obviously, there are problems with this method. Authentication messages are transmitted in clear text and there is no anti-brute force.
2.2 API KEY
After user authentication, the server assigns an API Key to the client, similar to http://example.com/api?key=dfkaj134. The general processing process is as follows:
A simple design example is as follows:
The client side:
Server side:
The client registers with the server, and the server sends the response api_key and security_key to the client. Then, the client uses the HMACSHA256 algorithm to obtain a hash value sign based on api_key,secrity_key,timestrap, and rest_URI, and sends the URL to the server.
After receiving the request, the server first verifies whether the API_key exists. If it does, the server obtains the security_key of the API_key. Then it verifies whether timestrap exceeds the time limit, depending on the system, which prevents some replay attacks. The rest_API on the way is obtained from the URL as /rest/v1/interface/eth0. Finally, the value of sign is calculated and verified with the value of sign in the URL. This design prevents data from being tampered with.
The API Key is designed in such a way that it’s time-stamped to prevent partial replay, it’s validated to prevent data from being tampered with, and it also avoids the transfer of user names and passwords, which of course has some overhead.
2.3 OAUTH1.0A or Oauth2
OAuth protocol is applicable to the situation that external applications are authorized to access the resources of this site. The encryption mechanism is more secure than HTTP Digest authentication. Both use and configuration are complicated, so we won’t cover them here.
2.4 JWT
JWT is a JSON Web Token used to send things that can be digitally signed and authenticated. It contains a compact, URL-safe JSON object that the server can parse to verify security checks such as permission to operate, expiration, and so on. Due to its compact characteristics, it can be placed in THE URL or HTTP Authorization header. The specific algorithm is shown in the following figure
0 x03 authorization
After authentication comes authorization, granting different access rights according to different identities. For example, the admin user, common user, and auditor user have different identities. A simple example:
#! php $roles = array( 'ADMIN'=>array( 'permit'=>array('/^((\/system\/(clouds|device)$/'), What URL / / allow access to regular expressions' deny '= > array (' / ^ (\ system \ / audit) $/') / / what URL blocking access to regular expressions), 'AUDIT' = > array (' permit '= > array (' / ^ (\ system \ / AUDIT) $/'), / / allow access to the URL of the regular expression 'deny'=>array('/^((\/system\/(clouds|device).*)$/') ) );Copy the code
The above is the processing of vertical permissions. If parallel permissions are encountered, for example, user A obtains user B’s identity information or changes other user information, it is necessary to add judgment on the user for these sensitive data interfaces, which is generally implemented in specific logical implementation.
0 x04 URL filtering
Before entering the logical processing, add the URL parameter filtering, such as /site/{num}/policy limit num position to integer, if not a parameter directly return invalid parameters, set a URL list, not in the URL list directly reject requests, so as to prevent the development of API leakage. GET,POST,PUT, and DELETE are commonly used in REST APIS. Unimplemented methods are not allowed to be returned directly. Data in THE POST and PUT methods are in JSON format and checked before entering the logic.
0x05 Major Functions Encrypted Transmission
In the first step, you are advised to use SSL to encrypt the transmission of important functions in the system, such as certificates, some data, backup of configurations, and ensure that you have the appropriate permissions. This step is covered in authorization.
0x06 Rate Limit
The request rate limit is based on the api_key or the user to determine the number of requests in a certain period of time. The data is updated to the in-memory database (redis, memcached) until the maximum number of requests from the user is reached. In this way, the in-memory database key will expire automatically at a certain time. APC is available in PHP. Alternative PHP Cache (APC) is an open free PHP Opcode Cache. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code. Set x-rate-limit-reset on return: the number of seconds remaining in the current period. Example code for APC is as follows:
#!php
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');
}
});
Copy the code
0x07 Error handling
Illegal requests that cause system errors are recorded. Some important operations, such as login and registration, are displayed through the log interface. There is a unified error interface. For 400 series and 500 series errors, there are corresponding error codes and related messages, such as 401: Unauthorized; 403: The user has been authenticated, but has no corresponding permission. {“result”:”Invalid URL!” }, error request parameters {“result”:”json format error”}, invalid methods: {“result”:”Method Not Allowed”}, invalid parameters, etc. All the above are single-state codes, and there are multi-state codes, indicating partial success, some characters are illegal, etc. The following is an example:
HTTP/1.1 207 Multi-Status Content-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" }] }] },Copy the code
0x08 Major ID Opaque processing
In some sensitive functions of the system, for example, /user/1123 can obtain user information with ID =1123. In order to prevent dictionary traversal attacks, the ID can be processed with URL62 or UUID. In this way, the ID is unique and character safe.
0x09 Other Precautions
(1) Request data, data in POST and DELETE methods are in JSON format, of course, not to say that REST architecture does not support XML, XML is too difficult to parse, JSON is enough for most applications, the recent trend is also json is becoming more popular. The JSON format also does not have some of the security issues of XML, such as XXE. Using the JSON format currently prevents automatic scanning by the scanner.
(2) Uniform encoding format and return Type of returned data, such as Content-Type: application/json; charset=”UTF-8″
(3) in the logical implementation, after json decoding, parameter verification or escape operation, the first step of JSON format verification, the second step of specific parameter verification can basically prevent most of the injection problems.
(4) During transmission, SSL is used to ensure transmission security.
(5) Storage security, important information encrypted storage, such as authentication information hash storage.
In short, use SSL whenever possible.