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-2024 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.4.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"))
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"))
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"))
124  {
125  //Save realm
127  }
128 #if (WEB_SOCKET_DIGEST_AUTH_SUPPORT == ENABLED)
129  else if(!osStrcasecmp(name, "nonce"))
130  {
131  //Save nonce
132  strSafeCopy(authContext->nonce, value, WEB_SOCKET_NONCE_MAX_LEN + 1);
133  }
134  else if(!osStrcasecmp(name, "opaque"))
135  {
136  //Save nonce
138  }
139  else if(!osStrcasecmp(name, "stale"))
140  {
141  //Save stale flag
142  if(!osStrcasecmp(value, "true"))
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  char_t ha1[2 * MD5_DIGEST_SIZE + 1];
216  char_t ha2[2 * MD5_DIGEST_SIZE + 1];
217  char_t nc[9];
218 
219  //Count of the number of requests (including the current request)
220  //that the client has sent with the nonce value in this request
221  authContext->nc++;
222 
223  //Convert the value to hex string
224  osSprintf(nc, "%08x", authContext->nc);
225 
226  //Compute HA1 = MD5(username : realm : password)
227  md5Init(&md5Context);
228  md5Update(&md5Context, authContext->username, osStrlen(authContext->username));
229  md5Update(&md5Context, ":", 1);
230  md5Update(&md5Context, authContext->realm, osStrlen(authContext->realm));
231  md5Update(&md5Context, ":", 1);
232  md5Update(&md5Context, authContext->password, osStrlen(authContext->password));
233  md5Final(&md5Context, NULL);
234 
235  //Convert MD5 hash to hex string
237  //Debug message
238  TRACE_DEBUG(" HA1: %s\r\n", ha1);
239 
240  //Compute HA2 = MD5(method : uri)
241  md5Init(&md5Context);
242  md5Update(&md5Context, "GET", 3);
243  md5Update(&md5Context, ":", 1);
244  md5Update(&md5Context, webSocket->uri, osStrlen(webSocket->uri));
245  md5Final(&md5Context, NULL);
246 
247  //Convert MD5 hash to hex string
249  //Debug message
250  TRACE_DEBUG(" HA2: %s\r\n", ha2);
251 
252  //Compute MD5(HA1 : nonce : nc : cnonce : qop : HA2)
253  md5Init(&md5Context);
254  md5Update(&md5Context, ha1, osStrlen(ha1));
255  md5Update(&md5Context, ":", 1);
256  md5Update(&md5Context, authContext->nonce, osStrlen(authContext->nonce));
257  md5Update(&md5Context, ":", 1);
258  md5Update(&md5Context, nc, osStrlen(nc));
259  md5Update(&md5Context, ":", 1);
260  md5Update(&md5Context, authContext->cnonce, osStrlen(authContext->cnonce));
261  md5Update(&md5Context, ":", 1);
262  md5Update(&md5Context, "auth", 4);
263  md5Update(&md5Context, ":", 1);
264  md5Update(&md5Context, ha2, osStrlen(ha2));
265  md5Final(&md5Context, NULL);
266 
267  //Convert MD5 hash to hex string
269  //Debug message
270  TRACE_DEBUG(" response: %s\r\n", ha1);
271 
272  //Format Authorization header field
273  n = osSprintf(output, "Authorization: Digest ");
274 
275  //Username
276  n += osSprintf(output + n, "username=\"%s\", ", authContext->username);
277  //Realm
278  n += osSprintf(output + n, "realm=\"%s\", ", authContext->realm);
279  //Nonce value
280  n += osSprintf(output + n, "nonce=\"%s\", ", authContext->nonce);
281  //URI
282  n += osSprintf(output + n, "uri=\"%s\", ", webSocket->uri);
283  //Quality of protection
284  n += osSprintf(output + n, "qop=\"auth\", ");
285  //Nonce count
286  n += osSprintf(output + n, "nc=\"%08x\", ", authContext->nc);
287  //Cnonce value
288  n += osSprintf(output + n, "cnonce=\"%s\", ", authContext->cnonce);
289  //Response
290  n += osSprintf(output + n, "response=\"%s\", ", ha1);
291  //Opaque parameter
292  n += osSprintf(output + n, "opaque=\"%s\"\r\n", authContext->opaque);
293  }
294  else
295 #endif
296  //Unknown authentication scheme?
297  {
298  //No need to add the Authorization header field
299  n = 0;
300  }
301 
302  //Return the total length of the Authorization header field
303  return n;
304 }
305 
306 
307 /**
308  * @brief Convert byte array to hex string
309  * @param[in] input Point to the byte array
310  * @param[in] inputLen Length of the byte array
311  * @param[out] output NULL-terminated string resulting from the conversion
312  **/
313 
314 void webSocketConvertArrayToHexString(const uint8_t *input,
315  size_t inputLen, char_t *output)
316 {
317  size_t i;
318 
319  //Hex conversion table
320  static const char_t hexDigit[16] =
321  {
322  '0', '1', '2', '3', '4', '5', '6', '7',
323  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
324  };
325 
326  //Process byte array
327  for(i = 0; i < inputLen; i++)
328  {
329  //Convert upper nibble
330  output[i * 2] = hexDigit[(input[i] >> 4) & 0x0F];
331  //Then convert lower nibble
332  output[i * 2 + 1] = hexDigit[input[i] & 0x0F];
333  }
334 
335  //Properly terminate the string with a NULL character
336  output[i * 2] = '\0';
337 }
338 
339 #endif
void md5Update(Md5Context *context, const void *data, size_t length)
Update the MD5 context with a portion of the message being hashed.
void base64Encode(const void *input, size_t inputLen, char_t *output, size_t *outputLen)
Base64 encoding algorithm.
Definition: base64.c:142
Base64 encoding scheme.
uint8_t token[]
Definition: coap_common.h:181
char char_t
Definition: compiler_port.h:48
Debugging facilities.
#define TRACE_DEBUG(...)
Definition: debug.h:107
uint8_t n
error_t
Error codes.
Definition: error.h:43
@ ERROR_INVALID_SYNTAX
Definition: error.h:68
@ NO_ERROR
Success.
Definition: error.h:44
MD5 (Message-Digest Algorithm)
#define MD5_DIGEST_SIZE
Definition: md5.h:45
void md5Init(Md5Context *context)
Initialize MD5 message digest context.
void md5Final(Md5Context *context, uint8_t *digest)
Finish the MD5 message digest.
uint8_t p
Definition: ndp.h:300
TCP/IP stack core.
#define osStrcasecmp(s1, s2)
Definition: os_port.h:183
#define osStrchr(s, c)
Definition: os_port.h:195
#define osStrlen(s)
Definition: os_port.h:165
#define osSprintf(dest,...)
Definition: os_port.h:231
#define TRUE
Definition: os_port.h:50
#define FALSE
Definition: os_port.h:46
#define osStrtok_r(s, delim, last)
Definition: os_port.h:225
char_t name[]
error_t strSafeCopy(char_t *dest, const char_t *src, size_t destSize)
Copy string.
Definition: str.c:164
char_t * strTrimWhitespace(char_t *s)
Removes all leading and trailing whitespace from a string.
Definition: str.c:78
String manipulation helper functions.
MD5 algorithm context.
Definition: md5.h:62
uint8_t digest[16]
Definition: md5.h:66
Authentication context.
Definition: web_socket.h:358
char_t password[WEB_SOCKET_PASSWORD_MAX_LEN+1]
Definition: web_socket.h:363
char_t realm[WEB_SOCKET_REALM_MAX_LEN+1]
Definition: web_socket.h:364
char_t username[WEB_SOCKET_USERNAME_MAX_LEN+1]
Definition: web_socket.h:362
WebSocketAuthMode requiredAuthMode
Definition: web_socket.h:360
char_t nonce[WEB_SOCKET_NONCE_MAX_LEN+1]
Definition: web_socket.h:367
char_t cnonce[WEB_SOCKET_CNONCE_SIZE *2+1]
Definition: web_socket.h:368
char_t opaque[WEB_SOCKET_OPAQUE_MAX_LEN+1]
Definition: web_socket.h:369
WebSocketAuthMode selectedAuthMode
Definition: web_socket.h:361
uint8_t value[]
Definition: tcp.h:369
WebSocket API (client and server)
#define WEB_SOCKET_OPAQUE_MAX_LEN
Definition: web_socket.h:152
@ WS_AUTH_MODE_BASIC
Definition: web_socket.h:215
@ WS_AUTH_MODE_DIGEST
Definition: web_socket.h:216
#define WEB_SOCKET_NONCE_MAX_LEN
Definition: web_socket.h:145
#define WebSocket
Definition: web_socket.h:177
#define WEB_SOCKET_REALM_MAX_LEN
Definition: web_socket.h:124
void webSocketConvertArrayToHexString(const uint8_t *input, size_t inputLen, char_t *output)
Convert byte array to hex string.
size_t webSocketAddAuthorizationField(WebSocket *webSocket, char_t *output)
Format Authorization header field.
error_t webSocketParseAuthenticateField(WebSocket *webSocket, char_t *value)
Parse WWW-Authenticate header field.
HTTP authentication for WebSockets.