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