]> git.plutz.net Git - cgilite/blobdiff - session.sh
allow configuration of session timeout, make timestamp variable reusable
[cgilite] / session.sh
index 3f3839ae8b167975a5e5231582509c5484d1f025..ee5c4993a72df047fe0fc67b3c384f2b5733be48 100755 (executable)
@@ -3,9 +3,12 @@
 [ -n "$include_session" ] && return 0
 include_session="$0"
 
+_DATE="$(date +%s)"
+SESSION_TIMEOUT="${SESSION_TIMEOUT:-7200}"
+
 server_key(){
   IDFILE="${IDFILE:-${_DATA:-.}/serverkey}"
-  if ! grep -m1 -xE '.{512}' "$IDFILE"; then
+  if [ "$(stat -c %s "$IDFILE")" -ne 512 ] || ! cat "$IDFILE"; then
     dd count=1 bs=512 if=/dev/urandom \
     | tee "$IDFILE"
   fi 2>&-
@@ -22,12 +25,12 @@ slopecode(){
 }
 
 randomid(){
-  dd bs=12 count=1 if=/dev/urandom \
-  | slopecode 2>&-
+  dd bs=12 count=1 if=/dev/urandom 2>&- \
+  | slopecode
 }
 
 timeid(){
-  d=$(($(date +%s) % 4294967296))
+  d=$(($_DATE % 4294967296))
   { printf "$(
       printf \\%o \
         $((d / 16777216 % 256)) \
@@ -35,11 +38,20 @@ timeid(){
         $((d / 256 % 256)) \
         $((d % 256))
     )"
-    dd bs=8 count=1 if=/dev/urandom
-  } | slopecode 2>&-
+    dd bs=8 count=1 if=/dev/urandom 2>&-
+  } | slopecode
 }
 
-checkid(){ grep -m 1 -xE '[0-9a-zA-Z:_]{16}'; }
+checkid(){ grep -m 1 -xE '[0-9a-zA-Z:=]{16}'; }
+
+transid(){
+  # transaction ID to modify a given file
+  local file="$1"
+  { stat -c %F%i%n%N%s%Y "$file" 2>&-
+    printf %s "$SESSION_ID"
+    server_key
+  } | sha256sum | cut -d\  -f1
+}
 
 update_session(){
   local session sid time sig serverkey checksig
@@ -51,18 +63,21 @@ update_session(){
   
   checksig="$(printf %s "$sid" "$time" "$serverkey" | sha256sum)"
   checksig="${checksig%% *}"
-  d=$(date +%s)
   
-  if [ "$checksig" != "$sig" -o "$time" -lt "$d" ] 2>&-; then
+  if ! [ "$checksig" = "$sig" \
+    -a "$time" -ge "$_DATE" \
+    -a "$(printf %s "$sid" |checkid)" ] 2>&-
+  then
+    debug Setting up new session
     sid="$(randomid)"
   fi
 
-  time=$(( $(date +%s) + 7200 ))
+  time=$(( $_DATE + $SESSION_TIMEOUT ))
   sig="$(printf %s "$sid" "$time" "$serverkey" |sha256sum)"
   sig="${sig%% *}"
   printf %s\\n "${sid}-${time}-${sig}"
 }
 
 SESSION_ID="$(update_session)"
-SET_COOKIE 0 "session=$SESSION_ID" HttpOnly
+SET_COOKIE 0 session="$SESSION_ID" Path=/ SameSite=Strict HttpOnly
 SESSION_ID="${SESSION_ID%%-*}"