s2n_sequence.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License").
  5. * You may not use this file except in compliance with the License.
  6. * A copy of the License is located at
  7. *
  8. * http://aws.amazon.com/apache2.0
  9. *
  10. * or in the "license" file accompanying this file. This file is distributed
  11. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  12. * express or implied. See the License for the specific language governing
  13. * permissions and limitations under the License.
  14. */
  15. #include "crypto/s2n_sequence.h"
  16. #include "error/s2n_errno.h"
  17. #include "tls/s2n_crypto.h"
  18. #include "utils/s2n_blob.h"
  19. #define SEQUENCE_NUMBER_POWER 8
  20. int s2n_increment_sequence_number(struct s2n_blob *sequence_number)
  21. {
  22. for (uint32_t j = sequence_number->size; j > 0; j--) {
  23. uint32_t i = j - 1;
  24. sequence_number->data[i] += 1;
  25. if (sequence_number->data[i]) {
  26. break;
  27. }
  28. /* RFC 5246 6.1: If a TLS implementation would need to wrap a sequence number, it must
  29. * renegotiate instead. We don't support renegotiation. Caller needs to create a new session.
  30. * This condition is very unlikely. It requires 2^64 - 1 records to be sent.
  31. */
  32. S2N_ERROR_IF(i == 0, S2N_ERR_RECORD_LIMIT);
  33. /* seq[i] wrapped, so let it carry */
  34. }
  35. return 0;
  36. }
  37. int s2n_sequence_number_to_uint64(struct s2n_blob *sequence_number, uint64_t *output)
  38. {
  39. POSIX_ENSURE_REF(sequence_number);
  40. uint8_t shift = 0;
  41. *output = 0;
  42. for (uint32_t i = sequence_number->size; i > 0; i--) {
  43. *output += ((uint64_t) sequence_number->data[i - 1]) << shift;
  44. shift += SEQUENCE_NUMBER_POWER;
  45. }
  46. return S2N_SUCCESS;
  47. }