-
Notifications
You must be signed in to change notification settings - Fork 10
/
mkcookie
executable file
·414 lines (399 loc) · 21 KB
/
mkcookie
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/bin/sh
######################################################################
#
# MKCOOKIE - HTTP Cookie String Generator
#
# USAGE: mkcookie [options] [<name>=<value>]
#
# * <name>=<value>:
# - Cookie variable name and value
# - If it is not given, try to get from STDIN "<name> <value>"
# (not use "="). You can give two or more variables by every pair
# is in every line
# * OPTIONS:
# - -e <expiring_info>
# for expiring date and time setting, You can use one of the following
# "YYYYMMDDHHMMSS" : direct setting of the datetime period.
# "+<n>" : lifetime in seconds from now.
# "YYYYMMDDHHMMSS+<n>" : lifetime in seconds from the datetime.
# (the datetimes is in your timezone)
# - -p <path_name>
# for path restriction
# - -d <domain_name>
# for domain restriction
# - -s <"Y"|"N"|"A">
# for HTTPS(SSL,TLS) restriction
# "Y" is always ON.
# "N" is always OFF.
# "A" is for auto-detection (default), with checking the HTTPS
# enviornmnent variable.
# - -h <"Y"|"N">
# for JavaScript restriction (HttpOnly)
# "Y" is HttpOnly ON.
# "N" is HttpOnly OFF (default).
# - -m <"S"|"L"|"N">
# for CSRF control
# "S" means "Strict."
# "L" means "Lax."
# "N" means "None."
# * NOTE:
# - The cookie string is started with <LF> for more usefulness. If you
# do not want the <LF> on the head, you can write the following.
# > mkcookie name=val | awk 'NR>1'
# - You can give me the cookie data with STDIN instead of the last
# argument. But name and value must be separated with space " "
# instead of equal "=".
#
# Return: $?=0 (when all of the options are valid)
# stdout : HTTP Cookie string
#
# Written by Shell-Shoccar Japan (@shellshoccarjpn) on 2024-08-14
#
# This is a public-domain software (CC0). It means that all of the
# people can use this for any purposes with no restrictions at all.
# By the way, We are fed up with the side effects which are brought
# about by the major licenses.
#
# The latest version is distributed on the following page.
# https://github.com/ShellShoccar-jpn/misc-tools
#
######################################################################
######################################################################
# Initial Configuration
######################################################################
# === Initialize shell environment ===================================
set -u
umask 0022
export LC_ALL=C
export PATH="$(command -p getconf PATH 2>/dev/null)${PATH+:}${PATH-}"
case $PATH in :*) PATH=${PATH#?};; esac
export UNIX_STD=2003 # to make HP-UX conform to POSIX
# === Define the functions for printing usage ========================
print_usage_and_exit () {
cat <<-USAGE 1>&2
Usage : ${0##*/} [options] [<name>=<value>]
Args : [<name>=<value>] ... Cookie variable name and value
If it is not given, try to get from
STDIN "<name> <value>" (not use "=").
You can give two or more variables
by every pair is in every line
Options : -e <expiring_info> . for expiring date and time setting
"YYYYMMDDHHMMSS" or "+<n>"
or "YYYYMMDDHHMMSS+<n>"
-p <path_name> ..... for path restriction
-d <domain_name> ... for domain restriction
-s <"Y"|"N"|"A"> ... for HTTPS(SSL,TLS) restriction
"Y" is always ON.
"N" is always OFF.
"A" is for auto-detection (default).
-h <"Y"|"N"> ....... for JavaScript restriction (HttpOnly)
"Y" is HttpOnly ON.
"N" is HttpOnly OFF (default).
-m <"S"|"L"|"N"> ... for CSRF control
"S" means "Strict."
"L" means "Lax."
"N" means "None."
Version : 2024-08-14 23:29:14 JST
(POSIX Bourne Shell/POSIX commands)
USAGE
exit 1
}
######################################################################
# Parse Arguments
######################################################################
# === Get the options and the filepath ===============================
# --- initialize option parameters -----------------------------------
var=''
opte=''
optp=''
optd=''
opts=''
opth=''
optm=''
#
# --- get them -------------------------------------------------------
optmode=''
case $# in [!0]*)
i=0
for arg in ${1+"$@"}; do
i=$((i+1))
if [ -z "$optmode" ]; then
case "$arg" in
-[epdshm]*)
ret=$(printf '%s\n' "${arg#-}" |
awk '{opt = substr($0,1,1); #
opt_str = (length($0)>1) ? substr($0,2) : ""; #
printf("%s %s", opt, opt_str); }')
ret1=${ret%% *}
ret2=${ret#* }
if [ "$ret1" = 'e' ]; then
if [ -n "$ret2" ]; then
opte=$ret2
else
optmode='e'
fi
fi
if [ "$ret1" = 'p' ]; then
if [ -n "$ret2" ]; then
optp=$ret2
else
optmode='p'
fi
fi
if [ "$ret1" = 'd' ]; then
if [ -n "$ret2" ]; then
optd=$ret2
else
optmode='d'
fi
fi
if [ "$ret1" = 's' ]; then
if [ -n "$ret2" ]; then
opts=$ret2
else
optmode='s'
fi
fi
if [ "$ret1" = 'h' ]; then
if [ -n "$ret2" ]; then
opth=$ret2
else
optmode='h'
fi
fi
if [ "$ret1" = 'm' ]; then
if [ -n "$ret2" ]; then
optm=$ret2
else
optmode='m'
fi
fi
;;
*)
if printf '%s' "$arg" | grep '^[^;.[:blank:]=]\{1,\}=.*$' >/dev/null; then
var=$arg
else
print_usage_and_exit
fi
;;
esac
elif [ "$optmode" = 'e' ]; then
opte=$arg
optmode=''
elif [ "$optmode" = 'p' ]; then
optp=$arg
optmode=''
elif [ "$optmode" = 'd' ]; then
optd=$arg
optmode=''
elif [ "$optmode" = 's' ]; then
opts=$arg
optmode=''
elif [ "$optmode" = 'h' ]; then
opth=$arg
optmode=''
elif [ "$optmode" = 'm' ]; then
optm=$arg
optmode=''
else
print_usage_and_exit
fi
done
;;
esac
# === Vaidate arguments ==============================================
printf '%s\n' "$var" | grep -Eq "$(printf '^([^ \t=]+=)?')" || print_usage_and_exit
case "$opte" in
'') ;;
*) check=$(printf '%s\n' "$opte" |
awk ' #
/^[0-9]+[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/ { #
print $0, 0; #
exit; #
} #
/^\+[0-9]+$/ { #
print "_", substr($0,2); #
exit; #
} #
/^[0-9]+[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\+[0-9]+$/ { #
pos = index($0,"+"); #
print substr($0,1,pos-1), substr($0,pos+1); #
exit; #
} #
{ #
print "!"; #
exit; #
}' )
case "$check" in '!') print_usage_and_exit ;; esac
datetime=${check% *}
case "$datetime" in '_') datetime=$(date '+%Y%m%d%H%M%S');; esac
lifetime=${check#* }
;;
esac
case "$optp" in '') ;;
*) path=$( printf '%s' "$optp" | tr -d ';\n' )
case "$path" in "$optp") :;; *) print_usage_and_exit;; esac;;
esac
case "$optd" in '') ;;
*) domain=$( printf '%s' "$optd" | tr -Cd 'A-Za-z0-9.-')
case "$domain" in "$optd") :;; *) print_usage_and_exit;; esac;;
esac
case "$opts" in '') ;;
*) secure=$( printf '%s' "$opts" | tr -Cd 'A-Za-z' )
case "$secure" in "$opts") :;; *) print_usage_and_exit;; esac;;
esac
case "$opth" in '') ;;
*) httponly=$(printf '%s' "$opth" | tr -Cd 'A-Za-z' )
case "$httponly" in "$opth") :;; *) print_usage_and_exit;; esac;;
esac
case "$optm" in '') ;;
*) samesite=$(printf '%s' "$optm" | tr -Cd 'A-Za-z' )
case "$samesite" in "$optm") :;; *) print_usage_and_exit;; esac;;
esac
######################################################################
# Main Routine
######################################################################
# === Print the basic part of cookie (with URL encoding) =============
case "$var" in #
'') cat ;;
*) printf '%s %s\n' "${var%%=*}" "${var#*=}" ;;
esac |
path="${path:-}" awk ' #
BEGIN { #
# --- prepare #
LF = sprintf("\n"); #
OFS = ""; #
ORS = ""; #
# --- prepare str2url #
for(i= 0;i< 16;i++){c2a[sprintf("%c",i)]=sprintf("%%0%X",i);} #
for( ;i<256;i++){c2a[sprintf("%c",i)]=sprintf("%%%X" ,i);} #
c2a[" "]="+"; #
for(i=48;i< 58;i++){c2a[sprintf("%c",i)]=sprintf("%c",i); } #
for(i=65;i< 91;i++){c2a[sprintf("%c",i)]=sprintf("%c",i); } #
for(i=97;i<123;i++){c2a[sprintf("%c",i)]=sprintf("%c",i); } #
c2a["-"]="-"; c2a["."]="."; c2a["_"]="_"; c2a["~"]="~"; #
# --- make the additional variables #
s = "'"${datetime:-}"'"; #
if (s != "") { addvar = addvar expires_var(s,"'"${lifetime:-}"'"); } #
s = ENVIRON["path"]; #
if (s != "") { addvar = addvar sprintf("; path=%s", s); } #
s = "'"${domain:-}"'"; #
if (s != "") { addvar = addvar sprintf("; domain=%s", s); } #
s = "'"${secure:-AUTO}"'"; #
if (match(s,/^[Yy]/)) { #
addvar = addvar "; Secure"; #
} else if (match(s,/^[Aa]/) && (match("'"${HTTPS:-}"'",/^[Oo][Nn]$/))) { #
addvar = addvar "; Secure"; #
} #
if (match("'"${httponly:-}"'",/^[Yy]/)) { addvar = addvar "; HttpOnly"; } #
s = "'"${samesite:-L}"'"; #
if (match(s,/^[Ss]/)) {addvar = addvar "; SameSite=Strict"; #
} else if (match(s,/^[Nn]/)) {addvar = addvar "; SameSite=None" ; #
} else {addvar = addvar "; SameSite=Lax" ;} #
} #
{ #
pos = index($0," "); #
print LF, "Set-Cookie: "; #
print substr($0,1,pos-1), "=", str2url(substr($0,pos+1)), addvar; #
} #
function str2url(s0, i,s) { #
for(i=1; i<=length(s0); i++){ #
s = s c2a[substr(s0,i,1)]; #
} #
return s; #
} #
function expires_var(datetime, lifetime, ut1,ut2,dt) { #
max_calced_year = 1970; # To remember every days on 1/1 from #
days_on_Jan1st_from_epoch[1970] = 0; # the Epoch which was calculated once #
split("31 0 31 30 31 30 31 31 30 31 30 31", days_of_month); #
split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec",monthname); #
split("Sun Mon Tue Wed Thu Fri Sat",weekname); #
# #
gm = YYYYMMDDhhmmss2unixtime('$(date -u '+%Y%m%d%H%M%S')'); #
lo = YYYYMMDDhhmmss2unixtime('$(date '+%Y%m%d%H%M%S')'); #
offset = lo - gm; #
offset -= (offset%2); # calcel the time lag of the two date starting time #
ut1 = YYYYMMDDhhmmss2unixtime(datetime) - offset; #
ut2 = ut1 + lifetime; #
dt = unixtime2YYYYMMDDhhmmss(ut2); #
return sprintf("; expires=%s", rfc850form(dt)); #
} #
function unixtime2YYYYMMDDhhmmss(ut, Y,M,D,h,m,s,t,i,j) { #
# 1) calculate hour,minute,second and number of days from the Epoch #
s = ut % 60; t = int(ut/60); #
m = t % 60; t = int( t/60); #
h = t % 24; #
days_from_epoch = int( t/24); #
# #
# 2) calculate year #
Y = int(days_from_epoch/365.2425)+1970+1; #
if (Y > max_calced_year) { #
i = days_on_Jan1st_from_epoch[max_calced_year]; #
for (j=max_calced_year; j<Y; j++) { #
i += (j%4!=0)?365:(j%100!=0)?366:(j%400!=0)?365:366; #
days_on_Jan1st_from_epoch[j+1] = i; #
} #
max_calced_year = Y; #
} #
for (;;Y--) { #
if (days_from_epoch >= days_on_Jan1st_from_epoch[Y]) { #
break; #
} #
} #
# #
# 3) calculate month,day #
days_of_month[2] = (Y%4!=0)?28:(Y%100!=0)?29:(Y%400!=0)?28:29; #
D = days_from_epoch - days_on_Jan1st_from_epoch[Y] + 1; #
for (M=1; ; M++) { #
if (D > days_of_month[M]) { #
D -= days_of_month[M]; #
} else { #
break; #
} #
} #
# #
return sprintf("%04d%02d%02d%02d%02d%02d",Y,M,D,h,m,s); #
} #
function YYYYMMDDhhmmss2unixtime(YYYYMMDDhhmmss, Y,M,D,h,m,s,l) { #
# 1) seperate the units #
l = length(YYYYMMDDhhmmss); #
Y = substr(YYYYMMDDhhmmss, 1,l-10)*1; #
M = substr(YYYYMMDDhhmmss,l-9, 2)*1; #
D = substr(YYYYMMDDhhmmss,l-7, 2)*1; #
h = substr(YYYYMMDDhhmmss,l-5, 2)*1; #
m = substr(YYYYMMDDhhmmss,l-3, 2)*1; #
s = substr(YYYYMMDDhhmmss,l-1 )*1; #
# #
# 2) validate #
if ((s>60) || (m>59) || (h>23) || (M>12)) {return -1;} #
days_of_month[2] = (Y%4!=0)?28:(Y%100!=0)?29:(Y%400!=0)?28:29; #
if (D > days_of_month[M] ) {return -1;} #
# #
# 3) adjust the value of year and month #
if (M<3) {M+=12; Y--;} #
# #
# 4) calculate unixtime #
return (365*Y+int(Y/4)-int(Y/100)+int(Y/400)+int(306*(M+1)/10)-428+D-719163)*86400+(h*3600)+(m*60)+s;
} #
function rfc850form(YYYYMMDDhhmmss, Y,M,D,h,m,s,l,w,Y2,M2) { #
# 1) seperate the units #
l = length(YYYYMMDDhhmmss); #
Y = substr(YYYYMMDDhhmmss, 1,l-10)*1; #
M = substr(YYYYMMDDhhmmss,l-9, 2)*1; #
D = substr(YYYYMMDDhhmmss,l-7, 2)*1; #
h = substr(YYYYMMDDhhmmss,l-5, 2)*1; #
m = substr(YYYYMMDDhhmmss,l-3, 2)*1; #
s = substr(YYYYMMDDhhmmss,l-1 )*1; #
# 2) choose the weekday #
M2 = (M<3) ? M+12 : M; #
Y2 = (M<3) ? Y-1 : Y; #
w = (365*Y2+int(Y2/4)-int(Y2/100)+int(Y2/400)+int(306*(M2+1)/10)+D-1)%7+1; #
# 3) generate the rfc850 formatted datetime #
return sprintf("%s, %02d-%s-%04d %02d:%02d:%02d GMT", #
weekname[w], D, monthname[M], Y, h, m, s); #
} #
'
######################################################################
# Finish
######################################################################
exit 0