-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-deployment.php
More file actions
929 lines (774 loc) · 41.9 KB
/
git-deployment.php
File metadata and controls
929 lines (774 loc) · 41.9 KB
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
<?php
/***
Git deployment script example by UtilMind.
==========================================
!! WARNING !! Never deploy anything under 'root' privileges, automatically or manually !! Never deploy anything as user with 'sudoer' privilegy !!
@see https://github.com/utilmind/git-deployment/ The GitHub project
@author Oleksii Kuznietsov (utilmind) <utilmind@gmail.com>
QUICK START:
1. Rename this script into your project name.
2. Modify the configuration options below ($CONFIG), according to your environment.
(Don't forget to specify unique 'secret'. Use the same secret passphrase for your Git Webhook.)
3. Upload this script to your serer and point the URL to this script as WebHook.
If you did everything right, your web project will be automatically updated from Git on every `git push`.
All files and directory structure on your web server will be synchronized with the content in Git repository.
Everything will be mirrored, everything what supposed to be deleted will be deleted.
The good practice is to use code integrity checker, to monitor the code and inform administrator about all possible
modifications outside of the Git repository (inform about possible malicious code injections, hacks).
Use `code-integrity-checker.php` as example to monitor your live code.
IMPORTANT!
* -= You never need sudo to pull updates from Git. =-
If you think that you need to be a sudoer to use this script -- you're doing something wrong.
The web user should NEVER have a super-privileges. Otherwise your web app is critically vulnerable.
* Do not accidentally publish /.git directory. Keep it outside of any public_html's.
* Do not accidentally fetch/deploy the branch under 'root' privileges or some other users, different than web user (used by HTTP server).
No matter, manually or automatically. If this does happen, all further deployments may fail. Then the whole directory with .git branch
should be removed and redeployed from scratch.
* Make sure that `proc_open, proc_close` functions are available and not disabled (in `disable_functions` of `php.ini`).
CONTRIBUTORS to original branch:
* Don't require any other libraries. Use only standard functions.
MISCELLANEOUS TIPS:
* How to create Deploy key: https://docs.github.com/en/authentication/connecting-to-github-with-ssh/managing-deploy-keys#deploy-keys
Briefly...
1. Generate key:
ssh-keygen -t ed25519 -C "<email@address>" -f <key_file_name>
2. Add key to ssh-agent:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/<key_file_name>
3. Open /etc/ssh/ssh_config (or create new file in "/etc/ssh/ssh_config/ssh_config.d/" if your ssh_config including files in "ssh_config.d" directory, or use local config "~/.ssh/config")
Add some record like follows:
Host <git_hostname, eg. github.com or bitbucket.org>-<your_repository_name>
HostName <git_hostname, eg. github.com or bitbucket.org>
IdentityFile ~/.ssh/<key_file_name>
IdentitiesOnly yes
* Always generate SSH key for web user only (e.g. www-data or deamon, depending which username execute scripts in your HTTP server, depending which user executing this deployment script).
* Your deployment directory must be write-accessible for the web-user.
***/
// -- SHOW ALL ERRORS (even before the config)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// -- CONFIGURATION --
define('__HOME_DIR__', $_SERVER['HOME'] ?? '~'); // where /.ssh/known_hosts stored. NO TRAILING SLASH!
$CONFIG = [
'is_test' => false, // set to TRUE only to test, to skip authentication. Normally should be always FALSE.
'allow_init_new_git' => true, // allow to initialize new local .git repository, if 'git_dir' doesn't exists. (Find 'git_dir' option below.)
'log_output' => true, // log file name is 'this_script_name.log'.
// !! Don't keep any secrets and passwords in Git, use some environment variable instead.
'secret' => '< Your $uper $ekret PaSsPhrase >', // use long passphrases with the mix of alphanumeric and special ASCII characters!
'git_host' => 'github.com', // don't change if we fetching repo from GitHub. This domain adding to "~/.ssh/known_hosts" on first fetching.
'git_addr' => 'git@github-REPO_NAME', // Look how exactly the hostname specified for certain key in /etc/ssh/ssh_config (or ~/.ssh/config). Name in config may differ from repository name.
'repo_name' => 'YOUR_REPO_NAME',
'repo_username' => 'YOUR_USERNAME',
'remote_name' => 'origin',
'def_branch' => 'master', // only for test mode. It automatically determinates the branch name from Git.
'allowed_branches' => [ // Use allowed branches for security, to not let to allow deployment of garbage branches or branches with garbage names.
// If you specify just string(s) with branch names, they will be deployed by path specified in $CONFIG['target_dir']
'master',
'main',
// Specify the exact path for each listed branch, to deploy it by the path other than specified in $CONFIG['def_target_dir'].
'staging' => '/path/to/published/project/main',
], // 'production', 'debug'],
'def_target_dir'=> '/path/to/published/project', // The exact path to a directory with the published project.
// ALL branches specified in "allowed_branches" without individual paths will be deployed into this directory.
// IMPORTANT!! Must be writeable for web user! Idealy do `sudo chown [www-data] [target_dir]`.
// You will need to set up write permission for the following directories.
// Get web username with $_SERVER['LOGNAME'] ?? $_SERVER['USER'] ?? $_SERVER['USERNAME']; // (from $_SERVER['USER'] on Ubuntu/Nginx).
'git_dir' => __HOME_DIR__.'/repo/name', // + the /branch_name/ will be added automatically to this path
'log_dir' => __HOME_DIR__.'/logs/', // must have trailing /. Make sure that it's writeable for the web user (e.g. www-data, daemon)
// Uncomment the following line if web-user has no home directory and ~/.ssh/[private_key] can't be found.
//'private_key' => __HOME_DIR__.'/.ssh/private_key_file_name',
'known_hosts' => __HOME_DIR__.'/.ssh/known_hosts', // location of "known_hosts". Use full path, ~ in '~/.ssh/known_hosts' is not interpreted by PHP. Usually specified path should not be changed. We adding the fingerprint of 'git_host' into the list of known_hosts to avoid confirmation via CLI.
// --- Post-deploy cleanup: remove files by suffix (glob-style), e.g. '.src.js' => removes '*.src.js'
// IMPORTANT: keep this list strict; these files will be deleted from the deployed tree after each deploy.
'forbidden_file_names' => [ // Exact file names or exact PATHS and filenames if starts with / (path relative to the target deployment directory).
//'/.gitignore', // Don't delete .gitingore if you monitor the integrity of deployment. Otherwise you will see all untracked files which supposed to be ignored.
'/.gitattributes',
'/.dockerignore',
'/.eslintrc',
'/.npmrc',
'/.nvmrc',
'/gulpfile.js',
],
'forbidden_file_suffixes' => [ // *.extension
'.md',
'.sql',
'.bat',
'.sh',
'.bak',
'.src.js',
'.src.css',
'.map',
'.log', // Be careful with logs. They are useful, but only when kept outside of the 'public_html`.
// However block the possibility to download logs and extensions above with your HTTP server configuration.
// Don't remove .txt files if you don't want to remove your 'robots.txt'.
],
// Directories (relative to $target_dir) where forbidden suffixes will be searched and removed.
// Use [''] to scan the whole target directory.
'forbidden_scan_dirs' => ['www'], // 'www' or 'public_html', any public directory
'commit_deployed_snapshot' => true, // commit deployed snapshot after all cleanup operations, for further integrity checks.
];
// -- No output buffering. Output immediately
@ini_set('output_buffering', 0);
@ini_set('zlib.output_compression', 0);
@ini_set('session.use_trans_sid', 0); // produce warning if session is active
ob_implicit_flush(1);
@ob_end_flush(); // it doesn't works (returns notice) on my local Windows PC, but required to start output without buffering
set_time_limit(900); // +15 minutes for execution. (Extend later if required!)
header('Content-type: text/plain'); // no HTML-formatting for output
ob_start(); // to catch all errors
// -- FUNCTIONS --
function strip_leading_slash($path) {
return ltrim($path, '/\\ ');
}
function strip_trailing_slash($path) {
return rtrim($path, '/\\ ');
}
function add_trailing_slash($path) {
return strip_trailing_slash($path) . DIRECTORY_SEPARATOR;
} // * remove trailing slash with: rtrim($str, '/\\ ');
/**
* Build map: branch => target_dir.
*
* Supports allowed_branches as:
* - list of strings: ['master', 'beta'] -> deployed into $def_target_dir
* - map of branch => target_dir: ['staging' => '/var/www/sc-staging']
* - mixed.
*
* Returned value example:
* [
* 'master' => '/var/www/sc',
* 'staging' => '/var/www/sc-staging'
* ]
*/
function build_branch_targets(array $allowed_branches, string $def_target_dir) { // returns array
$targets = [];
$def_target_dir = strip_trailing_slash($def_target_dir);
foreach ($allowed_branches as $k => $v) {
if (is_int($k)) { // ['master', 'main] -- to default target directory
$branch = trim((string)$v);
$dir = $def_target_dir;
}else { // ['staging' => '/var/www/staging'] -- to individual directory
$branch = trim((string)$k);
$dir = strip_trailing_slash((string)$v);
}
if ($branch) {
$targets[$branch] = $dir ?: $def_target_dir;
}
}
return $targets; // returns array
}
/**
* Get request headers in a portable way (Apache, Nginx, FPM, CGI).
* Returns array with LOWERCASED keys.
*/
function get_request_headers_lowercased() { // returns array
$headers = [];
// Try getallheaders() if available and returns something
// Headers not available if HTTP server (Apache, Nginx+PHP-FPM or some FastCGI) did not parse them. getallheaders() is Apache-only (mod_php).
if (function_exists('getallheaders')) {
$tmp = getallheaders();
if (is_array($tmp) && !empty($tmp)) {
foreach ($tmp as $k => $v) {
$headers[strtolower($k)] = $v;
}
return $headers;
}
}
// Fallback: build from $_SERVER
foreach ($_SERVER as $key => $value) {
if (0 === strpos($key, 'HTTP_')) {
// HTTP_X_GITHUB_EVENT -> x-github-event
$name = strtolower(str_replace('_', '-', substr($key, 5)));
$headers[$name] = $value;
}elseif ('CONTENT_TYPE' === $key) {
$headers['content-type'] = $value;
}elseif ('CONTENT_LENGTH' === $key) {
$headers['content-length'] = $value;
}
}
return $headers; // returns array
}
// Write to log + output as text
function print_log($msg, $http_exit_code = 0) { // if $http_exit_code specified, then script terminating (exiting).
global $CONFIG, $out, $log_name;
$msg.= "\n";
$out.= $msg;
if ($CONFIG['log_output']) {
static $is_first_output = true; // AK: we want to log IP and date in start.
$log = $msg;
// IP and date are only for the log file. They are not needed in stdout.
if ($is_first_output) {
$is_first_output = false;
$log = 'IP: '.get_ip().', '.date('r')."\n$log"; // we output this when the process starts or on authentication errors.
}
if ($http_exit_code) {
$log .= "\n"; // one more line separator in log
}
file_put_contents("$CONFIG[log_dir]$log_name.log", $log, FILE_APPEND);
}
// Terminate if any $http_exit_code specified.
if ($http_exit_code && (200 !== $http_exit_code)) {
http_response_code($http_exit_code);
}
echo $msg; // after possible http_response_code(), after headers sent
if ($http_exit_code) {
exit;
}
}
// Execute command + output and log the result.
// Return value is result code
function exec_log($command, $ignore_empty_stdout = false, $debug_stderr = false,
$ok_codes = null, // codes considered as successful. 0 is default, if not provided.
&$stdout_capture = null, &$stderr_capture = null) {
print_log('>> '.$command);
if (null === $ok_codes) {
$ok_codes = [0];
}
$proc = null; // we use it in `finally`, but it can be uninited if proc_open() fails.
$pipes = [];
try { // We could use 'exec($command, $stdout, $result_code);', but we'd like to catch STDERR too.
$proc = proc_open($command, [
1 => ['pipe', 'w'], // STDOUT
2 => ['pipe', 'w'], // STDERR
], $pipes);
if (!is_resource($proc)) {
// proc_open failed (disabled, permission, wrong command, etc.)
print_log("FATAL: proc_open failed for '$command'.", 500);
return 500; // or throw new RuntimeException(...)
}
// Reading STDOUT
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
if ($debug_stderr) {
// AK 2024-08-07: I had issue with getting error stream on 'git fetch'. Reason unknown, all file permissions was ok.
// Solved after commenting out ob_start() and ob_end_flush() in the response to GitHub. But let's keep this debug block for while, maybe it will be useful...
print_log('Getting error stream...');
// Set the timeout and non-blocking mode
stream_set_timeout($pipes[2], 5); // Timeout in seconds
stream_set_blocking($pipes[2], false); // Non-blocking mode
// Initializing STDERR to read stream by chunks
$stderr = '';
$start_time = time();
// Reading STDERR with timeout checking
while (!feof($pipes[2])) {
$stderr .= fread($pipes[2], 8192);
$info = stream_get_meta_data($pipes[2]);
if ($info['timed_out']) {
print_log('Timeout occurred while reading from pipe.');
break;
}
// Additional check to stop the loop if automatic timeout failed
if (6 < time() - $start_time) { // AK: I think 6 seconds is enough. But feel free to adjust.
print_log('Manual timeout occurred.');
break;
}
}
print_log('Error stream received.');
}else {
$stderr = stream_get_contents($pipes[2]);
}
fclose($pipes[2]);
// Provide captured output to caller (even if empty)
if (null !== $stdout_capture) {
$stdout_capture = $stdout;
}
if (null !== $stderr_capture) {
$stderr_capture = $stderr;
}
}catch (Exception $e) {
print_log("FATAL: failure on '$command'.", 500);
}finally { // supported starting from PHP 5.5. If you can't use it -- just comment out 'finally' line and more proc_close() outside of 'finally'.
$result_code = is_resource($proc)
? proc_close($proc)
: 1;
}
// no sense to output $result_code here, it's always 0 (success) here.
if (!empty($stderr)) { // Let's show errors first
print_log('<< '.$stderr);
}
if (!empty($stdout)) {
print_log($stdout);
}
if (!in_array($result_code, $ok_codes, true)) { // default OK code is 0; override via $ok_codes
if (127 === $result_code) {
print_log("ERROR: '$command' can't be executed. Command not found or not installed. Exiting.", 500); // nothing to execute?
}
if (!$stdout) {
print_log("ERROR: '$command' not executed? Empty output. Return value: $result_code.", $ignore_empty_stdout ? null : 500);
}
}
return $result_code;
}
function ensure_known_host(string $host, string $known_hosts_file): void {
// Ensure directory exists (best-effort)
$dir = dirname($known_hosts_file);
if (!is_dir($dir)) {
@mkdir($dir, 0700, true);
}
// Create file if missing (best-effort)
if (!file_exists($known_hosts_file)) {
@touch($known_hosts_file);
@chmod($known_hosts_file, 0644);
}
// Check if host already present (ssh-keygen -F exits 0 if found)
$cmd_check = 'ssh-keygen -F ' . escapeshellarg($host) . ' -f ' . escapeshellarg($known_hosts_file) . ' >/dev/null 2>&1';
$ret = exec_log($cmd_check);
if (0 !== $ret) {
// Add hashed host entry (-H) to avoid duplicates + reduce exposure of hostnames list.
exec_log('ssh-keyscan -H ' . escapeshellarg($host) . ' >> ' . escapeshellarg($known_hosts_file));
}
}
/* Returns string representation of IP. It can either IPv6 OR IPv4 format.
Maximum length of returned value is 45 characters.
Note: the type of determined IP depends on server. The same script can work differently on different server.
Some servers addresses IPv6 representation only, some in both IPv4 and IPv6. It's not related to PHP. Check the settings of your HTTP server.
See also
IP functions: https://dev.mysql.com/doc/refman/5.6/en/miscellaneous-functions.html
How to store IP as binary: https://dev.mysql.com/blog-archive/mysql-8-0-storing-ipv6/
*/
function get_ip() {
if (!empty($_SERVER['HTTP_CLIENT_IP']) && (4 < strlen($_SERVER['HTTP_CLIENT_IP']))) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && (4 < strlen($_SERVER['HTTP_X_FORWARDED_FOR']))) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else {
$ip = $_SERVER['REMOTE_ADDR'] ?? false;
}
if (!$ip) {
return '0.0.0.0'; // It's '0:0:0:0:0:ffff:0:0' in IPv6, but this is impossible situation, so we don't care.
}
$ip = false !== ($p = strpos($ip, ','))
? substr($ip, 0, $p)
: $ip;
// Log4j JNDI Attack? IP can look like the follows: ${jndi:ldap://${:-126}${:-178}.${hostName}.xforwardedfor.cpkj12ja2d9cud2sd53084m68qyho39is.oast.me}
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
http_response_code(400);
die('400 Bad request');
}
return $ip;
}
// -- GO! --
$this_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($_SERVER['PHP_SELF']));
$branch = $CONFIG['def_branch']; // default, while it's not determined yet.
$CONFIG['log_dir'] = add_trailing_slash($CONFIG['log_dir'] ?? __DIR__.'/logs');
if (!is_dir($CONFIG['log_dir'])) {
@mkdir($CONFIG['log_dir'], 0775, true);
}
// VALIDATION... (We don't want to give any output before request validated. Except errors, of course.)
if (!$CONFIG['is_test']) {
$log_name = $this_name.'-authentication-error';
// Check HTTP headers
$headers = get_request_headers_lowercased();
if (count($headers)) {
if ($CONFIG['log_output']) {
file_put_contents("$CONFIG[log_dir]$this_name-request-headers.log",
print_r($headers, true)
// if have POSTed payload (e.g. from GitHub)
. (isset($payload)
? "\n-- Payload:\n".print_r($payload, true)
: '')
);
}
// make header keys lowercase (they are case insetive according to RFC 2616), and sometimes GitHub may send headers with different characters case.
foreach ($headers as $k => $v) {
unset($headers[$k]);
$headers[strtolower($k)] = $v;
}
}
// Check POSTed data and headers
switch ($CONFIG['git_host']) {
case 'github.com':
// Headers
if (!$service_event = ($headers['x-github-event'] ?? false)) {
print_log('No service event', 400);
}
if ($is_push = 'push' === $service_event) {
if (!isset($_POST['payload']) || (!$payload = json_decode($_POST['payload'], true)) || empty($payload['ref'])) {
print_log("Bad request: no payload or bad payload.\n\$_POST:\n".print_r($_POST, true)."\nHEADERS:\n".print_r($headers, true), 400);
}
// Detect branch from Payload on GitHub.
$ref = explode('/', $payload['ref']);
if (!$branch = end($ref)) {
print_log('No branch', 400);
}
}
break;
case 'bitbucket.org': // 'bitbucket.org' doesn't POST anything. We can determinate branch from php://input
// Headers
if (!$service_event = ($headers['x-event-key'] ?? false)) {
print_log('No service event', 400);
}
if ($is_push = 'repo:push' === $service_event) {
// On BitBucket the branch name can be detected only from input JSON...
$detect_branch = true;
}
break;
default:
print_log('Unsupported service.', 400);
}
if (!$is_push) {
print_log('Wrong service event: '.$service_event, 400);
}
if (!$input = file_get_contents('php://input')) {
print_log('No input', 400);
}
if ($CONFIG['log_output']) {
file_put_contents("$CONFIG[log_dir]$this_name-request-input.log", $input);
}
// Verify signature
$signature = trim($headers['x-hub-signature-256'] ?? $headers['x-hub-signature'] ?? '');
if ('' === $signature) {
print_log('Unauthorized: missing signature', 401);
}
// Auto-detect algorithm (although it's 'sha256').
if (0 === strpos($signature, 'sha256=')) {
$algo = 'sha256';
}elseif (0 === strpos($signature, 'sha1=')) {
$algo = 'sha1';
}else {
print_log('Unauthorized: unknown signature algorithm', 401);
}
$expected = $algo . '=' . hash_hmac($algo, $input, $CONFIG['secret']);
if (!hash_equals($expected, $signature)) {
print_log('Unauthorized: invalid signature', 401);
}
// Determinate branch by input, if it's not known yet.
if (isset($detect_branch)) {
$data = json_decode($input, true);
switch ($CONFIG['git_host']) {
case 'bitbucket.org': // 'bitbucket.org' doesn't POST anything. We can determinate branch from php://input
if (isset($data['push']['changes'][0]['new']['name'])) {
$branch = $data['push']['changes'][0]['new']['name'];
} // otherwise just use default branch
break;
}
}
// -- RETURN --
// Return output to Git before the actual script execution. Idea: https://stackoverflow.com/questions/1019867/is-there-a-way-to-use-shell-exec-without-waiting-for-the-command-to-complete
ignore_user_abort(true);
ob_end_flush();
header('Connection: close'); // mb also header('Content-Length: 0'), but this is wrong. Apache terminates connection and close STDOUT buffer after getting these headers.
flush(); // AK: but there is nothing to flush?
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
} // end if $CONFIG['is_test']
// Starting the process (authentication was successful already)
if ($CONFIG['log_output']) {
$log_name = $this_name.'-'.$branch; // base name w/o extension. (We assume that extension is .php or .php5 or something... 3-4 characters.) + branch name.
@unlink(__DIR__."/$log_name.log"); // clearing previous log
}
$current_user = $_SERVER['LOGNAME'] ?? $_SERVER['USER'] ?? $_SERVER['USERNAME'] ?? '';
if (!$current_user) { // It can be still not defined on Apache.
exec('whoami', $whoami, $retval); // only if exec() is not disabled
$current_user = $whoami[0];
}
// Resolve target directory for this branch (default or per-branch override).
// allowed_branches supports both:
// - ['master', 'main'] -> def_target_dir
// - ['staging' => '/var/www/sc-staging'] -> custom target
$target_dir = $CONFIG['def_target_dir'] ?? '';
if ('' === $target_dir) {
print_log('Configuration error: `def_target_dir` is empty.', 500);
}
$branch_targets = build_branch_targets(is_array($CONFIG['allowed_branches']) ? $CONFIG['allowed_branches'] : [], $target_dir);
if (isset($branch_targets[$branch])) {
$target_dir = $branch_targets[$branch];
}elseif (!empty($CONFIG['allowed_branches'])) {
print_log('Branch not allowed: ' . $branch, 403);
}
// deploy lock
$deploy_lock_fn = '/tmp/deploylock_' . hash('sha256', $target_dir) . '.lock';
$lock_fp = fopen($deploy_lock_fn, 'c');
if (!$lock_fp) {
throw new Exception("Can't open lock file: $deploy_lock_fn");
}
if (!flock($lock_fp, LOCK_EX | LOCK_NB)) {
print_log("Deployment lock already exists: `$deploy_lock_fn` (age: $age_str). Aborting this deploy.", 423);
}
// Create lock file with some metadata as early as possible.
ftruncate($lock_fp, 0);
fwrite($lock_fp, json_encode([
'time' => date('c'),
'target' => $target_dir,
'branch' => $branch,
'user' => $current_user,
'remote' => $CONFIG['remote_name'] ?? '',
'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
], JSON_UNESCAPED_SLASHES));
// Bitbucket wants some output immediately. So giving this before starting output buffer...
print_log("Starting deployment of `$branch` branch into `$target_dir` as user `$current_user`...");
$start_time = microtime(true);
ob_start(); // to catch all further errors
try {
// Path to private key can be specified if system can't find its location. E.g. if key stored in some custom location for web-user w/o home directory.
if (!empty($CONFIG['private_key'])) {
// This points where the private key and `known_hosts` are stored.
putenv('GIT_SSH_COMMAND='
. 'ssh'
. ' -i ' . escapeshellarg($CONFIG['private_key'])
. ' -o UserKnownHostsFile=' . escapeshellarg($CONFIG['known_hosts'])
. ' -o IdentitiesOnly=yes'
. ' -o StrictHostKeyChecking=yes'
);
}
$git_dir = add_trailing_slash($CONFIG['git_dir']).$branch;
$git_dir_git = $git_dir . '/.git';
$git_dir_git_esc = escapeshellarg($git_dir_git);
if (!is_dir($git_dir_git)) {
if ($CONFIG['allow_init_new_git']) {
exec_log('git init ' . escapeshellarg($git_dir));
/* $CONFIG[git_addr]-$CONFIG[repo_name] is the record in your /etc/ssh/ssh_config (or ~/.ssh/config).
The typical record looks like follows:
Host bitbucket.org-repository_name
HostName bitbucket.org
IdentityFile ~/.ssh/id_ed25519_keyname
IdentitiesOnly yes
Host github-repository_name
HostName github.com
User git
IdentityFile /home/deploy/.ssh/keyname-id_ed25519
IdentitiesOnly yes
UserKnownHostsFile /home/deploy/.ssh/known_hosts
StrictHostKeyChecking yes
In some cases you may need just [git_addr], like 'git@github' w/o -[repo_name]. Use exact host as it specified in ssh config.
*/
$git_addr = $CONFIG['git_addr'] ?? '';
$repo_name = $CONFIG['repo_name'] ?? '';
$repo_user = $CONFIG['repo_username'] ?? '';
if ($git_addr === '' || $repo_user === '' || $repo_name === '') {
print_log("Configuration error: git_addr/repo_username/repo_name must be set. git_addr='$git_addr', repo_username='$repo_user', repo_name='$repo_name'", 500);
}
$remote_url = escapeshellarg($git_addr . ':' . $repo_user . '/' . $repo_name . '.git');
$remote = escapeshellarg($CONFIG['remote_name']);
$ret_val = exec_log("git --git-dir=$git_dir_git_esc remote get-url $remote >/dev/null 2>&1"
. " && git --git-dir=$git_dir_git_esc remote set-url $remote $remote_url"
. " || git --git-dir=$git_dir_git_esc remote add $remote $remote_url"); // add origin (or whatever 'remote_name')
// Check, whether 'git_host' already listed in "~/.ssh/known_hosts"... (must be writeable for $current_user!!)
// Add GitHub (or another host for repository) to the list of known_hosts, so it will not ask to confirm fingerprint in CLI.
// Read more about auto-confirmation for the fingerprint on https://serverfault.com/questions/447028/non-interactive-git-clone-ssh-fingerprint-prompt
ensure_known_host($CONFIG['git_host'], $CONFIG['known_hosts']);
}else {
print_log("Local .git directory doesn't exist in '$git_dir'. Please initialize local Git repository first, with specifying the remote origin, or allow initialization of new Git in the configuration.", 500);
}
}
// Fetch updates
// AK 2024-08-07: execution of this command stopped for unknown reason (solved by commenting out ob_start()/ob_end_flush()), but use exec_log(command, TRUE) to debug error stream.
$fetch_result = exec_log("git --git-dir=$git_dir_git_esc fetch ".escapeshellarg($CONFIG['remote_name']));
if (0 !== $fetch_result) {
print_log("Git Fetch failed with exit code $fetch_result.");
if (128 === $fetch_result) {
print_log("Exit code 128 usually means that security credentials are invalid. CHECK YOUR DEPLOYMENT KEY! Is it listed in ~/.ssh? Access granted for 'ssh_config'? Is the key prepared for user $current_user?");
}
}
$target_dir_esc = escapeshellarg($target_dir);
// ...We could PULL updates, but let's better do the "hard reset" to refresh EVERYTHING (if needed), not only updated stuff
// $ret_val = exec_log("git --git-dir=\"$git_dir/.git\" --work-tree=\"$CONFIG[def_target_dir]\" pull $CONFIG[remote_name] $branch");
// ...Do HARD RESET, to fully synchronize our deployment with Git...
$ret_val = exec_log('git --git-dir=' . escapeshellarg($git_dir . '/.git') . " --work-tree=$target_dir_esc reset --hard " . escapeshellarg('origin/' . $branch));
// Alternative if --work-tree doesn't works for any reason, e.g. if Permission denied on chdir. Just make $target_dir as current directory then. Although --work-tree considered as more caninical.
//$ret_val = exec_log('git --git-dir=' . escapeshellarg($git_dir . '/.git') . " -C $target_dir_esc reset --hard " . escapeshellarg('origin/' . $branch));
// Done
print_log("'hard reset' finished with code $ret_val in ".number_format(microtime(1) - $start_time, 3).' seconds.'); // $ret_val 0 is good!
// Switch to the correct branch for sure. It will respond something like "Already on 'master'" and this is fine.
// UPD. We actually don't need this. We don't switch branches, so it's useless.
//exec_log('git checkout ' . escapeshellarg($branch));
// Also if we need to set up the branch to work with (could be useful after initial hard reset)
//exec_log('git branch --set-upstream-to='.escapeshellarg($CONFIG['remote_name'].'/'.$branch).' '.escapeshellarg($branch));
// REMOVE DEPLOYED GARBAGE
// =======================
// chdir($target_dir);
// Consider 'git clean -fd' to remove untracked files.
//
// Delete directory
//exec_log('rm -rf '.escapeshellarg("$target_dir/website/DIRECTORY_NAME"));
// Delete .htaccess in target_dir and all subdirectories if you're running Nginx server. (We may use .htaccess in local environement, but don't need .htaccess on production Nginx.)
//exec_log('find ' . escapeshellarg("$target_dir/website/") . " -type f -name '.htaccess' -exec rm -f {} \\;");
// Delete README.md and possible .sql files. But better use 'forbidden_file_suffixes' configuration.
//exec_log('find ' . escapeshellarg("$target_dir/") . " \\( -name '*.md' -o -name '*.sql' \\) -type f -exec rm -f {} \\;");
// Delete forbidden files by configured exact names.
// ================================================
// Supports two formats in $CONFIG['forbidden_file_names']:
// 1) Absolute-from-target paths (starting with '/'), e.g. '/.gitignore' or '/www/.env'
// -> deletes exactly $target_dir + that path.
// 2) Plain file names without any slashes, e.g. '.gitignore', 'README.md'
// -> deletes files with that name under each directory from 'forbidden_scan_dirs'.
$names_cfg = $CONFIG['forbidden_file_names'] ?? null;
if (!empty($names_cfg) && is_array($names_cfg)) {
$scan_dirs = $CONFIG['forbidden_scan_dirs'] ?? ['www'];
foreach ($names_cfg as $name) {
$name = trim((string)$name);
if ('' === $name) {
continue;
}
// Case 1: path starting with '/', treated as exact path relative to target_dir
if ('/' === $name[0] || '\\\\' === $name[0]) {
// Security: reject path traversal and weird chars
if (false !== strpos($name, '..')) {
print_log("Skipping forbidden file path with '..': $name");
continue;
}
if (!preg_match('#^[/\\\\][A-Za-z0-9._\\-/\\\\]+$#', $name)) {
print_log("Skipping unsafe forbidden file path: $name");
continue;
}
$full = strip_trailing_slash($target_dir) . DIRECTORY_SEPARATOR . strip_leading_slash($name);
$full_esc = escapeshellarg($full);
// Remove file if exists (file or symlink). Using shell rm because open_basedir may not include $target_dir.
exec_log("if [ -e $full_esc ] || [ -L $full_esc ]; then rm -f $full_esc; fi");
continue;
}
// Case 2: plain file name (no slashes) - search and remove in scan dirs
if (false !== strpos($name, '/') || false !== strpos($name, '\\\\')) {
print_log("Skipping forbidden file name containing slashes (use leading '/' for exact path): $name");
continue;
}
// Security: allow only simple file names like '.gitignore', 'README.md'
if (!preg_match('/^[A-Za-z0-9._-]+$/', $name)) {
print_log("Skipping unsafe forbidden file name: $name");
continue;
}
foreach ($scan_dirs as $rel_dir) {
$rel_dir = trim((string)$rel_dir);
$dir = strip_trailing_slash($target_dir);
if ('' !== $rel_dir) {
$dir .= DIRECTORY_SEPARATOR . strip_leading_slash($rel_dir);
}
$dir_esc = escapeshellarg($dir);
$nm_esc = escapeshellarg($name);
exec_log("find $dir_esc -type f -name $nm_esc -exec rm -f {} \\;");
}
}
}
// Delete forbidden files by configured suffixes.
// ==============================================
// Example suffix: '.src.js' will delete '*.src.js'.
$suffixes = $CONFIG['forbidden_file_suffixes'] ?? null;
if (!empty($suffixes) && is_array($suffixes)) {
$safe_suffixes = [];
foreach ($suffixes as $suf) {
$suf = trim((string)$suf);
if ('' === $suf) {
continue;
}
// Safety: allow only simple suffixes like '.src.js', '.bak', '.map'.
if (!preg_match('/^[A-Za-z0-9._-]+$/', $suf)) {
print_log("Skipping unsafe forbidden suffix: $suf");
continue;
}
$safe_suffixes[] = $suf;
}
$safe_suffixes = array_values(array_unique($safe_suffixes));
if ($safe_suffixes) {
$scan_dirs = $CONFIG['forbidden_scan_dirs'] ?? [''];
foreach ($scan_dirs as $rel_dir) {
$rel_dir = trim((string)$rel_dir);
$dir = strip_trailing_slash($target_dir);
if ('' !== $rel_dir) {
$dir .= DIRECTORY_SEPARATOR . strip_leading_slash($rel_dir);
}
$dir_esc = escapeshellarg($dir);
$expr = [];
foreach ($safe_suffixes as $suf) {
$expr[] = '-name '.escapeshellarg('*'.$suf);
}
$names = '\( '.implode(' -o ', $expr).' \)';
exec_log("find $dir_esc $names -type f -exec rm -f {} \\;");
}
}
}
/*
function change_dir_permission(string $dir_name, string $file_ext, int $permission): void {
// Make all .SH-files (except hidden) in /tools/ directory executable.
if ($dir_handle = opendir($dir_name)) {
try {
while (false !== ($entry = readdir($dir_handle))) {
if ('.' === $entry[0]) { // skip all directories and system (hidden) files
continue;
}
if (is_dir($fn = $dir_name . DIRECTORY_SEPARATOR . $entry)) {
change_dir_permission($fn, $file_ext, $permission);
// Only if file has .sh extension
}elseif ($file_ext === pathinfo($entry, PATHINFO_EXTENSION)) {
$permission_str = sprintf('%04o', $permission); // dec to oct
// Update access privileges
print_log(chmod($fn, $permission)
? "$permission_str privileges applied for $fn"
: "ERROR on setting $permission_str privileges for $fn");
}
}
}finally {
closedir($dir_handle);
}
}else {
print_log("Can't open $dir_name");
}
}
change_dir_permission("$target_dir/tools", 'sh', 0755);
*/
// Execute something to increase version in some environment variable
//exec_log('php '.escapeshellarg(__DIR__.'/inc_php_var.php').' '.escapeshellarg("$target_dir/.credentials.php")." \\\$ext_script_ver v=");
//print_log('Cleared some garbage and increased version number.');
//if ('master' === $branch && empty($_POST['admin-key'])) { // if this is not manual re-deployment
// ... send notification to Telegram or Slack or email.
//}
// Commit deployed snapshot (local-only, never pushed).
if ($CONFIG['commit_deployed_snapshot']) {
// This fixes the "dirty work-tree" after post-deploy cleanup/customizations,
// so integrity monitoring can rely on `git status --porcelain`.
//
// Notes:
// - We stage everything (including deletions) with `git add -A`.
// - Then we check whether index differs from HEAD via `git diff --cached --quiet`:
// rc=0 -> nothing staged; rc=1 -> there are staged changes; rc>1 -> error.
// - Commit is local-only and will be discarded on the next deploy by `git reset --hard origin/<branch>`.
exec_log("git --git-dir=$git_dir_git_esc --work-tree=$target_dir_esc add -A", true);
// Decide whether we need a commit without relying on stdout parsing.
$diff_rc = exec_log(
"git --git-dir=$git_dir_git_esc --work-tree=$target_dir_esc diff --cached --quiet",
true, // ignore empty stdout
false, // no special stderr debug
[0, 1] // rc=1 means "differences found" (expected)
);
print_log("Staged diff rc=$diff_rc (0=nothing to commit, 1=have changes).");
// Log porcelain for visibility
$porcelain_rc = exec_log("git --git-dir=$git_dir_git_esc --work-tree=$target_dir_esc status --porcelain", true);
if (1 === $diff_rc) {
$commit_msg = 'Deploy snapshot ' . gmdate('Y-m-d\TH:i:s\Z') . ' (' . $branch . ')';
// Provide identity via -c to avoid relying on global git config on the server.
// AK: don't pay attention that this is commit to 'master' branch. This is internal anyway and will never be pushed. Also anyway we doing hard reset on each deployment.
// If you want it accurately be deployed to separate branch, restore the following: https://github.com/utilmind/git-deployment/commit/7ce6daf203e388bd15fa8415f22835b498fc60b2
$commit_cmd = "git --git-dir=$git_dir_git_esc --work-tree=$target_dir_esc"
. ' -c user.name=deploy-bot -c user.email=deploy-bot@localhost'
. ' commit --no-verify --no-gpg-sign -m ' . escapeshellarg($commit_msg);
$commit_rc = exec_log($commit_cmd, true);
print_log("Snapshot commit rc=$commit_rc.");
// Debug: ensure work-tree is clean after commit.
$after_out = '';
$after_rc = exec_log(
"git --git-dir=$git_dir_git_esc --work-tree=$target_dir_esc status --porcelain",
true, // ignore empty stdout
false, // no special stderr debug
null, // default
$after_out
);
if (0 === $after_rc && '' !== trim($after_out)) {
print_log("WARNING: Work-tree still dirty after snapshot commit:\n" . $after_out);
}
}elseif (0 === $diff_rc) {
print_log('No staged changes detected; snapshot commit skipped.');
}else {
print_log("WARNING: Can't determine staged diff (rc=$diff_rc). Snapshot commit skipped.");
}
}
print_log('Done in '.number_format(microtime(true) - $start_time, 3).' sec.', 200); // exit with "200 OK".
}finally {
flock($lock_fp, LOCK_UN);
fclose($lock_fp);
// get all stdout to write into log
$out = ob_get_contents();
ob_end_clean();
echo $out;
file_put_contents("$CONFIG[log_dir]$log_name-stdout.log", $out);
}