ParsedCookie.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 void parse_attributes(ParsedCookie& parsed_cookie, StringView unparsed_attributes);
  18. static void process_attribute(ParsedCookie& parsed_cookie, StringView attribute_name, StringView attribute_value);
  19. static void on_expires_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  20. static void on_max_age_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  21. static void on_domain_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  22. static void on_path_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  23. static void on_secure_attribute(ParsedCookie& parsed_cookie);
  24. static void on_http_only_attribute(ParsedCookie& parsed_cookie);
  25. static void on_same_site_attribute(ParsedCookie& parsed_cookie, StringView attribute_value);
  26. static Optional<UnixDateTime> parse_date_time(StringView date_string);
  27. bool cookie_contains_invalid_control_character(StringView cookie_string)
  28. {
  29. for (auto code_point : Utf8View { cookie_string }) {
  30. if (code_point <= 0x08)
  31. return true;
  32. if (code_point >= 0x0a && code_point <= 0x1f)
  33. return true;
  34. if (code_point == 0x7f)
  35. return true;
  36. }
  37. return false;
  38. }
  39. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6-6
  40. Optional<ParsedCookie> parse_cookie(StringView cookie_string)
  41. {
  42. // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F character (CTL characters excluding HTAB):
  43. // Abort these steps and ignore the set-cookie-string entirely.
  44. if (cookie_contains_invalid_control_character(cookie_string))
  45. return {};
  46. StringView name_value_pair;
  47. StringView unparsed_attributes;
  48. // 2. If the set-cookie-string contains a %x3B (";") character:
  49. if (auto position = cookie_string.find(';'); position.has_value()) {
  50. // 1. The name-value-pair string consists of the characters up to, but not including, the first %x3B (";"), and
  51. // the unparsed-attributes consist of the remainder of the set-cookie-string (including the %x3B (";") in
  52. // question).
  53. name_value_pair = cookie_string.substring_view(0, position.value());
  54. unparsed_attributes = cookie_string.substring_view(position.value());
  55. }
  56. // Otherwise:
  57. else {
  58. // 1. The name-value-pair string consists of all the characters contained in the set-cookie-string, and the
  59. // unparsed-attributes is the empty string.
  60. name_value_pair = cookie_string;
  61. }
  62. StringView name;
  63. StringView value;
  64. // 3. If the name-value-pair string lacks a %x3D ("=") character, then the name string is empty, and the value
  65. // string is the value of name-value-pair.
  66. if (auto position = name_value_pair.find('='); !position.has_value()) {
  67. value = name_value_pair;
  68. } else {
  69. // Otherwise, the name string consists of the characters up to, but not including, the first %x3D ("=") character
  70. // and the (possibly empty) value string consists of the characters after the first %x3D ("=") character.
  71. name = name_value_pair.substring_view(0, position.value());
  72. if (position.value() < name_value_pair.length() - 1)
  73. value = name_value_pair.substring_view(position.value() + 1);
  74. }
  75. // 4. Remove any leading or trailing WSP characters from the name string and the value string.
  76. name = name.trim_whitespace();
  77. value = value.trim_whitespace();
  78. // 5. If the sum of the lengths of the name string and the value string is more than 4096 octets, abort these steps
  79. // and ignore the set-cookie-string entirely.
  80. if (name.length() + value.length() > 4096)
  81. return {};
  82. // 6. The cookie-name is the name string, and the cookie-value is the value string.
  83. ParsedCookie parsed_cookie { MUST(String::from_utf8(name)), MUST(String::from_utf8(value)) };
  84. parse_attributes(parsed_cookie, unparsed_attributes);
  85. return parsed_cookie;
  86. }
  87. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6-8
  88. void parse_attributes(ParsedCookie& parsed_cookie, StringView unparsed_attributes)
  89. {
  90. // 1. If the unparsed-attributes string is empty, skip the rest of these steps.
  91. if (unparsed_attributes.is_empty())
  92. return;
  93. // 2. Discard the first character of the unparsed-attributes (which will be a %x3B (";") character).
  94. unparsed_attributes = unparsed_attributes.substring_view(1);
  95. StringView cookie_av;
  96. // 3. If the remaining unparsed-attributes contains a %x3B (";") character:
  97. if (auto position = unparsed_attributes.find(';'); position.has_value()) {
  98. // 1. Consume the characters of the unparsed-attributes up to, but not including, the first %x3B (";") character.
  99. cookie_av = unparsed_attributes.substring_view(0, position.value());
  100. unparsed_attributes = unparsed_attributes.substring_view(position.value());
  101. }
  102. // Otherwise:
  103. else {
  104. // 1. Consume the remainder of the unparsed-attributes.
  105. cookie_av = unparsed_attributes;
  106. unparsed_attributes = {};
  107. }
  108. // Let the cookie-av string be the characters consumed in this step.
  109. StringView attribute_name;
  110. StringView attribute_value;
  111. // 4. If the cookie-av string contains a %x3D ("=") character:
  112. if (auto position = cookie_av.find('='); position.has_value()) {
  113. // 1. The (possibly empty) attribute-name string consists of the characters up to, but not including, the first
  114. // %x3D ("=") character, and the (possibly empty) attribute-value string consists of the characters after the
  115. // first %x3D ("=") character.
  116. attribute_name = cookie_av.substring_view(0, position.value());
  117. if (position.value() < cookie_av.length() - 1)
  118. attribute_value = cookie_av.substring_view(position.value() + 1);
  119. }
  120. // Otherwise:
  121. else {
  122. // 1. The attribute-name string consists of the entire cookie-av string, and the attribute-value string is empty.
  123. attribute_name = cookie_av;
  124. }
  125. // 5. Remove any leading or trailing WSP characters from the attribute-name string and the attribute-value string.
  126. attribute_name = attribute_name.trim_whitespace();
  127. attribute_value = attribute_value.trim_whitespace();
  128. // 6. If the attribute-value is longer than 1024 octets, ignore the cookie-av string and return to Step 1 of this
  129. // algorithm.
  130. if (attribute_value.length() > 1024) {
  131. parse_attributes(parsed_cookie, unparsed_attributes);
  132. return;
  133. }
  134. // 7. Process the attribute-name and attribute-value according to the requirements in the following subsections.
  135. // (Notice that attributes with unrecognized attribute-names are ignored.)
  136. process_attribute(parsed_cookie, attribute_name, attribute_value);
  137. // 8. Return to Step 1 of this algorithm.
  138. parse_attributes(parsed_cookie, unparsed_attributes);
  139. }
  140. void process_attribute(ParsedCookie& parsed_cookie, StringView attribute_name, StringView attribute_value)
  141. {
  142. if (attribute_name.equals_ignoring_ascii_case("Expires"sv)) {
  143. on_expires_attribute(parsed_cookie, attribute_value);
  144. } else if (attribute_name.equals_ignoring_ascii_case("Max-Age"sv)) {
  145. on_max_age_attribute(parsed_cookie, attribute_value);
  146. } else if (attribute_name.equals_ignoring_ascii_case("Domain"sv)) {
  147. on_domain_attribute(parsed_cookie, attribute_value);
  148. } else if (attribute_name.equals_ignoring_ascii_case("Path"sv)) {
  149. on_path_attribute(parsed_cookie, attribute_value);
  150. } else if (attribute_name.equals_ignoring_ascii_case("Secure"sv)) {
  151. on_secure_attribute(parsed_cookie);
  152. } else if (attribute_name.equals_ignoring_ascii_case("HttpOnly"sv)) {
  153. on_http_only_attribute(parsed_cookie);
  154. } else if (attribute_name.equals_ignoring_ascii_case("SameSite"sv)) {
  155. on_same_site_attribute(parsed_cookie, attribute_value);
  156. }
  157. }
  158. static constexpr AK::Duration maximum_cookie_age()
  159. {
  160. return AK::Duration::from_seconds(400LL * 24 * 60 * 60);
  161. }
  162. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.1
  163. void on_expires_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  164. {
  165. // 1. Let the expiry-time be the result of parsing the attribute-value as cookie-date (see Section 5.1.1).
  166. auto expiry_time = parse_date_time(attribute_value);
  167. // 2. If the attribute-value failed to parse as a cookie date, ignore the cookie-av.
  168. if (!expiry_time.has_value())
  169. return;
  170. // 3. Let cookie-age-limit be the maximum age of the cookie (which SHOULD be 400 days in the future or sooner, see
  171. // Section 5.5).
  172. auto cookie_age_limit = UnixDateTime::now() + maximum_cookie_age();
  173. // 4. If the expiry-time is more than cookie-age-limit, the user agent MUST set the expiry time to cookie-age-limit
  174. // in seconds.
  175. if (expiry_time->seconds_since_epoch() > cookie_age_limit.seconds_since_epoch())
  176. expiry_time = cookie_age_limit;
  177. // 5. If the expiry-time is earlier than the earliest date the user agent can represent, the user agent MAY replace
  178. // the expiry-time with the earliest representable date.
  179. if (auto earliest = UnixDateTime::earliest(); *expiry_time < earliest)
  180. expiry_time = earliest;
  181. // 6. Append an attribute to the cookie-attribute-list with an attribute-name of Expires and an attribute-value of
  182. // expiry-time.
  183. parsed_cookie.expiry_time_from_expires_attribute = expiry_time.release_value();
  184. }
  185. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.2
  186. void on_max_age_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  187. {
  188. // 1. If the attribute-value is empty, ignore the cookie-av.
  189. if (attribute_value.is_empty())
  190. return;
  191. // 2. If the first character of the attribute-value is neither a DIGIT, nor a "-" character followed by a DIGIT,
  192. // ignore the cookie-av.
  193. if (!is_ascii_digit(attribute_value[0]) && attribute_value[0] != '-')
  194. return;
  195. // 3. If the remainder of attribute-value contains a non-DIGIT character, ignore the cookie-av.
  196. // 4. Let delta-seconds be the attribute-value converted to a base 10 integer.
  197. auto delta_seconds = attribute_value.to_number<i64>();
  198. if (!delta_seconds.has_value())
  199. return;
  200. // 5. Let cookie-age-limit be the maximum age of the cookie (which SHOULD be 400 days or less, see Section 5.5).
  201. auto cookie_age_limit = maximum_cookie_age();
  202. // 6. Set delta-seconds to the smaller of its present value and cookie-age-limit.
  203. if (*delta_seconds > cookie_age_limit.to_seconds())
  204. delta_seconds = cookie_age_limit.to_seconds();
  205. // 7. If delta-seconds is less than or equal to zero (0), let expiry-time be the earliest representable date and
  206. // time. Otherwise, let the expiry-time be the current date and time plus delta-seconds seconds.
  207. auto expiry_time = *delta_seconds <= 0
  208. ? UnixDateTime::earliest()
  209. : UnixDateTime::now() + AK::Duration::from_seconds(*delta_seconds);
  210. // 8. Append an attribute to the cookie-attribute-list with an attribute-name of Max-Age and an attribute-value of
  211. // expiry-time.
  212. parsed_cookie.expiry_time_from_max_age_attribute = expiry_time;
  213. }
  214. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.3
  215. void on_domain_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  216. {
  217. // 1. Let cookie-domain be the attribute-value.
  218. auto cookie_domain = attribute_value;
  219. // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be cookie-domain without its leading %x2E (".").
  220. if (cookie_domain.starts_with('.'))
  221. cookie_domain = cookie_domain.substring_view(1);
  222. // 3. Convert the cookie-domain to lower case.
  223. auto lowercase_cookie_domain = MUST(Infra::to_ascii_lowercase(cookie_domain));
  224. // 4. Append an attribute to the cookie-attribute-list with an attribute-name of Domain and an attribute-value of
  225. // cookie-domain.
  226. parsed_cookie.domain = move(lowercase_cookie_domain);
  227. }
  228. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.4
  229. void on_path_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  230. {
  231. // 1. If the attribute-value is empty or if the first character of the attribute-value is not %x2F ("/"):
  232. if (attribute_value.is_empty() || attribute_value[0] != '/') {
  233. // Let cookie-path be the default-path.
  234. return;
  235. }
  236. // Otherwise:
  237. // 1. Let cookie-path be the attribute-value.
  238. auto cookie_path = attribute_value;
  239. // 2. Append an attribute to the cookie-attribute-list with an attribute-name of Path and an attribute-value of
  240. // cookie-path.
  241. parsed_cookie.path = MUST(String::from_utf8(cookie_path));
  242. }
  243. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.5
  244. void on_secure_attribute(ParsedCookie& parsed_cookie)
  245. {
  246. parsed_cookie.secure_attribute_present = true;
  247. }
  248. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.6
  249. void on_http_only_attribute(ParsedCookie& parsed_cookie)
  250. {
  251. parsed_cookie.http_only_attribute_present = true;
  252. }
  253. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.7
  254. void on_same_site_attribute(ParsedCookie& parsed_cookie, StringView attribute_value)
  255. {
  256. // 1. Let enforcement be "Default".
  257. // 2. If cookie-av's attribute-value is a case-insensitive match for "None", set enforcement to "None".
  258. // 3. If cookie-av's attribute-value is a case-insensitive match for "Strict", set enforcement to "Strict".
  259. // 4. If cookie-av's attribute-value is a case-insensitive match for "Lax", set enforcement to "Lax".
  260. auto enforcement = same_site_from_string(attribute_value);
  261. // 5. Append an attribute to the cookie-attribute-list with an attribute-name of "SameSite" and an attribute-value
  262. // of enforcement.
  263. parsed_cookie.same_site_attribute = enforcement;
  264. }
  265. // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.1.1
  266. Optional<UnixDateTime> parse_date_time(StringView date_string)
  267. {
  268. // https://tools.ietf.org/html/rfc6265#section-5.1.1
  269. unsigned hour = 0;
  270. unsigned minute = 0;
  271. unsigned second = 0;
  272. unsigned day_of_month = 0;
  273. unsigned month = 0;
  274. unsigned year = 0;
  275. auto to_uint = [](StringView token, unsigned& result) {
  276. if (!all_of(token, isdigit))
  277. return false;
  278. if (auto converted = token.to_number<unsigned>(); converted.has_value()) {
  279. result = *converted;
  280. return true;
  281. }
  282. return false;
  283. };
  284. auto parse_time = [&](StringView token) {
  285. Vector<StringView> parts = token.split_view(':');
  286. if (parts.size() != 3)
  287. return false;
  288. for (auto const& part : parts) {
  289. if (part.is_empty() || part.length() > 2)
  290. return false;
  291. }
  292. return to_uint(parts[0], hour) && to_uint(parts[1], minute) && to_uint(parts[2], second);
  293. };
  294. auto parse_day_of_month = [&](StringView token) {
  295. if (token.is_empty() || token.length() > 2)
  296. return false;
  297. return to_uint(token, day_of_month);
  298. };
  299. auto parse_month = [&](StringView token) {
  300. for (unsigned i = 0; i < 12; ++i) {
  301. if (token.equals_ignoring_ascii_case(short_month_names[i])) {
  302. month = i + 1;
  303. return true;
  304. }
  305. }
  306. return false;
  307. };
  308. auto parse_year = [&](StringView token) {
  309. if (token.length() != 2 && token.length() != 4)
  310. return false;
  311. return to_uint(token, year);
  312. };
  313. Function<bool(char)> is_delimiter = [](char ch) {
  314. return ch == 0x09 || (ch >= 0x20 && ch <= 0x2f) || (ch >= 0x3b && ch <= 0x40) || (ch >= 0x5b && ch <= 0x60) || (ch >= 0x7b && ch <= 0x7e);
  315. };
  316. // 1. Using the grammar below, divide the cookie-date into date-tokens.
  317. Vector<StringView> date_tokens = date_string.split_view_if(is_delimiter);
  318. // 2. Process each date-token sequentially in the order the date-tokens appear in the cookie-date:
  319. bool found_time = false;
  320. bool found_day_of_month = false;
  321. bool found_month = false;
  322. bool found_year = false;
  323. for (auto const& date_token : date_tokens) {
  324. // 1. If the found-time flag is not set and the token matches the time production, set the found-time flag and
  325. // set the hour-value, minute-value, and second-value to the numbers denoted by the digits in the date-token,
  326. // respectively. Skip the remaining sub-steps and continue to the next date-token.
  327. if (!found_time && parse_time(date_token)) {
  328. found_time = true;
  329. }
  330. // 2. If the found-day-of-month flag is not set and the date-token matches the day-of-month production, set the
  331. // found-day-of-month flag and set the day-of-month-value to the number denoted by the date-token. Skip the
  332. // remaining sub-steps and continue to the next date-token.
  333. else if (!found_day_of_month && parse_day_of_month(date_token)) {
  334. found_day_of_month = true;
  335. }
  336. // 3. If the found-month flag is not set and the date-token matches the month production, set the found-month
  337. // flag and set the month-value to the month denoted by the date-token. Skip the remaining sub-steps and
  338. // continue to the next date-token.
  339. else if (!found_month && parse_month(date_token)) {
  340. found_month = true;
  341. }
  342. // 4. If the found-year flag is not set and the date-token matches the year production, set the found-year flag
  343. // and set the year-value to the number denoted by the date-token. Skip the remaining sub-steps and continue
  344. // to the next date-token.
  345. else if (!found_year && parse_year(date_token)) {
  346. found_year = true;
  347. }
  348. }
  349. // 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.
  350. if (year >= 70 && year <= 99)
  351. year += 1900;
  352. // 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.
  353. if (year <= 69)
  354. year += 2000;
  355. // 5. Abort these steps and fail to parse the cookie-date if:
  356. // * at least one of the found-day-of-month, found-month, found-year, or found-time flags is not set,
  357. if (!found_day_of_month || !found_month || !found_year || !found_time)
  358. return {};
  359. // * the day-of-month-value is less than 1 or greater than 31,
  360. if (day_of_month < 1 || day_of_month > 31)
  361. return {};
  362. // * the year-value is less than 1601,
  363. if (year < 1601)
  364. return {};
  365. // * the hour-value is greater than 23,
  366. if (hour > 23)
  367. return {};
  368. // * the minute-value is greater than 59, or
  369. if (minute > 59)
  370. return {};
  371. // * the second-value is greater than 59.
  372. if (second > 59)
  373. return {};
  374. // 6. Let the parsed-cookie-date be the date whose day-of-month, month, year, hour, minute, and second (in UTC) are the
  375. // day-of-month-value, the month-value, the year-value, the hour-value, the minute-value, and the second-value, respectively.
  376. // If no such date exists, abort these steps and fail to parse the cookie-date.
  377. if (day_of_month > static_cast<unsigned int>(days_in_month(year, month)))
  378. return {};
  379. // FIXME: This currently uses UNIX time, which is not equivalent to UTC due to leap seconds.
  380. auto parsed_cookie_date = UnixDateTime::from_unix_time_parts(year, month, day_of_month, hour, minute, second, 0);
  381. // 7. Return the parsed-cookie-date as the result of this algorithm.
  382. return parsed_cookie_date;
  383. }
  384. }
  385. template<>
  386. ErrorOr<void> IPC::encode(Encoder& encoder, Web::Cookie::ParsedCookie const& cookie)
  387. {
  388. TRY(encoder.encode(cookie.name));
  389. TRY(encoder.encode(cookie.value));
  390. TRY(encoder.encode(cookie.expiry_time_from_expires_attribute));
  391. TRY(encoder.encode(cookie.expiry_time_from_max_age_attribute));
  392. TRY(encoder.encode(cookie.domain));
  393. TRY(encoder.encode(cookie.path));
  394. TRY(encoder.encode(cookie.secure_attribute_present));
  395. TRY(encoder.encode(cookie.http_only_attribute_present));
  396. TRY(encoder.encode(cookie.same_site_attribute));
  397. return {};
  398. }
  399. template<>
  400. ErrorOr<Web::Cookie::ParsedCookie> IPC::decode(Decoder& decoder)
  401. {
  402. auto name = TRY(decoder.decode<String>());
  403. auto value = TRY(decoder.decode<String>());
  404. auto expiry_time_from_expires_attribute = TRY(decoder.decode<Optional<UnixDateTime>>());
  405. auto expiry_time_from_max_age_attribute = TRY(decoder.decode<Optional<UnixDateTime>>());
  406. auto domain = TRY(decoder.decode<Optional<String>>());
  407. auto path = TRY(decoder.decode<Optional<String>>());
  408. auto secure_attribute_present = TRY(decoder.decode<bool>());
  409. auto http_only_attribute_present = TRY(decoder.decode<bool>());
  410. auto same_site_attribute = TRY(decoder.decode<Web::Cookie::SameSite>());
  411. 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 };
  412. }