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-2026 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 2.6.8
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 = osStrtok_r(value, " \t", &p);
70 
71  //Any parsing error?
72  if(token == NULL)
73  {
74  return ERROR_INVALID_SYNTAX;
75  }
76 
77  //Basic access authentication?
78  if(osStrcasecmp(token, "Basic") == 0)
79  {
80  //Basic authentication is required by the WebSocket server
81  authContext->requiredAuthMode = WS_AUTH_MODE_BASIC;
82  }
83  //Digest access authentication?
84  else if(osStrcasecmp(token, "Digest") == 0)
85  {
86  //Digest authentication is required by the WebSocket server
88  }
89  //Unknown authentication scheme?
90  else
91  {
92  //Report an error
93  return ERROR_INVALID_SYNTAX;
94  }
95 
96  //Get the first parameter
97  token = osStrtok_r(NULL, ",", &p);
98 
99  //Parse the WWW-Authenticate field
100  while(token != NULL)
101  {
102  //Check whether a separator is present
103  separator = osStrchr(token, '=');
104 
105  //Separator found?
106  if(separator != NULL)
107  {
108  //Split the string
109  *separator = '\0';
110 
111  //Get field name and value
113  value = strTrimWhitespace(separator + 1);
114 
115  //Retrieve the length of the value field
116  n = osStrlen(value);
117 
118  //Discard the surrounding quotes
119  if(n > 0 && value[n - 1] == '\"')
120  {
121  value[n - 1] = '\0';
122  }
123 
124  if(value[0] == '\"')
125  {
126  value++;
127  }
128 
129  //Check parameter name
130  if(osStrcasecmp(name, "realm") == 0)
131  {
132  //Save realm
133  strSafeCopy(authContext->realm, value, WEB_SOCKET_REALM_MAX_LEN + 1);
134  }
135 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
136  else if(osStrcasecmp(name, "nonce") == 0)
137  {
138  //Save nonce
139  strSafeCopy(authContext->nonce, value, WEB_SOCKET_NONCE_MAX_LEN + 1);
140  }
141  else if(osStrcasecmp(name, "opaque") == 0)
142  {
143  //Save nonce
145  }
146  else if(osStrcasecmp(name, "stale") == 0)
147  {
148  //Save stale flag
149  if(osStrcasecmp(value, "true") == 0)
150  {
151  authContext->stale = TRUE;
152  }
153  else
154  {
155  authContext->stale = FALSE;
156  }
157  }
158 #endif
159  }
160 
161  //Get next parameter
162  token = osStrtok_r(NULL, ",", &p);
163  }
164 #endif
165 
166  //Successful processing
167  return NO_ERROR;
168 }
169 
170 
171 /**
172  * @brief Format Authorization header field
173  * @param[in] webSocket Handle to a WebSocket
174  * @param[out] output Buffer where to format the header field
175  * @return Total length of the header field
176  **/
177 
179 {
180  size_t n;
181 
182 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED || WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
183  WebSocketAuthContext *authContext;
184 
185  //Point to the handshake context
186  authContext = &webSocket->authContext;
187 #endif
188 
189 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED)
190  //Basic authentication scheme?
191  if(authContext->selectedAuthMode == WS_AUTH_MODE_BASIC)
192  {
193  size_t k;
194  char_t *temp;
195 
196  //Temporary buffer
197  temp = (char_t *) webSocket->rxContext.buffer;
198 
199  //Format Authorization header field
200  n = osSprintf(output, "Authorization: Basic ");
201 
202  //The client sends the userid and password, separated by a single colon
203  //character, within a Base64-encoded string in the credentials
204  k = osSprintf(temp, "%s:%s", authContext->username,
205  authContext->password);
206 
207  //Encode the resulting string using Base64
208  base64Encode(temp, k, output + n, &k);
209  //Update the total length of the header field
210  n += k;
211 
212  //Properly terminate the Authorization header field
213  n += osSprintf(output + n, "\r\n");
214  }
215  else
216 #endif
217 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
218  //Digest authentication scheme?
219  if(authContext->selectedAuthMode == WS_AUTH_MODE_DIGEST)
220  {
221  Md5Context md5Context;
222  uint8_t digest[MD5_DIGEST_SIZE];
223  char_t ha1[2 * MD5_DIGEST_SIZE + 1];
224  char_t ha2[2 * MD5_DIGEST_SIZE + 1];
225  char_t nc[9];
226 
227  //Count of the number of requests (including the current request)
228  //that the client has sent with the nonce value in this request
229  authContext->nc++;
230 
231  //Convert the value to hex string
232  osSprintf(nc, "%08x", authContext->nc);
233 
234  //Compute HA1 = MD5(username : realm : password)
235  md5Init(&md5Context);
236  md5Update(&md5Context, authContext->username, osStrlen(authContext->username));
237  md5Update(&md5Context, ":", 1);
238  md5Update(&md5Context, authContext->realm, osStrlen(authContext->realm));
239  md5Update(&md5Context, ":", 1);
240  md5Update(&md5Context, authContext->password, osStrlen(authContext->password));
241  md5Final(&md5Context, digest);
242 
243  //Convert MD5 hash to hex string
245  //Debug message
246  TRACE_DEBUG(" HA1: %s\r\n", ha1);
247 
248  //Compute HA2 = MD5(method : uri)
249  md5Init(&md5Context);
250  md5Update(&md5Context, "GET", 3);
251  md5Update(&md5Context, ":", 1);
252  md5Update(&md5Context, webSocket->uri, osStrlen(webSocket->uri));
253  md5Final(&md5Context, digest);
254 
255  //Convert MD5 hash to hex string
257  //Debug message
258  TRACE_DEBUG(" HA2: %s\r\n", ha2);
259 
260  //Compute MD5(HA1 : nonce : nc : cnonce : qop : HA2)
261  md5Init(&md5Context);
262  md5Update(&md5Context, ha1, osStrlen(ha1));
263  md5Update(&md5Context, ":", 1);
264  md5Update(&md5Context, authContext->nonce, osStrlen(authContext->nonce));
265  md5Update(&md5Context, ":", 1);
266  md5Update(&md5Context, nc, osStrlen(nc));
267  md5Update(&md5Context, ":", 1);
268  md5Update(&md5Context, authContext->cnonce, osStrlen(authContext->cnonce));
269  md5Update(&md5Context, ":", 1);
270  md5Update(&md5Context, "auth", 4);
271  md5Update(&md5Context, ":", 1);
272  md5Update(&md5Context, ha2, osStrlen(ha2));
273  md5Final(&md5Context, digest);
274 
275  //Convert MD5 hash to hex string
277  //Debug message
278  TRACE_DEBUG(" response: %s\r\n", ha1);
279 
280  //Format Authorization header field
281  n = osSprintf(output, "Authorization: Digest ");
282 
283  //Username
284  n += osSprintf(output + n, "username=\"%s\", ", authContext->username);
285  //Realm
286  n += osSprintf(output + n, "realm=\"%s\", ", authContext->realm);
287  //Nonce value
288  n += osSprintf(output + n, "nonce=\"%s\", ", authContext->nonce);
289  //URI
290  n += osSprintf(output + n, "uri=\"%s\", ", webSocket->uri);
291  //Quality of protection
292  n += osSprintf(output + n, "qop=\"auth\", ");
293  //Nonce count
294  n += osSprintf(output + n, "nc=\"%08x\", ", authContext->nc);
295  //Cnonce value
296  n += osSprintf(output + n, "cnonce=\"%s\", ", authContext->cnonce);
297  //Response
298  n += osSprintf(output + n, "response=\"%s\", ", ha1);
299  //Opaque parameter
300  n += osSprintf(output + n, "opaque=\"%s\"\r\n", authContext->opaque);
301  }
302  else
303 #endif
304  //Unknown authentication scheme?
305  {
306  //No need to add the Authorization header field
307  n = 0;
308  }
309 
310  //Return the total length of the Authorization header field
311  return n;
312 }
313 
314 
315 /**
316  * @brief Convert byte array to hex string
317  * @param[in] input Point to the byte array
318  * @param[in] inputLen Length of the byte array
319  * @param[out] output NULL-terminated string resulting from the conversion
320  **/
321 
322 void webSocketConvertArrayToHexString(const uint8_t *input,
323  size_t inputLen, char_t *output)
324 {
325  size_t i;
326 
327  //Hex conversion table
328  static const char_t hexDigit[16] =
329  {
330  '0', '1', '2', '3', '4', '5', '6', '7',
331  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
332  };
333 
334  //Process byte array
335  for(i = 0; i < inputLen; i++)
336  {
337  //Convert upper nibble
338  output[i * 2] = hexDigit[(input[i] >> 4) & 0x0F];
339  //Then convert lower nibble
340  output[i * 2 + 1] = hexDigit[input[i] & 0x0F];
341  }
342 
343  //Properly terminate the string with a NULL character
344  output[i * 2] = '\0';
345 }
346 
347 #endif
char_t name[]
#define osStrchr(s, c)
Definition: os_port.h:201
String manipulation helper functions.
char_t password[WEB_SOCKET_PASSWORD_MAX_LEN+1]
Definition: web_socket.h:363
uint8_t p
Definition: ndp.h:300
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:142
void md5Final(Md5Context *context, uint8_t *digest)
Finish the MD5 message digest.
#define osStrlen(s)
Definition: os_port.h:171
@ WS_AUTH_MODE_BASIC
Definition: web_socket.h:215
WebSocketAuthMode selectedAuthMode
Definition: web_socket.h:361
void md5Init(Md5Context *context)
Initialize MD5 message digest context.
#define FALSE
Definition: os_port.h:46
char_t opaque[WEB_SOCKET_OPAQUE_MAX_LEN+1]
Definition: web_socket.h:369
#define WEB_SOCKET_NONCE_MAX_LEN
Definition: web_socket.h:145
error_t
Error codes.
Definition: error.h:43
#define osSprintf(dest,...)
Definition: os_port.h:237
#define osStrtok_r(s, delim, last)
Definition: os_port.h:231
@ WS_AUTH_MODE_DIGEST
Definition: web_socket.h:216
char_t username[WEB_SOCKET_USERNAME_MAX_LEN+1]
Definition: web_socket.h:362
#define osStrcasecmp(s1, s2)
Definition: os_port.h:189
MD5 algorithm context.
Definition: md5.h:62
Base64 encoding scheme.
WebSocketAuthMode requiredAuthMode
Definition: web_socket.h:360
#define WebSocket
Definition: web_socket.h:177
#define MD5_DIGEST_SIZE
Definition: md5.h:45
Authentication context.
Definition: web_socket.h:358
#define TRACE_DEBUG(...)
Definition: debug.h:119
char char_t
Definition: compiler_port.h:55
error_t strSafeCopy(char_t *dest, const char_t *src, size_t destSize)
Copy string.
Definition: str.c:178
#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:368
uint8_t value[]
Definition: tcp.h:376
char_t nonce[WEB_SOCKET_NONCE_MAX_LEN+1]
Definition: web_socket.h:367
@ ERROR_INVALID_SYNTAX
Definition: error.h:68
size_t webSocketAddAuthorizationField(WebSocket *webSocket, char_t *output)
Format Authorization header field.
char_t realm[WEB_SOCKET_REALM_MAX_LEN+1]
Definition: web_socket.h:364
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
void md5Update(Md5Context *context, const void *data, size_t length)
Update the MD5 context with a portion of the message being hashed.
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
uint8_t token[]
Definition: coap_common.h:181