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-2025 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.5.0
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  return ERROR_INVALID_SYNTAX;
74 
75  //Basic access authentication?
76  if(osStrcasecmp(token, "Basic") == 0)
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(osStrcasecmp(token, "Digest") == 0)
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 = osStrtok_r(NULL, ",", &p);
96 
97  //Parse the WWW-Authenticate field
98  while(token != NULL)
99  {
100  //Check whether a separator is present
101  separator = osStrchr(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 = osStrlen(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(osStrcasecmp(name, "realm") == 0)
124  {
125  //Save realm
127  }
128 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
129  else if(osStrcasecmp(name, "nonce") == 0)
130  {
131  //Save nonce
132  strSafeCopy(authContext->nonce, value, WEB_SOCKET_NONCE_MAX_LEN + 1);
133  }
134  else if(osStrcasecmp(name, "opaque") == 0)
135  {
136  //Save nonce
138  }
139  else if(osStrcasecmp(name, "stale") == 0)
140  {
141  //Save stale flag
142  if(osStrcasecmp(value, "true") == 0)
143  {
144  authContext->stale = TRUE;
145  }
146  else
147  {
148  authContext->stale = FALSE;
149  }
150  }
151 #endif
152 
153  //Get next parameter
154  token = osStrtok_r(NULL, ",", &p);
155  }
156  }
157 #endif
158 
159  //Successful processing
160  return NO_ERROR;
161 }
162 
163 
164 /**
165  * @brief Format Authorization header field
166  * @param[in] webSocket Handle to a WebSocket
167  * @param[out] output Buffer where to format the header field
168  * @return Total length of the header field
169  **/
170 
172 {
173  size_t n;
174 
175 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED || WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
176  WebSocketAuthContext *authContext;
177 
178  //Point to the handshake context
179  authContext = &webSocket->authContext;
180 #endif
181 
182 #if (WEB_SOCKET_BASIC_AUTH_SUPPORT == ENABLED)
183  //Basic authentication scheme?
184  if(authContext->selectedAuthMode == WS_AUTH_MODE_BASIC)
185  {
186  size_t k;
187  char_t *temp;
188 
189  //Temporary buffer
190  temp = (char_t *) webSocket->rxContext.buffer;
191 
192  //Format Authorization header field
193  n = osSprintf(output, "Authorization: Basic ");
194 
195  //The client sends the userid and password, separated by a single colon
196  //character, within a Base64-encoded string in the credentials
197  k = osSprintf(temp, "%s:%s", authContext->username,
198  authContext->password);
199 
200  //Encode the resulting string using Base64
201  base64Encode(temp, k, output + n, &k);
202  //Update the total length of the header field
203  n += k;
204 
205  //Properly terminate the Authorization header field
206  n += osSprintf(output + n, "\r\n");
207  }
208  else
209 #endif
210 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
211  //Digest authentication scheme?
212  if(authContext->selectedAuthMode == WS_AUTH_MODE_DIGEST)
213  {
214  Md5Context md5Context;
215  uint8_t digest[MD5_DIGEST_SIZE];
216  char_t ha1[2 * MD5_DIGEST_SIZE + 1];
217  char_t ha2[2 * MD5_DIGEST_SIZE + 1];
218  char_t nc[9];
219 
220  //Count of the number of requests (including the current request)
221  //that the client has sent with the nonce value in this request
222  authContext->nc++;
223 
224  //Convert the value to hex string
225  osSprintf(nc, "%08x", authContext->nc);
226 
227  //Compute HA1 = MD5(username : realm : password)
228  md5Init(&md5Context);
229  md5Update(&md5Context, authContext->username, osStrlen(authContext->username));
230  md5Update(&md5Context, ":", 1);
231  md5Update(&md5Context, authContext->realm, osStrlen(authContext->realm));
232  md5Update(&md5Context, ":", 1);
233  md5Update(&md5Context, authContext->password, osStrlen(authContext->password));
234  md5Final(&md5Context, digest);
235 
236  //Convert MD5 hash to hex string
238  //Debug message
239  TRACE_DEBUG(" HA1: %s\r\n", ha1);
240 
241  //Compute HA2 = MD5(method : uri)
242  md5Init(&md5Context);
243  md5Update(&md5Context, "GET", 3);
244  md5Update(&md5Context, ":", 1);
245  md5Update(&md5Context, webSocket->uri, osStrlen(webSocket->uri));
246  md5Final(&md5Context, digest);
247 
248  //Convert MD5 hash to hex string
250  //Debug message
251  TRACE_DEBUG(" HA2: %s\r\n", ha2);
252 
253  //Compute MD5(HA1 : nonce : nc : cnonce : qop : HA2)
254  md5Init(&md5Context);
255  md5Update(&md5Context, ha1, osStrlen(ha1));
256  md5Update(&md5Context, ":", 1);
257  md5Update(&md5Context, authContext->nonce, osStrlen(authContext->nonce));
258  md5Update(&md5Context, ":", 1);
259  md5Update(&md5Context, nc, osStrlen(nc));
260  md5Update(&md5Context, ":", 1);
261  md5Update(&md5Context, authContext->cnonce, osStrlen(authContext->cnonce));
262  md5Update(&md5Context, ":", 1);
263  md5Update(&md5Context, "auth", 4);
264  md5Update(&md5Context, ":", 1);
265  md5Update(&md5Context, ha2, osStrlen(ha2));
266  md5Final(&md5Context, digest);
267 
268  //Convert MD5 hash to hex string
270  //Debug message
271  TRACE_DEBUG(" response: %s\r\n", ha1);
272 
273  //Format Authorization header field
274  n = osSprintf(output, "Authorization: Digest ");
275 
276  //Username
277  n += osSprintf(output + n, "username=\"%s\", ", authContext->username);
278  //Realm
279  n += osSprintf(output + n, "realm=\"%s\", ", authContext->realm);
280  //Nonce value
281  n += osSprintf(output + n, "nonce=\"%s\", ", authContext->nonce);
282  //URI
283  n += osSprintf(output + n, "uri=\"%s\", ", webSocket->uri);
284  //Quality of protection
285  n += osSprintf(output + n, "qop=\"auth\", ");
286  //Nonce count
287  n += osSprintf(output + n, "nc=\"%08x\", ", authContext->nc);
288  //Cnonce value
289  n += osSprintf(output + n, "cnonce=\"%s\", ", authContext->cnonce);
290  //Response
291  n += osSprintf(output + n, "response=\"%s\", ", ha1);
292  //Opaque parameter
293  n += osSprintf(output + n, "opaque=\"%s\"\r\n", authContext->opaque);
294  }
295  else
296 #endif
297  //Unknown authentication scheme?
298  {
299  //No need to add the Authorization header field
300  n = 0;
301  }
302 
303  //Return the total length of the Authorization header field
304  return n;
305 }
306 
307 
308 /**
309  * @brief Convert byte array to hex string
310  * @param[in] input Point to the byte array
311  * @param[in] inputLen Length of the byte array
312  * @param[out] output NULL-terminated string resulting from the conversion
313  **/
314 
315 void webSocketConvertArrayToHexString(const uint8_t *input,
316  size_t inputLen, char_t *output)
317 {
318  size_t i;
319 
320  //Hex conversion table
321  static const char_t hexDigit[16] =
322  {
323  '0', '1', '2', '3', '4', '5', '6', '7',
324  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
325  };
326 
327  //Process byte array
328  for(i = 0; i < inputLen; i++)
329  {
330  //Convert upper nibble
331  output[i * 2] = hexDigit[(input[i] >> 4) & 0x0F];
332  //Then convert lower nibble
333  output[i * 2 + 1] = hexDigit[input[i] & 0x0F];
334  }
335 
336  //Properly terminate the string with a NULL character
337  output[i * 2] = '\0';
338 }
339 
340 #endif
#define osStrchr(s, c)
Definition: os_port.h:198
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.
char_t name[]
#define osStrlen(s)
Definition: os_port.h:168
@ 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:234
#define osStrtok_r(s, delim, last)
Definition: os_port.h:228
@ 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:186
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:172
#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