ParsedCookie.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ParsedCookie.h"
  7. #include <AK/DateConstants.h>
  8. #include <AK/Function.h>
  9. #include <AK/StdLibExtras.h>
  10. #include <AK/Time.h>
  11. #include <AK/Vector.h>
  12. #include <LibIPC/Decoder.h>
  13. #include <LibIPC/Encoder.h>
  14. #include <LibWeb/Infra/Strings.h>
  15. #include <ctype.h>
  16. namespace Web::Cookie {
  17. static constexpr size_t s_max_cookie_size = 4096;
  18. static void parse_attributes(ParsedCookie& parsed_cookie, StringView unparsed_attributes);
  19. static void process_attribute(ParsedCookie& parsed_cookie, StringView attribute_name, StringView attribute_value);
  20. static void on_expires_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  21. static void on_max_age_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  22. static void on_domain_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  23. static void on_path_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  24. static void on_secure_attribute(ParsedCookie& parsed_cookie);
  25. static void on_http_only_attribute(ParsedCookie& parsed_cookie);
  26. static void on_same_site_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  27. static Optional<UnixDateTime> parse_date_time(StringView date_string);
  28. Optional<ParsedCookie> parse_cookie(StringView cookie_string)
  29. {
  30. // https://tools.ietf.org/html/rfc6265#section-5.2
  31. if (cookie_string.length() > s_max_cookie_size)
  32. return {};
  33. StringView name_value_pair;
  34. StringView unparsed_attributes;
  35. // 1. If the set-cookie-string contains a %x3B (";") character:
  36. if (auto position = cookie_string.find(';'); position.has_value()) {
  37. // The name-value-pair string consists of the characters up to, but not including, the first %x3B (";"), and the unparsed-
  38. // attributes consist of the remainder of the set-cookie-string (including the %x3B (";") in question).
  39. name_value_pair = cookie_string.substring_view(0, position.value());
  40. unparsed_attributes = cookie_string.substring_view(position.value());
  41. } else {
  42. // The name-value-pair string consists of all the characters contained in the set-cookie-string, and the unparsed-
  43. // attributes is the empty string.
  44. name_value_pair = cookie_string;
  45. }
  46. StringView name;
  47. StringView value;
  48. if (auto position = name_value_pair.find('='); position.has_value()) {
  49. // 3. The (possibly empty) name string consists of the characters up to, but not including, the first %x3D ("=") character, and the
  50. // (possibly empty) value string consists of the characters after the first %x3D ("=") character.
  51. name = name_value_pair.substring_view(0, position.value());
  52. if (position.value() < name_value_pair.length() - 1)
  53. value = name_value_pair.substring_view(position.value() + 1);
  54. } else {
  55. // 2. If the name-value-pair string lacks a %x3D ("=") character, ignore the set-cookie-string entirely.
  56. return {};
  57. }
  58. // 4. Remove any leading or trailing WSP characters from the name string and the value string.
  59. name = name.trim_whitespace();
  60. value = value.trim_whitespace();
  61. // 5. If the name string is empty, ignore the set-cookie-string entirely.
  62. if (name.is_empty())
  63. return {};
  64. // 6. The cookie-name is the name string, and the cookie-value is the value string.
  65. ParsedCookie parsed_cookie { MUST(String::from_utf8(name)), MUST(String::from_utf8(value)) };
  66. parse_attributes(parsed_cookie, unparsed_attributes);
  67. return parsed_cookie;
  68. }
  69. void parse_attributes(ParsedCookie& parsed_cookie, StringView unparsed_attributes)
  70. {
  71. // 1. If the unparsed-attributes string is empty, skip the rest of these steps.
  72. if (unparsed_attributes.is_empty())
  73. return;
  74. // 2. Discard the first character of the unparsed-attributes (which will be a %x3B (";") character).
  75. unparsed_attributes = unparsed_attributes.substring_view(1);
  76. StringView cookie_av;
  77. // 3. If the remaining unparsed-attributes contains a %x3B (";") character:
  78. if (auto position = unparsed_attributes.find(';'); position.has_value()) {
  79. // Consume the characters of the unparsed-attributes up to, but not including, the first %x3B (";") character.
  80. cookie_av = unparsed_attributes.substring_view(0, position.value());
  81. unparsed_attributes = unparsed_attributes.substring_view(position.value());
  82. } else {
  83. // Consume the remainder of the unparsed-attributes.
  84. cookie_av = unparsed_attributes;
  85. unparsed_attributes = {};
  86. }
  87. StringView attribute_name;
  88. StringView attribute_value;
  89. // 4. If the cookie-av string contains a %x3D ("=") character:
  90. if (auto position = cookie_av.find('='); position.has_value()) {
  91. // The (possibly empty) attribute-name string consists of the characters up to, but not including, the first %x3D ("=")
  92. // character, and the (possibly empty) attribute-value string consists of the characters after the first %x3D ("=") character.
  93. attribute_name = cookie_av.substring_view(0, position.value());
  94. if (position.value() < cookie_av.length() - 1)
  95. attribute_value = cookie_av.substring_view(position.value() + 1);
  96. } else {
  97. // The attribute-name string consists of the entire cookie-av string, and the attribute-value string is empty.
  98. attribute_name = cookie_av;
  99. }
  100. // 5. Remove any leading or trailing WSP characters from the attribute-name string and the attribute-value string.
  101. attribute_name = attribute_name.trim_whitespace();
  102. attribute_value = attribute_value.trim_whitespace();
  103. // 6. Process the attribute-name and attribute-value according to the requirements in the following subsections.
  104. // (Notice that attributes with unrecognized attribute-names are ignored.)
  105. process_attribute(parsed_cookie, attribute_name, attribute_value);
  106. // 7. Return to Step 1 of this algorithm.
  107. parse_attributes(parsed_cookie, unparsed_attributes);
  108. }
  109. void process_attribute(ParsedCookie& parsed_cookie, StringView attribute_name, StringView attribute_value)
  110. {
  111. if (attribute_name.equals_ignoring_ascii_case("Expires"sv)) {
  112. on_expires_attribute(parsed_cookie, attribute_value);
  113. } else if (attribute_name.equals_ignoring_ascii_case("Max-Age"sv)) {
  114. on_max_age_attribute(parsed_cookie, attribute_value);
  115. } else if (attribute_name.equals_ignoring_ascii_case("Domain"sv)) {
  116. on_domain_attribute(parsed_cookie, attribute_value);
  117. } else if (attribute_name.equals_ignoring_ascii_case("Path"sv)) {
  118. on_path_attribute(parsed_cookie, attribute_value);
  119. } else if (attribute_name.equals_ignoring_ascii_case("Secure"sv)) {
  120. on_secure_attribute(parsed_cookie);
  121. } else if (attribute_name.equals_ignoring_ascii_case("HttpOnly"sv)) {
  122. on_http_only_attribute(parsed_cookie);
  123. } else if (attribute_name.equals_ignoring_ascii_case("SameSite"sv)) {
  124. on_same_site_attribute(parsed_cookie, attribute_value);
  125. }
  126. }
  127. void on_expires_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  128. {
  129. // https://tools.ietf.org/html/rfc6265#section-5.2.1
  130. if (auto expiry_time = parse_date_time(attribute_value); expiry_time.has_value())
  131. parsed_cookie.expiry_time_from_expires_attribute = expiry_time.release_value();
  132. }
  133. void on_max_age_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  134. {
  135. // https://tools.ietf.org/html/rfc6265#section-5.2.2
  136. // If the first character of the attribute-value is not a DIGIT or a "-" character, ignore the cookie-av.
  137. if (attribute_value.is_empty() || (!isdigit(attribute_value[0]) && (attribute_value[0] != '-')))
  138. return;
  139. // Let delta-seconds be the attribute-value converted to an integer.
  140. if (auto delta_seconds = attribute_value.to_number<int>(); delta_seconds.has_value()) {
  141. if (*delta_seconds <= 0) {
  142. // If delta-seconds is less than or equal to zero (0), let expiry-time be the earliest representable date and time.
  143. parsed_cookie.expiry_time_from_max_age_attribute = UnixDateTime::earliest();
  144. } else {
  145. // Otherwise, let the expiry-time be the current date and time plus delta-seconds seconds.
  146. parsed_cookie.expiry_time_from_max_age_attribute = UnixDateTime::now() + Duration::from_seconds(*delta_seconds);
  147. }
  148. }
  149. }
  150. void on_domain_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  151. {
  152. // https://tools.ietf.org/html/rfc6265#section-5.2.3
  153. // If the attribute-value is empty, the behavior is undefined. However, the user agent SHOULD ignore the cookie-av entirely.
  154. if (attribute_value.is_empty())
  155. return;
  156. StringView cookie_domain;
  157. // If the first character of the attribute-value string is %x2E ("."):
  158. if (attribute_value[0] == '.') {
  159. // Let cookie-domain be the attribute-value without the leading %x2E (".") character.
  160. cookie_domain = attribute_value.substring_view(1);
  161. } else {
  162. // Let cookie-domain be the entire attribute-value.
  163. cookie_domain = attribute_value;
  164. }
  165. // Convert the cookie-domain to lower case.
  166. parsed_cookie.domain = MUST(Infra::to_ascii_lowercase(cookie_domain));
  167. }
  168. void on_path_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  169. {
  170. // https://tools.ietf.org/html/rfc6265#section-5.2.4
  171. // If the attribute-value is empty or if the first character of the attribute-value is not %x2F ("/"):
  172. if (attribute_value.is_empty() || attribute_value[0] != '/')
  173. // Let cookie-path be the default-path.
  174. return;
  175. // Let cookie-path be the attribute-value
  176. parsed_cookie.path = MUST(String::from_utf8(attribute_value));
  177. }
  178. void on_secure_attribute(ParsedCookie& parsed_cookie)
  179. {
  180. // https://tools.ietf.org/html/rfc6265#section-5.2.5
  181. parsed_cookie.secure_attribute_present = true;
  182. }
  183. void on_http_only_attribute(ParsedCookie& parsed_cookie)
  184. {
  185. // https://tools.ietf.org/html/rfc6265#section-5.2.6
  186. parsed_cookie.http_only_attribute_present = true;
  187. }
  188. // https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#name-the-samesite-attribute-2
  189. void on_same_site_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  190. {
  191. // 1. Let enforcement be "Default"
  192. // 2. If cookie-av's attribute-value is a case-insensitive match for "None", set enforcement to "None".
  193. // 3. If cookie-av's attribute-value is a case-insensitive match for "Strict", set enforcement to "Strict".
  194. // 4. If cookie-av's attribute-value is a case-insensitive match for "Lax", set enforcement to "Lax".
  195. parsed_cookie.same_site_attribute = same_site_from_string(attribute_value);
  196. }
  197. Optional<UnixDateTime> parse_date_time(StringView date_string)
  198. {
  199. // https://tools.ietf.org/html/rfc6265#section-5.1.1
  200. unsigned hour = 0;
  201. unsigned minute = 0;
  202. unsigned second = 0;
  203. unsigned day_of_month = 0;
  204. unsigned month = 0;
  205. unsigned year = 0;
  206. auto to_uint = [](StringView token, unsigned& result) {
  207. if (!all_of(token, isdigit))
  208. return false;
  209. if (auto converted = token.to_number<unsigned>(); converted.has_value()) {
  210. result = *converted;
  211. return true;
  212. }
  213. return false;
  214. };
  215. auto parse_time = [&](StringView token) {
  216. Vector<StringView> parts = token.split_view(':');
  217. if (parts.size() != 3)
  218. return false;
  219. for (const auto& part : parts) {
  220. if (part.is_empty() || part.length() > 2)
  221. return false;
  222. }
  223. return to_uint(parts[0], hour) && to_uint(parts[1], minute) && to_uint(parts[2], second);
  224. };
  225. auto parse_day_of_month = [&](StringView token) {
  226. if (token.is_empty() || token.length() > 2)
  227. return false;
  228. return to_uint(token, day_of_month);
  229. };
  230. auto parse_month = [&](StringView token) {
  231. for (unsigned i = 0; i < 12; ++i) {
  232. if (token.equals_ignoring_ascii_case(short_month_names[i])) {
  233. month = i + 1;
  234. return true;
  235. }
  236. }
  237. return false;
  238. };
  239. auto parse_year = [&](StringView token) {
  240. if (token.length() != 2 && token.length() != 4)
  241. return false;
  242. return to_uint(token, year);
  243. };
  244. Function<bool(char)> is_delimiter = [](char ch) {
  245. return ch == 0x09 || (ch >= 0x20 && ch <= 0x2f) || (ch >= 0x3b && ch <= 0x40) || (ch >= 0x5b && ch <= 0x60) || (ch >= 0x7b && ch <= 0x7e);
  246. };
  247. // 1. Using the grammar below, divide the cookie-date into date-tokens.
  248. Vector<StringView> date_tokens = date_string.split_view_if(is_delimiter);
  249. // 2. Process each date-token sequentially in the order the date-tokens appear in the cookie-date.
  250. bool found_time = false;
  251. bool found_day_of_month = false;
  252. bool found_month = false;
  253. bool found_year = false;
  254. for (auto const& date_token : date_tokens) {
  255. if (!found_time && parse_time(date_token)) {
  256. found_time = true;
  257. } else if (!found_day_of_month && parse_day_of_month(date_token)) {
  258. found_day_of_month = true;
  259. } else if (!found_month && parse_month(date_token)) {
  260. found_month = true;
  261. } else if (!found_year && parse_year(date_token)) {
  262. found_year = true;
  263. }
  264. }
  265. // 3. If the year-value is greater than or equal to 70 and less than or equal to 99, increment the year-value by 1900.
  266. if (year >= 70 && year <= 99)
  267. year += 1900;
  268. // 4. If the year-value is greater than or equal to 0 and less than or equal to 69, increment the year-value by 2000.
  269. if (year <= 69)
  270. year += 2000;
  271. // 5. Abort these steps and fail to parse the cookie-date if:
  272. if (!found_time || !found_day_of_month || !found_month || !found_year)
  273. return {};
  274. if (day_of_month < 1 || day_of_month > 31)
  275. return {};
  276. if (year < 1601)
  277. return {};
  278. if (hour > 23)
  279. return {};
  280. if (minute > 59)
  281. return {};
  282. if (second > 59)
  283. return {};
  284. // 6. Let the parsed-cookie-date be the date whose day-of-month, month, year, hour, minute, and second (in UTC) are the
  285. // day-of-month-value, the month-value, the year-value, the hour-value, the minute-value, and the second-value, respectively.
  286. // If no such date exists, abort these steps and fail to parse the cookie-date.
  287. if (day_of_month > static_cast<unsigned int>(days_in_month(year, month)))
  288. return {};
  289. // FIXME: This currently uses UNIX time, which is not equivalent to UTC due to leap seconds.
  290. auto parsed_cookie_date = UnixDateTime::from_unix_time_parts(year, month, day_of_month, hour, minute, second, 0);
  291. // 7. Return the parsed-cookie-date as the result of this algorithm.
  292. return parsed_cookie_date;
  293. }
  294. }
  295. template<>
  296. ErrorOr<void> IPC::encode(Encoder& encoder, Web::Cookie::ParsedCookie const& cookie)
  297. {
  298. TRY(encoder.encode(cookie.name));
  299. TRY(encoder.encode(cookie.value));
  300. TRY(encoder.encode(cookie.expiry_time_from_expires_attribute));
  301. TRY(encoder.encode(cookie.expiry_time_from_max_age_attribute));
  302. TRY(encoder.encode(cookie.domain));
  303. TRY(encoder.encode(cookie.path));
  304. TRY(encoder.encode(cookie.secure_attribute_present));
  305. TRY(encoder.encode(cookie.http_only_attribute_present));
  306. TRY(encoder.encode(cookie.same_site_attribute));
  307. return {};
  308. }
  309. template<>
  310. ErrorOr<Web::Cookie::ParsedCookie> IPC::decode(Decoder& decoder)
  311. {
  312. auto name = TRY(decoder.decode<String>());
  313. auto value = TRY(decoder.decode<String>());
  314. auto expiry_time_from_expires_attribute = TRY(decoder.decode<Optional<UnixDateTime>>());
  315. auto expiry_time_from_max_age_attribute = TRY(decoder.decode<Optional<UnixDateTime>>());
  316. auto domain = TRY(decoder.decode<Optional<String>>());
  317. auto path = TRY(decoder.decode<Optional<String>>());
  318. auto secure_attribute_present = TRY(decoder.decode<bool>());
  319. auto http_only_attribute_present = TRY(decoder.decode<bool>());
  320. auto same_site_attribute = TRY(decoder.decode<Web::Cookie::SameSite>());
  321. return Web::Cookie::ParsedCookie { move(name), move(value), same_site_attribute, move(expiry_time_from_expires_attribute), move(expiry_time_from_max_age_attribute), move(domain), move(path), secure_attribute_present, http_only_attribute_present };
  322. }