-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.php
314 lines (271 loc) · 9.85 KB
/
utils.php
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
<?php
/**
BSD 2-Clause License
Copyright (c) 2020, Alexandre Janon <alex14fr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
include_once "conf/conf.php";
function canonical()
{
global $canonicalProto, $canonicalHost;
if (!empty($canonicalHost)) {
if (empty($_SERVER["HTTP_X_FORWARDED_HOST"]) && empty($_SERVER["HTTP_HOST"])) {
return;
}
if (empty($canonicalProto)) {
$canonicalProto = ($_SERVER["HTTP_X_FORWARDED_PROTO"] ?? $_SERVER["REQUEST_SCHEME"]);
}
$curHost = ($_SERVER["HTTP_X_FORWARDED_HOST"] ?? $_SERVER["HTTP_HOST"]);
if ($curHost !== $canonicalHost) {
$destination = "$canonicalProto://$canonicalHost" . $_SERVER["REQUEST_URI"];
header("HTTP/1.1 302 Found");
header("Cache-control: max-age=3600");
header("Location: $destination");
print "<h1>302 Found</h1><a href=\"$destination\">$destination</a>";
exit;
}
}
}
function sendCsp($add = "")
{
header("Content-security-policy: default-src 'none'; font-src 'self'; img-src 'self'; style-src 'self'; base-uri 'none'; frame-ancestors 'none'; " . (empty($add) ? "" : $add));
header("X-frame-options: deny");
}
function die403($s)
{
header("403 Forbidden");
die($s);
}
function str_replace_first($search, $replace, $subject)
{
$pos = strpos($subject, $search);
if ($pos !== false) {
return substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
function san_pageId($id)
{
$id = strtolower($id);
$id = substr($id, 0, 47);
return preg_replace("/[^a-z0-9\-_]/", "", $id);
}
function san_pageRev($rev)
{
return preg_replace("/[^0-9]/", "", $rev);
}
function san_filename($fn)
{
$fn = basename($fn);
$fn = strtolower($fn);
$fn = substr($fn, 0, 255);
return preg_replace("/[^a-z0-9\-_\.]/", "", $fn);
}
function san_csv($string)
{
return preg_replace("/[^ a-zA-Z0-9\-_\.@éèçàäëüïöâêîôûùŸÿŷŶâêîôûÉÈÇÀÄËÜÏÖÂÊÎÔÛÙ]/", " ", $string);
}
function san_csv_ext($string)
{
return preg_replace("/[^ a-zA-Z0-9\-_\.@éèçàäëüïöâêîôûùŸÿŷŶâêîôûÉÈÇÀÄËÜÏÖÂÊÎÔÛÙ&;]/", " ", $string);
}
function san_diff($string)
{
return preg_replace("/[^ \r\na-zA-Z0-9\[\](){}\/?=\\|#~&'\"µ%§:;\^!,*+\-_\.@éèçàäëüïöûùŸÿŷŶâêîôŷûÉÈÇÀÄËÜÏÖÂÊÎÔÛÙ`]/", "", $string);
}
function sendNotify($reason, $subj, $body, $hdrs="")
{
global $mailNotify;
xmail(implode(',',$mailNotify[$reason]), $subj, $body, $hdrs);
}
function readtmpl($id)
{
$id = san_pageId($id);
$out = str_replace("\n", "", file_get_contents("conf/$id.tmpl"));
if ($id === "htmlhead") {
$out = str_replace("<!doctype html>", "<!doctype html>\n", $out);
$out = str_replace("~~CSSTS~~", filemtime("static/style.min.css"), $out);
global $pageId;
if($pageId == 'index') {
global $metaDesc;
$out = str_replace('~~METADESC~~', '<meta name=description content="'.$metaDesc.'">', $out);
} else {
$out = str_replace('~~METADESC~~', '', $out);
}
}
return $out;
}
function pageLink($id, $incbase = false)
{
global $baseUrl,$pagePrefix,$pageSuffix;
return ($incbase ? $baseUrl : "") . $pagePrefix . $id . $pageSuffix;
}
if(!function_exists("random_bytes")) {
function random_bytes($n) {
$f=fopen("/dev/urandom","r");
return fread($f, $n);
}
}
function get_random()
{
return hash("sha256",random_bytes(32));
}
function gen_xtok($namespace = "")
{
}
function base64url_encode( $data ){
return rtrim( strtr( base64_encode( $data ), '+/', '-_'), '=');
}
function base64url_decode( $data ){
return base64_decode( strtr( $data, '-_', '+/') . str_repeat('=', 3 - ( 3 + strlen( $data )) % 4 ));
}
$verifiedLogin=false;
$certLogin="";
function issue_login_token($login)
{
global $clientIp, $baseUrl, $secret3, $secret2;
$sticky=base64url_encode(hash("sha256",$clientIp."|".$baseUrl."|".$_SERVER["HTTP_USER_AGENT"]."|".hash("sha256",$secret2,true),true));
$mask=hash("sha512","mnwiki@$baseUrl@".filemtime("conf/conf.php"),true);
if(strlen($login)>strlen($mask)) { die("login too long"); }
$loginn=base64url_encode($login^$mask);
$strToSign="$sticky.$loginn.".time();
$sign=base64url_encode(hash_hmac("sha256",$strToSign,$secret3,true));
return "$strToSign.$sign";
}
function get_login_cookie_name() {
global $baseUrl;
$ret=base64url_encode(hash("md5","mnwiki@$baseUrl@".filemtime("conf/conf.php"),true));
//print "GLCN = $ret<p>";
return $ret;
}
function allow_login($login)
{
global $verifiedLogin, $certLogin;
$tok=issue_login_token($login);
setcookie(get_login_cookie_name(), $tok, array("samesite"=>"Strict","expires"=>time()+86400, "secure"=>true, "httponly"=>true));
$verifiedLogin=true;
$certLogin=$login;
}
function chk_login_tok($token) {
global $clientIp, $baseUrl, $secret3, $secret2;
if(empty($token)) return "";
$cltok=explode(".",$token);
//print "CK LOGIN TOK $token<p>";
if(count($cltok)!==4) {
// print " 1<p>";
return "";
}
$signOk=base64url_encode(hash_hmac("sha256",$cltok[0].".".$cltok[1].".".$cltok[2],$secret3,true));
if(!hash_equals($signOk,$cltok[3])) { die("login token verification failed (signature)"); }
$sticky=base64url_encode(hash("sha256",$clientIp."|".$baseUrl."|".$_SERVER["HTTP_USER_AGENT"]."|".hash("sha256",$secret2,true),true));
if(!hash_equals($sticky,$cltok[0])) {
// print " 2<p>";
return "";
}
if(!is_numeric($cltok[2]) || ($cltok[2]+86400<time())) {
// print " 3<p>";
return "";
}
$mask=hash("sha512","mnwiki@$baseUrl@".filemtime("conf/conf.php"),true);
$login=base64url_decode($cltok[1])^$mask;
//print " 4 LOGIN=$login ".base64url_encode($login)." <p>";
return $login;
}
function get_login()
{
global $verifiedLogin, $certLogin;
if($verifiedLogin)
return($certLogin);
else {
$verifiedLogin=true;
$certLogin="";
if(!isset($_COOKIE[get_login_cookie_name()])) {
return($certLogin);
}
$tok=$_COOKIE[get_login_cookie_name()];
$certLogin=chk_login_tok($tok);
return($certLogin);
}
}
$xtokCookie=false;
function head_xtok()
{
global $xtokCookie;
$xtokCookie=random_bytes(16);
setcookie("xtok", base64url_encode($xtokCookie), array("samesite"=>"Strict","secure"=>true,"httponly"=>true));
}
function get_xtok($namespace = "")
{
global $clientIp, $baseUrl, $secret2, $verifiedLogin, $xtokCookie;
if(!$xtokCookie) { die("xtok cookie not set"); }
$strToSign=base64url_encode(hash("sha256",$xtokCookie."|".$namespace."|".$clientIp."|".$baseUrl."|".$verifiedLogin."|".$_SERVER["HTTP_USER_AGENT"]."|".hash("sha256",$secret2,true),true)).".".time();
$sign=base64url_encode(hash_hmac("sha256",$strToSign,$secret2,true));
$tok=$strToSign.".".$sign;
return $tok;
}
function pr_xtok($namespace = "")
{
$tok=get_xtok($namespace);
return "<input type=hidden name=xtok value=$tok>";
}
function chk_xtok_tok($token, $namespace = "")
{
global $clientIp, $baseUrl, $secret2, $verifiedLogin;
$cltok=explode(".", $token);
if(count($cltok)!==3) { die("xtok verification failed (format) - go back, refresh page and try again"); }
$signOk=base64url_encode(hash_hmac("sha256",$cltok[0].".".$cltok[1],$secret2,true));
if(!hash_equals($signOk,$cltok[2])) { die("xtok verification failed (signature) - go back, refresh page and try again"); }
$cook=base64url_decode($_COOKIE['xtok']);
if(strlen($cook)!=16) { die("xtok verification failed (decoded cookie len) - go back, refresh page and try again"); }
$signedStrOk=base64url_encode(hash("sha256",$cook."|".$namespace."|".$clientIp."|".$baseUrl."|".$verifiedLogin."|".$_SERVER["HTTP_USER_AGENT"]."|".hash("sha256",$secret2,true),true));
if(!hash_equals($signedStrOk,$cltok[0])) { die("xtok verification failed (claim) - go back, refresh page and try again"); }
if(!is_numeric($cltok[1]) || ($cltok[1]+3600<time())) { die("xtok verification failed (expired) - go back, refresh page and try again"); }
// setcookie("xtok", "", array("samesite"=>"Strict","secure"=>true,"httponly"=>true));
return(true);
}
function chk_xtok($namespace = "") {
return chk_xtok_tok($_REQUEST['xtok'], $namespace);
}
function contextDiff($dc) {
$dcout=array();
for($i=0; $i<count($dc); ++$i) {
if($dc[$i][1]==Diff::UNMODIFIED) {
if( ($i<count($dc)-1 && $dc[$i+1][1]!=Diff::UNMODIFIED) ||
($i<count($dc)-2 && $dc[$i+2][1]!=Diff::UNMODIFIED) ||
($i>0 && $dc[$i-1][1]!=Diff::UNMODIFIED) ||
($i>1 && $dc[$i-2][1]!=Diff::UNMODIFIED) )
$dcout[]=$dc[$i];
} else
$dcout[]=$dc[$i];
}
return($dcout);
}
function rmhtmltags($str) {
$n=strlen($str);
$s="";
$b=true;
for($i=0; $i<$n; $i++) {
$c=$str[$i];
if($c==='<') $b=false;
else if($c==='>') $b=true;
if($b && $c !== '>') $s.=$c;
}
return($s);
}