nqminds / edgesec

Secure router - reference implementation
https://edgesec.info
MIT License
6 stars 1 forks source link

`os_get_reltime` returns actual time, not relative time #408

Closed aloisklink closed 1 year ago

aloisklink commented 1 year ago

Describe the bug

The current implementation of os_get_reltime returns the actual time, instead of the relative time.

To Reproduce

  1. Call os_get_reltime().
  2. Change the date/time on your PC (e.g. using leap seconds)
  3. Notice that the result of os_get_reltime() may go backwards.

Expected behavior

Every call to os_get_reltime() shows the actual relative time compared to when the program started running.

Additionally, the result of os_get_reltime() should never be lower than previous calls.

Additional context

It's one of the falsehoods programmers believe about time :laughing:

[...]

  • Timestamps always advance monotonically.

Taken from https://gist.github.com/timvisee/fcda9bbdff88d45cc9061606b4b923ca

man gettimeofday(2) also recommends using clock_gettime().

Notes

The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).

Copied from man gettimeofday(2) under the Linux-man-pages-copyleft license

hostapd also has a better implementation that we can use, (see https://w1.fi/cgit/hostap/commit/?id=594516b4c28a94ca686b17f1e463dfd6712b75a7) but it might be Linux specific and not work on FreeBSD/CheriBSD.

mereacre commented 1 year ago

Great find. Can you provide a fix as a PR?

aloisklink commented 1 year ago

Great find. Can you provide a fix as a PR?

:+1: I'll stick it on my todo-list, but since this is a bit of a high/medium-priority issue, it might take a while to get to it!

It looks like standard ISO C has clock() that we can use for this, but there's a bunch of warnings about non-conforming implementations, so it might be better to use the clock_gettime() with CLOCK_MONOTONIC from POSIX C.