The application security strategy based on the HTTP protocol communication

Source: Internet
Author: User

To make a statement, I have not done any business app, the following ideas are just a little bit of personal time thinking, if you are a professional, the liberal enlighten.


Overview

During the development process, the APIs that are provided by the server are used, which are all based on the HTTP protocol, why does our own app server not use this method?

The most intuitive benefit of this approach is that when the API is designed well enough, the server only needs to be developed once, regardless of the front end is Web,app, APK ... Both request data and respond through the HTTP call API.

This approach is similar to the development of the traditional C/S model, where the server/client defines the same sequence of data structures (called communication protocols), the difference being that the HTTP protocol is now used, and the data type is changed from the previous binary stream to the text (Xml/json) format.

This article mainly introduces the development process and security thinking in this mode.


Logon process

HTTP-based Apps encounter server stateless issues, such as client-initiated API calls: GetUserInfo, how does the server determine who the user is?

The first thing that comes to mind is that every API call takes a user's username and password, which is a really stupid method.

Here is the idea is: The server saves a lot of boxes with locks, the box stores the user information, the user after the successful login, to obtain a key, the subsequent user requests only need to provide this key, the simple process is as follows:

1, User provides user name and password to send login request

2. The server checks whether the user name and password are correct, and the error fails directly. If checked, an access token is generated, the user information is placed in the box corresponding to the access token, and the access token is returned to the user.

3, the user to the server to obtain the user order information request, and with the access token obtained from the server.

4. The server opens the box with an access token, obtains the basic information of the user, and then detects the user's order information from the database and returns the user.

5, after the user and server interactive repeat 3, 4 steps

This mainly refers to the public number practice: Public Number: access to user information

Public number to get information about a concern, the condition is accesstoken and the ID of the followers (OpenID). Does not provide the public information, but instead uses a Accesstoken (access token), which means that the server holds a < access token, public Information > list, through Accesstoken can obtain a public number related information.

And how did this accesstoken get it? Public number: Get Accesstoken


Public number to get a accsstoken need to provide a public ID (AppID) and a password (Secret), which is not equivalent to providing a user name and password to get Accesstoken (access token)?


the security of the communication process

From the introduction above, each time the user sends an HTTP request, a typical interaction is as follows: Take the JSON data format as an example

Request:

{    "Command": "Getorderlist",    "Accesstoken": "3bf63b28-bdd2-4bb1-80b0-8d5b42070222"}

Response:

{"Success": true, "orderlist": [{"NO": "20150327131072", "Ordertime": "2015-03-27 09                        : 33:20 "," TotalCost ": 118," Detail ": [{" Product ": { "GUID": "4bb603b2-0916-412d-ae51-b296c838673b", "Name": "Vegetable pot Stall", " Mainpicture ":" 5 (8).                JPG "}," Count ": 1," Price ": 28},                        {"GUID": "630e38dd-60ae-4ed0-98f0-affea23c5fee", "Product": { "GUID": "da9dce4a-101e-45dc-a88e-3b5e296ca092", "Name": "Fragrant pot Trotters", "mainpictu Re ":" 2 (1).                JPG "}," Count ": 1," Price ": 58},               {"GUID": "6018c248-64e2-4185-98db-c1408aa0d482", "Product": {         "GUID": "A405B104-F0EB-488C-AC41-A8A3DE2F0BCA", "Name": "Farmhouse crisp broth", "M Ainpicture ":" 7 (10).        JPG "}," Count ": 1," Price ": 32}] }, {"NO": "20150325131079", "Ordertime": "2015-03-25 17:38:15", "TotalCost": "Status": 2, "Detail": [{"GUID": "77df4888-8c88-4c51-b669-74                        71a8ae975b "," Product ": {" GUID ":" da9dce4a-101e-45dc-a88e-3b5e296ca092 ", "Name": "Fragrant pot Trotters", "Mainpicture": "2 (1).        JPG "}," Count ": 1," Price ": 58}] }    ]}
You can see that the user obtains his own order, provides an access token, returns the user's order, and shows the effect here.


From the above communication process can be seen, are transmitted by the plaintext in the network, and the user orders so sensitive data, it is inappropriate. Once in transit, this access token is intercepted, the consequences are unimaginable, that is, we have to find ways to ensure the security of the transmission process.

At the thought of security in transit, we thought about HTTPS and encrypted all the data transmitted. HTTPS can undoubtedly solve this problem, it is designed to ensure the security of the transmission process.

is HTTPS the best solution when we don't need to do the same level of security as the bank? I don't think so, you can look down and then provide a way of thinking.

Refer to QQ Mailbox practices: QQ Mailbox Landing Page

Login Page


Login successful after the page (this is my QQ mailbox, welcome letter)



Notice that the landing page using HTTPS, after successful adoption of the ordinary HTTP protocol! That's the way!

Our idea, the user login API needs HTTPS, get to the symmetric encryption Key (key), after the data communication both sides use this key for symmetric encryption (AES), the communication process only need to outsource a decryption shell in the way before, the process is as follows:

1, the user provides a user name and password, through the initiation of HTTPS login request

2, the server verifies that the login information is correct. If it fails, it returns an error, and if passed, generates a Accesstoken (access token) that opens the User information box and a symmetric key (key) behind the data, storing the Accesstoken,key and user information in the box, with the data of the box Accesstoken the Index

3. The user invokes the API via HTTP, but the JSON data needs to be symmetric encrypted with Key

4. The server decrypts the data, executes the user request, and then encrypts the data with key, and returns it.

5, after the communication repeat 3, 4

This gives the web-side test code (CRYPTOJS implementation), the service side (C # Implementation) source. AES Plus decryption here in addition to key, the additional need to provide IV

Service-Side implementation

Using system;using system.io;using system.collections.generic;using system.linq;using System.Text;using System.threading.tasks;using system.security.cryptography;namespace cryption{public class DoAES {private St        atic int _keysize = 128;        private static Ciphermode _ciphermodel = CIPHERMODE.CBC;        private static Paddingmode _paddingmodel = Paddingmode.zeros; public static string Encrypt (String strencrypt, String strkey, String striv) {if (string. IsNullOrEmpty (strencrypt) | | String. IsNullOrEmpty (strkey) | | String. IsNullOrEmpty (Striv)) return string.            Empty;                try {byte[] Keyarray = UTF8Encoding.UTF8.GetBytes (strkey);                byte[] Ivarray = UTF8Encoding.UTF8.GetBytes (Striv);                byte[] Toencryptarray = UTF8Encoding.UTF8.GetBytes (Strencrypt);                RijndaelManaged Rdel = new RijndaelManaged ();                Rdel.keysize = _keysize;           Rdel.key = Keyarray;     RDEL.IV = Ivarray;                Rdel.mode = _ciphermodel;                rdel.padding = _paddingmodel;                ICryptoTransform ctransform = Rdel.createencryptor ();                byte[] Resultarray = Ctransform.transformfinalblock (toencryptarray, 0, toencryptarray.length);            Return convert.tobase64string (resultarray, 0, resultarray.length); } catch (Exception) {return string.            Empty; }} public static string Decrypt (String strdecrypt, String strkey, String striv) {if (str Ing. IsNullOrEmpty (strdecrypt) | | String. IsNullOrEmpty (strkey) | | String. IsNullOrEmpty (Striv)) return string.            Empty;                try {byte[] Keyarray = UTF8Encoding.UTF8.GetBytes (strkey);                byte[] Ivarray = UTF8Encoding.UTF8.GetBytes (Striv);                byte[] Toencryptarray = convert.frombase64string (Strdecrypt); RijndaelManaged Rdel = new RijndaeLmanaged ();                Rdel.keysize = _keysize;                Rdel.key = Keyarray;                RDEL.IV = Ivarray;                Rdel.mode = _ciphermodel;                rdel.padding = _paddingmodel;                ICryptoTransform ctransform = Rdel.createdecryptor ();                byte[] Resultarray = Ctransform.transformfinalblock (toencryptarray, 0, toencryptarray.length);                int nIndex = resultarray.length-1;                for (; nIndex >= 0; nindex--) if (resultarray[nindex]! = ' + ') break;            Return UTF8Encoding.UTF8.GetString (resultarray, 0, NIndex + 1); } catch (Exception) {return string.            Empty; }        }    }}

JS End Implementation

<! DOCTYPE html>
   

A logical omission.

As described above, a typical request process is as follows:

Requesturl:http://aa.com.cn/orders

Carrying {"Key": "3bf63b28-bdd2-4bb1-80b0-8d5b42070222"} data after AES encryption

The question is: after the server receives the request, it should use which box key (key) to decrypt it? The server does not have any basis for judgment.

Here is a thought, each request in the URL with token:http://aa.com.cn/orders? accesstoken= 3bf63b28-bdd2-4bb1-80b0-8d5b42070222, the server through the Accesstoken Index to the box and open, take out the user information and encryption key


New issues introduced: URL security

To avoid a logical omission, a new problem has been introduced unknowingly: when requesting a list of orders from the server, We only provide a url: http://aa.com.cn/orders during the request? Accesstoken= 3bf63b28-bdd2-4bb1-80b0-8d5b42070222

If the user this URL is compromised, does it mean that the data we return to the user has been exposed (although AES encryption), since the user did not exit the system , anyone can get to the data by requesting this URL!!!

The data currently in the user's hand is: Key,accesstoken, the person who intercepts the URL already knows Accesstoken, the only thing that does not know is Key.

Here I give the idea from the signature, how to use this interceptor does not know the key to protect the user's URL, mainly refer to the payment method of generating payment links , the general idea is:

1, the user adds timestamp to the URL and the random string parameter http://aa.com.cn/orders? accesstoken= 3bf63b28-bdd2-4bb1-80b0-8d5b42070222 & nonstr=kgekgekghe42g4ea2w & timestamp=145246512

2, the user to the URL of the parameters of the MD5/SH1 signature, the way is as follows: sign = MD5 (resource URL + accesstoken + nostr + Timestamp + Key), and then fill in the original URL to generate a true request URL

Parameter description:

Resource URL = http://aa.com.cn/orders

Accesstoken = 3bf63b28-bdd2-4bb1-80b0-8d5b42070222

nonstr =  kgekgekghe42g4ea2w

timestamp =  145246512

key = 12345678     (saved in the user's memory, generated by the server, sent back by HTTPS)

Calculate sign = MD5 (http://aa.com.cn/orders3bf63b28-bdd2-4bb1-80b0-8d5b42070222 kgekgekghe42g4ea2w14524651212345678) = Gehhgeiklajkidjkie3uit3u9uoidiguyiffjkk


3, the user initiates an HTTP request, URL = http://aa.com.cn/orders? accesstoken= 3bf63b28-bdd2-4bb1-80b0-8d5b42070222 & nonstr=kgekgekghe42g4ea2w & timestamp= 145246512 & Sign = Gehhgeiklajkidjkie3uit3u9uoidiguyiffjkk

4, the server verifies the timestamp of the URL: if the time stamp with the current system is too far, the decision request is not legal.

5, the server verification sign: Open the box through Accesstoken, remove Key, the same with MD5 signature, compared to the validity of the signed value, the rule of law to determine the request is not legal.

6, in response to user requests, return the data after AES encryption


above, I am the use of HTTP as a means of communication app development to ensure data security ideas, hope to play a role, welcome message discussion, questioning.


The application security strategy based on the HTTP protocol communication

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.