qubes.GetRandomizedTime 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/bin/bash
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2016 Patrick Schleizer <adrelanos@riseup.net>
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License
  8. # as published by the Free Software Foundation; either version 2
  9. # of the License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. ## Similar code as Boot Clock Randomization.
  20. ## https://www.whonix.org/wiki/Boot_Clock_Randomization
  21. set -e
  22. ## Get a random 0 or 1.
  23. ## Will use this to decide to use plus or minus.
  24. ##
  25. ## Thanks to
  26. ## http://linux.byexamples.com/archives/128/generating-random-numbers/
  27. ZERO_OR_ONE="$(( 0+($(od -An -N2 -i /dev/random) )%(0+2) ))"
  28. ## Create a random number between 0 and 180.
  29. DELAY="$(( $(od -An -N2 -i /dev/random)%(180-0+1) ))"
  30. ## Create a random number between 0 and 999999999.
  31. ##
  32. ## Thanks to
  33. ## https://stackoverflow.com/questions/22887891/how-can-i-get-a-random-dev-random-number-between-0-and-999999999-in-bash
  34. NANOSECONDS="$(shuf -i0-999999999 -n1 --random-source=/dev/random)"
  35. ## Examples NANOSECONDS:
  36. ## 117752805
  37. ## 38653957
  38. ## Add leading zeros, because `date` expects 9 digits.
  39. NANOSECONDS="$(printf '%0*d\n' 9 "$NANOSECONDS")"
  40. ## Using
  41. ## printf '%0*d\n' 9 "38653957"
  42. ## 38653957
  43. ## becomes
  44. ## 038653957
  45. ## Examples NANOSECONDS:
  46. ## 117752805
  47. ## 038653957
  48. if [ "$ZERO_OR_ONE" = "0" ]; then
  49. PLUS_OR_MINUS="-"
  50. elif [ "$ZERO_OR_ONE" = "1" ]; then
  51. PLUS_OR_MINUS="+"
  52. else
  53. exit 2
  54. fi
  55. #OLD_TIME="$(date)"
  56. #OLD_TIME_NANOSECONDS="$(date +%s.%N)"
  57. OLD_UNIXTIME="$(date +%s)"
  58. NEW_TIME="$(( $OLD_UNIXTIME $PLUS_OR_MINUS $DELAY ))"
  59. NEW_TIME_NANOSECONDS="$NEW_TIME.$NANOSECONDS"
  60. echo "$NEW_TIME_NANOSECONDS"
  61. ## Testing the `date` syntax:
  62. ## date --date @1396733199.112834496
  63. ## date --date "@$NEW_TIME_NANOSECONDS"