web_socket_auth.c
Go to the documentation of this file.
1 /**
2  * @file web_socket_auth.c
3  * @brief HTTP authentication for WebSockets
4  *
5  * @section License
6  *
7  * Copyright (C) 2010-2018 Oryx Embedded SARL. All rights reserved.
8  *
9  * This file is part of CycloneTCP Open.
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24  *
25  * @author Oryx Embedded SARL (www.oryx-embedded.com)
26  * @version 1.9.0
27  **/
28 
29 //Switch to the appropriate trace level
30 #define TRACE_LEVEL WEB_SOCKET_TRACE_LEVEL
31 
32 //Dependencies
33 #include <stdlib.h>
34 #include "core/net.h"
35 #include "web_socket/web_socket.h"
37 #include "encoding/base64.h"
38 #include "hash/md5.h"
39 #include "str.h"
40 #include "debug.h"
41 
42 //Check TCP/IP stack configuration
43 #if (WEB_SOCKET_SUPPORT == ENABLED)
44 
45 
46 /**
47  * @brief Parse WWW-Authenticate header field
48  * @param[in] webSocket Handle to a WebSocket
49  * @param[in] value NULL-terminated string that contains the value of header field
50  * @return Error code
51  **/
52 
54 {
55 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED || WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
56  size_t n;
57  char_t *p;
58  char_t *token;
59  char_t *separator;
60  char_t *name;
61  WebSocketAuthContext *authContext;
62 
63  //Point to the handshake context
64  authContext = &webSocket->authContext;
65 
66  //Retrieve the authentication scheme
67  token = strtok_r(value, " \t", &p);
68 
69  //Any parsing error?
70  if(token == NULL)
71  return ERROR_INVALID_SYNTAX;
72 
73  //Basic access authentication?
74  if(!strcmp(token, "Basic"))
75  {
76  //Basic authentication is required by the WebSocket server
77  authContext->requiredAuthMode = WS_AUTH_MODE_BASIC;
78  }
79  //Digest access authentication?
80  else if(!strcasecmp(token, "Digest"))
81  {
82  //Digest authentication is required by the WebSocket server
84  }
85  //Unknown authentication scheme?
86  else
87  {
88  //Report an error
89  return ERROR_INVALID_SYNTAX;
90  }
91 
92  //Get the first parameter
93  token = strtok_r(NULL, ",", &p);
94 
95  //Parse the WWW-Authenticate field
96  while(token != NULL)
97  {
98  //Check whether a separator is present
99  separator = strchr(token, '=');
100 
101  //Separator found?
102  if(separator != NULL)
103  {
104  //Split the string
105  *separator = '\0';
106 
107  //Get field name and value
109  value = strTrimWhitespace(separator + 1);
110 
111  //Retrieve the length of the value field
112  n = strlen(value);
113 
114  //Discard the surrounding quotes
115  if(n > 0 && value[n - 1] == '\"')
116  value[n - 1] = '\0';
117  if(value[0] == '\"')
118  value++;
119 
120  //Check parameter name
121  if(!strcasecmp(name, "realm"))
122  {
123  //Save realm
125  }
126 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
127  else if(!strcasecmp(name, "nonce"))
128  {
129  //Save nonce
130  strSafeCopy(authContext->nonce, value, WEB_SOCKET_NONCE_MAX_LEN + 1);
131  }
132  else if(!strcasecmp(name, "opaque"))
133  {
134  //Save nonce
136  }
137  else if(!strcasecmp(name, "stale"))
138  {
139  //Save stale flag
140  if(!strcasecmp(value, "true"))
141  authContext->stale = TRUE;
142  else
143  authContext->stale = FALSE;
144  }
145 #endif
146 
147  //Get next parameter
148  token = strtok_r(NULL, ",", &p);
149  }
150  }
151 #endif
152 
153  //Successful processing
154  return NO_ERROR;
155 }
156 
157 
158 /**
159  * @brief Format Authorization header field
160  * @param[in] webSocket Handle to a WebSocket
161  * @param[out] output Buffer where to format the header field
162  * @return Total length of the header field
163  **/
164 
166 {
167  size_t n;
168 
169 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED || WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
170  WebSocketAuthContext *authContext;
171 
172  //Point to the handshake context
173  authContext = &webSocket->authContext;
174 #endif
175 
176 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED)
177  //Basic authentication scheme?
178  if(authContext->selectedAuthMode == WS_AUTH_MODE_BASIC)
179  {
180  size_t k;
181  char_t *temp;
182 
183  //Temporary buffer
184  temp = (char_t *) webSocket->rxContext.buffer;
185 
186  //Format Authorization header field
187  n = sprintf(output, "Authorization: Basic ");
188 
189  //The client sends the userid and password, separated by a single colon
190  //character, within a Base64 encoded string in the credentials
191  k = sprintf(temp, "%s:%s", authContext->username,
192  authContext->password);
193 
194  //Encode the resulting string using Base64
195  base64Encode(temp, k, output + n, &k);
196  //Update the total length of the header field
197  n += k;
198 
199  //Properly terminate the Authorization header field
200  n += sprintf(output + n, "\r\n");
201  }
202  else
203 #endif
204 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
205  //Digest authentication scheme?
206  if(authContext->selectedAuthMode == WS_AUTH_MODE_DIGEST)
207  {
208  Md5Context md5Context;
209  char_t ha1[2 * MD5_DIGEST_SIZE + 1];
210  char_t ha2[2 * MD5_DIGEST_SIZE + 1];
211  char_t nc[9];
212 
213  //Count of the number of requests (including the current request)
214  //that the client has sent with the nonce value in this request
215  authContext->nc++;
216 
217  //Convert the value to hex string
218  sprintf(nc, "%08x", authContext->nc);
219 
220  //Compute HA1 = MD5(username : realm : password)
221  md5Init(&md5Context);
222  md5Update(&md5Context, authContext->username, strlen(authContext->username));
223  md5Update(&md5Context, ":", 1);
224  md5Update(&md5Context, authContext->realm, strlen(authContext->realm));
225  md5Update(&md5Context, ":", 1);
226  md5Update(&md5Context, authContext->password, strlen(authContext->password));
227  md5Final(&md5Context, NULL);
228 
229  //Convert MD5 hash to hex string
231  //Debug message
232  TRACE_DEBUG(" HA1: %s\r\n", ha1);
233 
234  //Compute HA2 = MD5(method : uri)
235  md5Init(&md5Context);
236  md5Update(&md5Context, "GET", 3);
237  md5Update(&md5Context, ":", 1);
238  md5Update(&md5Context, webSocket->uri, strlen(webSocket->uri));
239  md5Final(&md5Context, NULL);
240 
241  //Convert MD5 hash to hex string
243  //Debug message
244  TRACE_DEBUG(" HA2: %s\r\n", ha2);
245 
246  //Compute MD5(HA1 : nonce : nc : cnonce : qop : HA1)
247  md5Init(&md5Context);
248  md5Update(&md5Context, ha1, strlen(ha1));
249  md5Update(&md5Context, ":", 1);
250  md5Update(&md5Context, authContext->nonce, strlen(authContext->nonce));
251  md5Update(&md5Context, ":", 1);
252  md5Update(&md5Context, nc, strlen(nc));
253  md5Update(&md5Context, ":", 1);
254  md5Update(&md5Context, authContext->cnonce, strlen(authContext->cnonce));
255  md5Update(&md5Context, ":", 1);
256  md5Update(&md5Context, "auth", 4);
257  md5Update(&md5Context, ":", 1);
258  md5Update(&md5Context, ha2, strlen(ha2));
259  md5Final(&md5Context, NULL);
260 
261  //Convert MD5 hash to hex string
263  //Debug message
264  TRACE_DEBUG(" response: %s\r\n", ha1);
265 
266  //Format Authorization header field
267  n = sprintf(output, "Authorization: Digest\r\n");
268 
269  //Username
270  n += sprintf(output + n, " username=\"%s\",\r\n", authContext->username);
271  //Realm
272  n += sprintf(output + n, " realm=\"%s\",\r\n", authContext->realm);
273  //Nonce value
274  n += sprintf(output + n, " nonce=\"%s\",\r\n", authContext->nonce);
275  //URI
276  n += sprintf(output + n, " uri=\"%s\",\r\n", webSocket->uri);
277  //Quality of protection
278  n += sprintf(output + n, " qop=\"auth\",\r\n");
279  //Nonce count
280  n += sprintf(output + n, " nc=\"%08x\",\r\n", authContext->nc);
281  //Cnonce value
282  n += sprintf(output + n, " cnonce=\"%s\",\r\n", authContext->cnonce);
283  //Response
284  n += sprintf(output + n, " response=\"%s\",\r\n", ha1);
285  //Opaque parameter
286  n += sprintf(output + n, " opaque=\"%s\",\r\n", authContext->opaque);
287  }
288  else
289 #endif
290  //Unknown authentication scheme?
291  {
292  //No need to add the Authorization header field
293  n = 0;
294  }
295 
296  //Return the total length of the Authorization header field
297  return n;
298 }
299 
300 
301 /**
302  * @brief Convert byte array to hex string
303  * @param[in] input Point to the byte array
304  * @param[in] inputLen Length of the byte array
305  * @param[out] output NULL-terminated string resulting from the conversion
306  * @return Error code
307  **/
308 
309 void webSocketConvertArrayToHexString(const uint8_t *input,
310  size_t inputLen, char_t *output)
311 {
312  size_t i;
313 
314  //Hex conversion table
315  static const char_t hexDigit[] =
316  {
317  '0', '1', '2', '3', '4', '5', '6', '7',
318  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
319  };
320 
321  //Process byte array
322  for(i = 0; i < inputLen; i++)
323  {
324  //Convert upper nibble
325  output[i * 2] = hexDigit[(input[i] >> 4) & 0x0F];
326  //Then convert lower nibble
327  output[i * 2 + 1] = hexDigit[input[i] & 0x0F];
328  }
329 
330  //Properly terminate the string with a NULL character
331  output[i * 2] = '\0';
332 }
333 
334 #endif
char_t username[WEB_SOCKET_USERNAME_MAX_LEN+1]
Definition: web_socket.h:356
char char_t
Definition: compiler_port.h:41
char_t nonce[WEB_SOCKET_NONCE_MAX_LEN+1]
Definition: web_socket.h:361
error_t webSocketParseAuthenticateField(WebSocket *webSocket, char_t *value)
Parse WWW-Authenticate header field.
TCP/IP stack core.
WebSocketAuthMode selectedAuthMode
Definition: web_socket.h:355
Debugging facilities.
Authentication context.
Definition: web_socket.h:351
uint8_t p
Definition: ndp.h:295
#define WEB_SOCKET_REALM_MAX_LEN
Definition: web_socket.h:122
#define WebSocket
Definition: web_socket.h:175
String manipulation helper functions.
#define strtok_r(str, delim, p)
void base64Encode(const void *input, size_t inputLen, char_t *output, size_t *outputLen)
Base64 encoding algorithm.
Definition: base64.c:76
#define WEB_SOCKET_NONCE_MAX_LEN
Definition: web_socket.h:143
#define TRUE
Definition: os_port.h:48
#define strcasecmp
void md5Final(Md5Context *context, uint8_t *digest)
Finish the MD5 message digest.
Definition: md5.c:192
HTTP authentication for WebSockets.
size_t webSocketAddAuthorizationField(WebSocket *webSocket, char_t *output)
Format Authorization header field.
char_t name[]
uint8_t digest[16]
Definition: md5.h:59
char_t password[WEB_SOCKET_PASSWORD_MAX_LEN+1]
Definition: web_socket.h:357
char_t opaque[WEB_SOCKET_OPAQUE_MAX_LEN+1]
Definition: web_socket.h:363
MD5 algorithm context.
Definition: md5.h:54
WebSocketAuthMode requiredAuthMode
Definition: web_socket.h:354
char_t cnonce[WEB_SOCKET_CNONCE_SIZE *2+1]
Definition: web_socket.h:362
Success.
Definition: error.h:42
char_t realm[WEB_SOCKET_REALM_MAX_LEN+1]
Definition: web_socket.h:358
error_t
Error codes.
Definition: error.h:40
Base64 encoding scheme.
error_t strSafeCopy(char_t *dest, const char_t *src, size_t destSize)
Copy string.
Definition: str.c:157
uint8_t token[]
Definition: coap_common.h:181
uint8_t value[]
Definition: dtls_misc.h:141
char_t * strTrimWhitespace(char_t *s)
Removes all leading and trailing whitespace from a string.
Definition: str.c:68
void md5Init(Md5Context *context)
Initialize MD5 message digest context.
Definition: md5.c:131
#define MD5_DIGEST_SIZE
Definition: md5.h:38
#define WEB_SOCKET_OPAQUE_MAX_LEN
Definition: web_socket.h:150
uint8_t n
MD5 (Message-Digest Algorithm)
#define FALSE
Definition: os_port.h:44
void webSocketConvertArrayToHexString(const uint8_t *input, size_t inputLen, char_t *output)
Convert byte array to hex string.
#define TRACE_DEBUG(...)
Definition: debug.h:98
WebSocket API (client and server)
void md5Update(Md5Context *context, const void *data, size_t length)
Update the MD5 context with a portion of the message being hashed.
Definition: md5.c:153