]> git.plutz.net Git - cgilite/blobdiff - session.sh
table style
[cgilite] / session.sh
index 8929ab3de62638fa4084cbf3f6d50ba5510ec960..1f4699e441357303b4dd4b6e4daeff3af1bb47c8 100755 (executable)
@@ -16,8 +16,16 @@ fi
 if which openssl >/dev/null; then
   session_mac(){ { [ $# -gt 0 ] && printf %s "$*" || cat; } | openssl dgst -sha1 -hmac "$(server_key)" -binary |slopecode; }
 else
-  # sham hmac if openssl is unavailable
-  session_mac(){ { [ $# -gt 0 ] && printf %s "$*" || cat; server_key; } | sha256sum |cut -d\  -f1; }
+  # Gonzo MAC if openssl is unavailable
+  session_mac(){
+    { server_key | dd status=none bs=256 count=1 skip=1
+      { server_key | dd status=none bs=256 count=1
+        [ $# -gt 0 ] && printf %s "$*" || cat
+      } \
+      | sha256sum -;
+    } \
+    | sha256sum | cut -d\  -f1
+  }
 fi
 
 server_key(){
@@ -67,6 +75,7 @@ checkid(){ { [ $# -gt 0 ] && printf %s "$*" || cat; } | grep -m 1 -xE '[0-9a-zA-
 
 update_session(){
   local session sid time sig checksig
+  unset SESSION_KEY SESSION_ID
 
   read -r sid time sig <<-END
        $(POST session_key || COOKIE session)
@@ -74,23 +83,38 @@ update_session(){
   
   checksig="$(session_mac "$sid" "$time")"
   
-  if [ "$checksig" = "$sig" \
-    -a "$time" -ge "$_DATE" \
-    -a "$(printf %s "$sid" |checkid)" ] 2>&-
+  if [ "$checksig" = "$sig" \
+       -a "$time" -ge "$_DATE" \
+       -a "$(checkid "$sid")" ] 2>&-
   then
-    debug "Setting up new session"
-    sid="$(randomid)"
+    time=$(( $_DATE + $SESSION_TIMEOUT ))
+    sig="$(session_mac "$sid" "$time")"
+
+    SESSION_KEY="${sid} ${time} ${sig}"
+    SESSION_ID="${sid}"
+    return 0
+  else
+    return 1
   fi
 
+}
+
+new_session(){
+  local sid time sig
+
+  debug "Setting up new session"
+  sid="$(randomid)"
   time=$(( $_DATE + $SESSION_TIMEOUT ))
   sig="$(session_mac "$sid" "$time")"
-  printf %s\\n "${sid} ${time} ${sig}"
+
+  SESSION_KEY="${sid} ${time} ${sig}"
+  SESSION_ID="${sid}"
 }
 
 SESSION_BIND() {
   # Set tamper-proof authenticated cookie
   local key="$1" value="$2"
-  SET_COOKIE session "$key"="${value} $(session_mac "$value" "$SESSION_ID")"
+  SET_COOKIE session "$key"="${value} $(session_mac "$value" "$SESSION_ID")" Path="/${_BASE#/}" SameSite=Strict HttpOnly
 }
 
 SESSION_VAR() {
@@ -106,6 +130,9 @@ SESSION_VAR() {
   fi
 }
 
-SESSION_KEY="$(update_session)"
-SET_COOKIE 0 session="$SESSION_KEY" Path=/ SameSite=Strict HttpOnly
-SESSION_ID="${SESSION_KEY%% *}"
+SESSION_COOKIE() {
+  [ "$1" = new ] && new_session
+  SET_COOKIE 0 session="$SESSION_KEY" Path="/${_BASE#/}" SameSite=Strict HttpOnly
+}
+
+update_session || new_session