forked from stereum-dev/ethereum-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeConnection.js
executable file
·2344 lines (2150 loc) · 94 KB
/
NodeConnection.js
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { SSHService } from "./SSHService";
import { StringUtils } from "./StringUtils";
import { nodeOS } from "./NodeOS";
import { ServiceVolume } from "./ethereum-services/ServiceVolume";
import net from "net";
import YAML from "yaml";
import { NodeUpdates } from "./NodeUpdates";
import { ConfigManager } from "./ConfigManager";
import axios from "axios";
const log = require("electron-log");
const electron = require("electron");
const Evilscan = require("evilscan");
const os = require("os");
async function Sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
if (process.env.IS_DEV === "true" || process.env.NODE_ENV === "test") {
global.branch = "main";
log.info("pulling from main branch");
} else {
global.branch = undefined;
}
export class NodeConnection {
constructor(nodeConnectionParams) {
this.sshService = new SSHService();
this.nodeConnectionParams = nodeConnectionParams;
this.os = null;
this.osv = null;
this.nodeUpdates = new NodeUpdates(this);
this.configManager = new ConfigManager(this);
}
async establish(taskManager, currentWindow) {
try {
if (this.sshService.connectionPool.length > 0) {
await this.sshService.disconnect(true);
}
await this.sshService.connect(this.nodeConnectionParams, currentWindow);
this.sshService.addingConnection = true;
await this.findStereumSettings();
this.taskManager = taskManager;
} catch (error) {
throw new Error(error);
}
}
/**
* identify the operating system of the connected node
*/
async findOS() {
// Run the command without sudo wrapper
let osName = null;
let osVersion = null;
const uname = await this.sshService.exec("cat /etc/*-release", null, false);
log.debug("result uname: ", uname);
if (uname.rc == 0 && uname.stdout) {
const regex = /VERSION_ID="([^"]+)"/;
const match = uname.stdout.match(regex);
const versionId = match ? match[1] : null;
if (uname.stdout.toLowerCase().search("centos") >= 0) {
log.debug(`setting centos, version ${versionId}`);
osName = nodeOS.centos;
osVersion = versionId;
} else if (uname.stdout.toLowerCase().search("ubuntu") >= 0) {
log.debug(`setting ubuntu, version ${versionId}`);
osName = nodeOS.ubuntu;
osVersion = versionId;
}
}
this.os = osName;
this.osv = osVersion;
return { name: osName, version: osVersion };
}
/**
* identify the sudo permission of the connected node
*/
async checkSudo() {
// Create the command that will be executed on the node to check sudo perms
let cmd = `
# Check if user is root
if [ $(id -u -n) == "root" ]; then
echo "SUCCESS: user can sudo without password because he is root"
exit 0
fi
# Check if users needs a password for sudo
msg=$(sudo hostname 2>&1)
if [[ "$msg" == *"sudo: a password is required"* ]]; then
echo "FAIL: user can not sudo without password!"
exit 1
fi
# Success
echo "SUCCESS: user can sudo without password"
exit 0
`;
// Run the command (without sudo wrapper!)
let result = await this.sshService.exec(cmd, null, false);
// No data in stdout or data in stderr? Executed code above failed to run!
if (result.stdout == "" || result.stderr != "") {
result.rc = 2;
result.stdout = "ERROR: Executed code failed to run";
if (result.stderr != "") {
result.stdout += " (" + result.stderr + ")";
} else if (result.stdout == "") {
result.stdout += " (syntax error)";
}
}
// Return the result
return result;
}
/**
* read stereum settings and make them accessible
*/
async findStereumSettings() {
const stereumConfig = await this.sshService.exec("cat /etc/stereum/stereum.yaml");
if (stereumConfig.rc == 0) {
this.settings = {
stereum: YAML.parse(stereumConfig.stdout).stereum_settings,
};
}
}
/**
* Prepare a fresh server to run stereum services on it
*/
async prepareStereumNode(installationDirectory) {
this.installationDirectory = installationDirectory;
if (!this.os) {
log.debug("os not found yet");
await this.findOS();
}
/**
* install necessary OS packages
*/
log.info("installing necessary os packages");
const ref = StringUtils.createRandomString();
this.taskManager.tasks.push({
name: "install os packages",
otherRunRef: ref,
});
log.debug("this.os: ", this.os);
log.debug("nodeOS.ubuntu: ", nodeOS.ubuntu);
if (this.os == nodeOS.centos) {
this.taskManager.otherSubTasks.push({
name: "Check OS",
otherRunRef: ref,
status: false,
});
this.taskManager.finishedOtherTasks.push({ otherRunRef: ref });
throw new Error("not implemented yet");
} else if (this.os == nodeOS.ubuntu) {
log.debug("proceed on ubuntu");
this.taskManager.otherSubTasks.push({
name: "Check OS",
otherRunRef: ref,
status: true,
});
let installPkgResult;
try {
installPkgResult = await this.sshService.exec(
"sudo -u root apt update &&\
sudo -u root apt install -y software-properties-common &&\
sudo -u root add-apt-repository --yes --update ppa:ansible/ansible &&\
sudo -u root apt install -y pip ansible tar gzip wget git",
false
);
} catch (err) {
log.error(err);
installPkgResult = { rc: 1, stderr: err };
}
if (SSHService.checkExecError(installPkgResult)) {
this.taskManager.otherSubTasks.push({
name: "installing packages",
otherRunRef: ref,
status: false,
data:
"This error might occur because of a missing interaction. Running this command manually may fix this problem: apt update && apt install -y software-properties-common && add-apt-repository --yes --update ppa:ansible/ansible && apt install -y pip ansible tar gzip wget git \n\n\nError: " +
installPkgResult.stderr,
});
this.taskManager.finishedOtherTasks.push({ otherRunRef: ref });
throw new Error("Can't install os packages: " + SSHService.extractExecError(installPkgResult));
}
this.taskManager.otherSubTasks.push({
name: "installing packages",
otherRunRef: ref,
status: true,
});
} else {
this.taskManager.otherSubTasks.push({
name: "Check OS",
otherRunRef: ref,
status: false,
});
this.taskManager.finishedOtherTasks.push({ otherRunRef: ref });
throw new Error("unsupported OS");
}
/**
* remove stereum ansible playbooks & roles if exist
*/
await this.sshService.exec(`rm -rf ${this.installationDirectory}/ansible`);
/**
* fetch stereum version
*/
let versions;
let commit;
try {
versions = await this.nodeUpdates.checkUpdates();
this.taskManager.otherSubTasks.push({
name: "Get Version Information",
otherRunRef: ref,
status: true,
});
} catch (err) {
this.taskManager.otherSubTasks.push({
name: "Get Version Information",
otherRunRef: ref,
status: false,
});
log.error(`Couldn't fetch versions in PrepareStereumNode...
Installing with predefined Versions...
${err.name}: ${err.message}
url: ${err.config.url}
method: ${err.config.method}
headers: ${err.config.headers}
timeout: ${err.config.timeout}
`);
}
if (versions) {
commit = versions["stereum"].slice(-1).pop().commit;
} else {
commit = "main";
}
log.info("CommitHash:", commit);
/**
* install stereum ansible playbooks & roles
*/
log.info("installing stereum ansible roles");
let installResult;
try {
installResult = await this.sshService.exec(
`mkdir -p "${this.installationDirectory}/ansible" &&
cd "${this.installationDirectory}/ansible" &&
git init &&
git remote add -f ethereum-node https://github.com/stereum-dev/ethereum-node.git &&
git config core.sparseCheckout true &&
echo 'controls' >> .git/info/sparse-checkout &&
git checkout ${global.branch ? global.branch : commit}`
);
} catch (err) {
log.error("can't install ansible roles", err);
this.taskManager.otherSubTasks.push({
name: "install ansible roles",
otherRunRef: ref,
status: false,
});
this.taskManager.finishedOtherTasks.push({ otherRunRef: ref });
throw new Error("Can't install ansible roles: " + err);
}
if (SSHService.checkExecError(installResult)) {
this.taskManager.otherSubTasks.push({
name: "install ansible roles",
otherRunRef: ref,
status: false,
});
this.taskManager.finishedOtherTasks.push({ otherRunRef: ref });
throw new Error("Can't install ansible role: " + SSHService.extractExecError(installResult));
}
this.taskManager.otherSubTasks.push({
name: "install ansible roles",
otherRunRef: ref,
status: true,
});
this.taskManager.finishedOtherTasks.push({ otherRunRef: ref });
/**
* run stereum ansible playbook "setup"
*/
log.info("run stereum ansible playbook 'setup'");
let playbookRuns = [];
try {
playbookRuns.push(
await this.runPlaybook("setup", {
stereum_role: "setup",
stereum_args: {
settings: {
controls_install_path: this.installationDirectory,
},
},
})
);
} catch (err) {
log.error("Can't run setup playbook: ", err);
throw new Error("Can't run setup playbook: " + err);
}
/*
* run stereum ansible playbook "configure-firewall"
*/
log.info("run stereum ansible playbook 'configure-firewall'");
try {
playbookRuns.push(
await this.runPlaybook("configure-firewall", {
stereum_role: "configure-firewall",
})
);
} catch (err) {
log.error("Can't run configure-firewall playbook: ", err);
throw new Error("Can't run configure-firewall playbook: " + err);
}
return playbookRuns;
}
/**
* start a playbook
*/
async runPlaybook(playbook, extraVars) {
if (!this.settings) {
throw new Error("Settings not loaded! Run findStereumSettings() first.");
}
log.info("starting playbook " + playbook + " with extra vars", extraVars);
const playbookRunRef = StringUtils.createRandomString();
log.info("using playbookRunRef: ", playbookRunRef);
let extraVarsJson = "";
if (extraVars) {
extraVarsJson = JSON.stringify(extraVars);
}
let ansibleResult;
this.taskManager.tasks.push({ name: playbook, ref: playbookRunRef });
try {
ansibleResult = await this.sshService.exec(
" ANSIBLE_LOAD_CALLBACK_PLUGINS=1\
ANSIBLE_STDOUT_CALLBACK=stereumjson\
ANSIBLE_LOG_FOLDER=/tmp/" +
playbookRunRef +
"\
ansible-playbook\
--connection=local\
--inventory 127.0.0.1,\
--extra-vars " +
StringUtils.escapeStringForShell(extraVarsJson) +
"\
" +
this.settings.stereum.settings.controls_install_path +
"/ansible/controls/genericPlaybook.yaml\
"
);
} catch (err) {
log.error("Can't run playbook '" + playbook + "'", err);
throw new Error("Can't run playbook: " + err);
}
if (SSHService.checkExecError(ansibleResult)) {
throw new Error("Failed running '" + playbook + "': " + SSHService.extractExecError(ansibleResult));
}
this.taskManager.finishedPlaybooks.push(playbookRunRef);
return {
playbook: playbook,
playbookRunRef: playbookRunRef,
};
}
/**
* get the logs of a playbook started via runPlayboook(...)
*/
async playbookStatus(playbookRunRef) {
log.debug("playbook status of ref ", playbookRunRef);
let statusResult;
try {
statusResult = await this.sshService.exec("cat /tmp/" + playbookRunRef + "/localhost");
} catch (err) {
log.error("Can't read playbook status '" + playbookRunRef + "'", err);
throw new Error("Can't read playbook status '" + playbookRunRef + "': " + err);
}
if (SSHService.checkExecError(statusResult)) {
throw new Error("Failed reading status of ref '" + playbookRunRef + "': " + SSHService.extractExecError(statusResult));
}
return statusResult.stdout;
}
/**
* list services configurations
*/
async listServicesConfigurations() {
let services;
try {
services = await this.sshService.exec("ls -1 /etc/stereum/services 2>/dev/null");
} catch (err) {
log.error("Can't read services configurations", err);
throw new Error("Can't read services configurations: " + err);
}
if (SSHService.checkExecError(services)) {
throw new Error("Failed reading services configurations: " + SSHService.extractExecError(services));
}
return services.stdout.split("\n").filter((i) => i);
}
/**
* read a specific service configuration
*/
async readServiceConfiguration(serviceId) {
let serviceConfig;
try {
const suffix = serviceId.endsWith(".yaml") ? "" : ".yaml";
serviceConfig = await this.sshService.exec("cat /etc/stereum/services/" + serviceId + suffix);
} catch (err) {
log.error("Can't read service configuration of " + serviceId, err);
throw new Error("Can't read service configuration of " + serviceId + ": " + err);
}
if (SSHService.checkExecError(serviceConfig)) {
throw new Error("Failed reading service configuration " + serviceId + ": " + SSHService.extractExecError(serviceConfig));
}
return YAML.parse(serviceConfig.stdout);
}
/**
* read a specific service configuration
*/
async readServiceYAML(serviceId) {
let serviceYAML;
try {
const suffix = serviceId.endsWith(".yaml") ? "" : ".yaml";
serviceYAML = await this.sshService.exec("cat /etc/stereum/services/" + serviceId + suffix);
} catch (err) {
log.error("Can't read service yaml of " + serviceId, err);
throw new Error("Can't read service yaml of " + serviceId + ": " + err);
}
if (SSHService.checkExecError(serviceYAML)) {
throw new Error("Failed reading service yaml " + serviceId + ": " + SSHService.extractExecError(serviceYAML));
}
return serviceYAML.stdout;
}
// <-------- NEW SSVMODAL START --------->
async forwardSSVCommand(args) {
try {
if (typeof this[args.command] === "function") {
return await this[args.command].apply(this, args.arguments);
} else {
throw new Error(`Method ${args.command} does not exist`);
}
} catch (err) {
log.error("Can't forward SSV command ", err);
throw new Error("Can't forward SSV command: " + err);
}
}
async getSSVOperatorDataFromApi(network, pubkey, throwErr = true) {
try {
// Check vars
if (!network || typeof network !== "string") {
let info = `ERROR: Invalid or undefined network specified`;
if (throwErr) throw new Error(info);
return {
code: 2,
info: `ERROR: Could not request operator data from SSV-API (${info})`,
data: {
network: network,
},
};
}
if (!pubkey || typeof pubkey !== "string") {
let info = `ERROR: Invalid or undefined pubkey specified`;
if (throwErr) throw new Error(info);
return {
code: 3,
info: `ERROR: Could not request operator data from SSV-API (${info})`,
data: {
pubkey: pubkey,
},
};
}
// Get operator ID from SSV
let opidresp;
try {
opidresp = await axios.get(`https://api.ssv.network/api/v4/${network}/operators/public_key/` + pubkey);
} catch (e) {
let info = `API endpoint to get operator ID is unavailable`;
if (throwErr) throw new Error(`${info} (${e.message})`);
return {
code: 4,
info: `ERROR: Could not request operator data from SSV-API (${info})`,
data: e,
};
}
const operator_id = opidresp ? opidresp?.data?.data?.id : null;
if (!operator_id) {
let info = `WARNING: SSV API reported unknown operator`;
if (throwErr) throw new Error(info);
return {
code: 99, // API available but operator not registered (yet), special error!
info: `${info}`,
data: {
opidresp: opidresp,
},
};
}
// Get operator metadata from SSV
let opmdresp;
try {
opmdresp = await axios.get(`https://api.ssv.network/api/v4/${network}/operators/` + operator_id);
} catch (e) {
let info = `API endpoint to get metadata for operator ${operator_id} is unavailable`;
if (throwErr) throw new Error(info);
return {
code: 5,
info: `ERROR: Could not request operator data from SSV-API (${info})`,
data: {
opidresp: opidresp,
opmdresp: opmdresp,
},
};
}
const operatorData = opmdresp ? opmdresp?.data : null;
if (!operatorData || !operatorData?.id) {
let info = `API endpoint to get metadata responded for operator ${operator_id} reponded and invalid format`;
if (throwErr) throw new Error(info);
return {
code: 6,
info: `ERROR: Could not request operator data from SSV-API (${info})`,
data: {
opidresp: opidresp,
opmdresp: opmdresp,
},
};
}
// Success (fully registered operator)
if (throwErr) return operatorData;
return {
code: 0,
info: "SUCCESS: operaor registered",
data: {
operatorData: operatorData,
// opidresp: opidresp,
// opmdresp: opmdresp,
},
};
} catch (e) {
let info = `ERROR: Could not request operator data from SSV-API (${e.message})`;
if (throwErr) throw new Error(`${info} (${e.message})`);
// This response would only happens on an uncaught error
return {
code: 1,
info: info,
data: e,
};
}
}
async getSSVLastKnownOperatorIdFilePath(serviceID, getSsvServiceCfg = null, getSsvNetworkCfg = null) {
try {
const getSSVNetworkConfig = getSsvNetworkCfg ? getSsvNetworkCfg : await this.getSSVNetworkConfig(serviceID, getSsvServiceCfg);
const ssvNetworkConfigDir = getSSVNetworkConfig.ssvNetworkConfigDir;
return ssvNetworkConfigDir + "/last_known_operator_id";
} catch (err) {
log.error("Can't get SSV last known operator id file path from service " + serviceID, err);
throw new Error("Can't get SSV last known operator id file path from service " + serviceID + ": " + err);
}
}
async setSSVLastKnownOperatorId(
serviceID,
operatorId,
return_details = false,
force = false,
getSsvServiceCfg = null,
getSsvNetworkCfg = null
) {
const strOperatorId = `${operatorId}`;
try {
try {
if (!force) {
const existing = await this.getSSVLastKnownOperatorId(serviceID, return_details, getSsvServiceCfg, getSsvNetworkCfg);
const existingLastKnownOperatorId = return_details ? existing.lastKnownOperatorIdFileData : existing;
if (existingLastKnownOperatorId == strOperatorId.trim()) {
return existing;
}
}
} catch (err) {}
const lastKnownOperatorIdFilePath = await this.getSSVLastKnownOperatorIdFilePath(serviceID, getSsvServiceCfg, getSsvNetworkCfg);
const lastKnownOperatorIdFileData = strOperatorId.trim();
const result = await this.sshService.exec(`echo -n "${lastKnownOperatorIdFileData}" > "${lastKnownOperatorIdFilePath}"`);
if (SSHService.checkExecError(result, true)) {
throw new Error(SSHService.extractExecError(result));
}
if (!return_details) return lastKnownOperatorIdFileData;
return {
lastKnownOperatorIdFilePath: lastKnownOperatorIdFilePath,
lastKnownOperatorIdFileData: lastKnownOperatorIdFileData,
};
} catch (err) {
log.error("Can't write SSV last known operator id for service " + serviceID, err);
throw new Error("Can't write SSV last known operator id for for service " + serviceID + ": " + err);
}
}
async getSSVLastKnownOperatorId(serviceID, return_details = false, getSsvServiceCfg = null, getSsvNetworkCfg = null) {
try {
const lastKnownOperatorIdFilePath = await this.getSSVLastKnownOperatorIdFilePath(serviceID, getSsvServiceCfg, getSsvNetworkCfg);
let lastKnownOperatorIdFileContent = "";
if (lastKnownOperatorIdFilePath) {
let lastKnownOperatorIdFileRequest = await this.sshService.exec(
`if [ -f "${lastKnownOperatorIdFilePath}" ]; then cat "${lastKnownOperatorIdFilePath}"; else echo ""; fi`
);
if (SSHService.checkExecError(lastKnownOperatorIdFileRequest, true)) {
throw new Error(lastKnownOperatorIdFileRequest.stderr);
} else {
lastKnownOperatorIdFileContent = lastKnownOperatorIdFileRequest.stdout;
}
}
if (!return_details) return lastKnownOperatorIdFileContent.trim();
return {
lastKnownOperatorIdFilePath: lastKnownOperatorIdFilePath,
lastKnownOperatorIdFileData: lastKnownOperatorIdFileContent.trim(),
};
} catch (err) {
log.error("Can't read SSV last known operator id from service " + serviceID, err);
throw new Error("Can't read SSV last known operator id from service " + serviceID + ": " + err);
}
}
async getSSVLastBackedPublicKeyFilePath(serviceID, getSsvServiceCfg = null, getSsvNetworkCfg = null) {
try {
const getSSVNetworkConfig = getSsvNetworkCfg ? getSsvNetworkCfg : await this.getSSVNetworkConfig(serviceID, getSsvServiceCfg);
const ssvNetworkConfigDir = getSSVNetworkConfig.ssvNetworkConfigDir;
return ssvNetworkConfigDir + "/last_backed_public_key";
} catch (err) {
log.error("Can't get SSV last backed public key file path from service " + serviceID, err);
throw new Error("Can't get SSV last backed public key file path from service " + serviceID + ": " + err);
}
}
async setSSVLastBackedPublicKey(serviceID, strPublicKey, return_details = false, getSsvServiceCfg = null, getSsvNetworkCfg = null) {
try {
const lastBackedPublicKeyFilePath = await this.getSSVLastBackedPublicKeyFilePath(serviceID, getSsvServiceCfg, getSsvNetworkCfg);
const lastBackedPublicKeyFileData = strPublicKey.trim();
const result = await this.sshService.exec(`echo -n "${lastBackedPublicKeyFileData}" > "${lastBackedPublicKeyFilePath}"`);
if (SSHService.checkExecError(result, true)) {
throw new Error(SSHService.extractExecError(result));
}
if (!return_details) return lastBackedPublicKeyFileData;
return {
lastBackedPublicKeyFilePath: lastBackedPublicKeyFilePath,
lastBackedPublicKeyFileData: lastBackedPublicKeyFileData,
};
} catch (err) {
log.error("Can't write SSV last backed public key for service " + serviceID, err);
throw new Error("Can't write SSV last backed public key for for service " + serviceID + ": " + err);
}
}
async getSSVLastBackedPublicKey(serviceID, return_details = false, getSsvServiceCfg = null, getSsvNetworkCfg = null) {
try {
const lastBackedPublicKeyFilePath = await this.getSSVLastBackedPublicKeyFilePath(serviceID, getSsvServiceCfg, getSsvNetworkCfg);
let lastBackedPublicKeyFileContent = "";
if (lastBackedPublicKeyFilePath) {
let lastBackedPublicKeyFileRequest = await this.sshService.exec(
`if [ -f "${lastBackedPublicKeyFilePath}" ]; then cat "${lastBackedPublicKeyFilePath}"; else echo ""; fi`
);
if (SSHService.checkExecError(lastBackedPublicKeyFileRequest, true)) {
throw new Error(lastBackedPublicKeyFileRequest.stderr);
} else {
lastBackedPublicKeyFileContent = lastBackedPublicKeyFileRequest.stdout;
}
}
if (!return_details) return lastBackedPublicKeyFileContent.trim();
return {
lastBackedPublicKeyFilePath: lastBackedPublicKeyFilePath,
lastBackedPublicKeyFileData: lastBackedPublicKeyFileContent.trim(),
};
} catch (err) {
log.error("Can't read SSV last backed public key from service " + serviceID, err);
throw new Error("Can't read SSV last backed public key from service " + serviceID + ": " + err);
}
}
async importSSVEncryptedKeys(serviceID, encrypted_ssv_private_key, password) {
try {
const totalConfig = await this.getSSVTotalConfig(serviceID);
const user = totalConfig.ssvServiceConfig.user;
const service_config_dir = totalConfig.ssvServiceConfigDir;
const service_config_file = service_config_dir + "/" + totalConfig.serviceID + ".yaml";
const network_config_dir = totalConfig.ssvNetworkConfigDir;
const network_config_db = network_config_dir + "/db";
const network_config_file = network_config_dir + "/config.yaml";
const secrets_dir = totalConfig.ssvSecretsDir;
const keystore_file = secrets_dir + "/encrypted_private_key.json";
const password_file = secrets_dir + "/password";
const keystore_file_cfg = "/" + secrets_dir.split("/").pop() + "/encrypted_private_key.json";
const password_file_cfg = "/" + secrets_dir.split("/").pop() + "/password";
const private_key = encrypted_ssv_private_key;
// Check encrypted SSV private_key (keystore) and get public key
if (!private_key) {
throw new Error("Given encrypted SSV private_key (keystore) is invalid");
}
let private_key_data;
try {
private_key_data = JSON.parse(private_key);
} catch (e) {
throw new Error("Given encrypted SSV private_key (keystore) is invalid (not JSON format)");
}
// SSV generated keystore uses "pubKey" since v1.3.3, previously it was "publicKey"
if (!private_key_data?.publicKey && !private_key_data?.pubKey) {
throw new Error("Given encrypted SSV private_key (keystore) is invalid (no public key available)");
}
private_key_data.publicKey = private_key_data?.publicKey ? private_key_data.publicKey : private_key_data?.pubKey;
const newPubKey = private_key_data.publicKey;
// Add password_file and keystore_file to secrets dir
const escapedPassword = StringUtils.escapeStringForShell(password);
const escapedPrivateKey = StringUtils.escapeStringForShell(private_key);
const keystore_password_write = await this.sshService.exec(`
mkdir -p ${secrets_dir} &&
echo ${escapedPassword} > ${password_file} &&
chown ${user}:${user} ${password_file} &&
chmod 0600 ${password_file} &&
echo ${escapedPrivateKey} > ${keystore_file} &&
chown ${user}:${user} ${keystore_file} &&
chmod 0600 ${keystore_file}
`);
if (SSHService.checkExecError(keystore_password_write, true)) {
throw new Error(SSHService.extractExecError(keystore_password_write));
}
// Write network config
const network_config_read = await this.sshService.exec(`cat ${network_config_file}`);
if (SSHService.checkExecError(network_config_read)) {
throw new Error(SSHService.extractExecError(network_config_read));
}
let network_config_content = network_config_read.stdout;
let replacementString = `KeyStore:\n PrivateKeyFile: ${keystore_file_cfg}\n PasswordFile: ${password_file_cfg}`;
network_config_content = network_config_content.replace(/^\s*(PrivateKeyFile|PasswordFile).*/gm, "");
network_config_content = network_config_content.replace(/^(KeyStore|OperatorPrivateKey).*/gm, replacementString);
const escapedNetworkConfigFile = StringUtils.escapeStringForShell(network_config_content.trim());
const network_config_write = await this.sshService.exec(`
mkdir -p ${network_config_dir} &&
echo ${escapedNetworkConfigFile} > ${network_config_file} &&
chown ${user}:${user} ${network_config_file} &&
chmod 0644 ${network_config_file}
`);
if (SSHService.checkExecError(network_config_write, true)) {
throw new Error(SSHService.extractExecError(network_config_write));
}
// Remove sk/pk from service config (if exists)
if (totalConfig.ssvServiceConfig?.ssv_pk || totalConfig.ssvServiceConfig?.ssv_sk) {
const service_config_read = await this.sshService.exec(`cat ${service_config_file}`);
if (SSHService.checkExecError(service_config_read)) {
throw new Error(SSHService.extractExecError(service_config_read));
}
const escapedServiceConfigFile = StringUtils.escapeStringForShell(
service_config_read.stdout.replace(/^(ssv_pk|ssv_sk|# BEGIN ANSIBLE MANAGED BLOCK|# END ANSIBLE MANAGED BLOCK).*/gm, "").trim()
);
const service_config_write = await this.sshService.exec(`
mkdir -p ${service_config_dir} &&
echo ${escapedServiceConfigFile} > ${service_config_file} &&
chown ${user}:${user} ${service_config_file} &&
chmod 0644 ${service_config_file}
`);
if (SSHService.checkExecError(service_config_write, true)) {
throw new Error(SSHService.extractExecError(service_config_write));
}
}
// Set last backed public key
await this.setSSVLastBackedPublicKey(totalConfig.serviceID, newPubKey);
// Remove database
const remove_db = await this.sshService.exec(`rm -rf ${network_config_db}`);
if (SSHService.checkExecError(remove_db, true)) {
throw new Error(SSHService.extractExecError(remove_db));
}
// Write last known public key file
return await this.writeSSVLastKnownPublicKeyFile(
totalConfig.serviceID,
newPubKey,
totalConfig.getSsvServiceConfig,
totalConfig.getSsvNetworkConfig
);
} catch (err) {
log.error("Can't import encrypted SSV keys for service " + serviceID, err);
throw new Error("Can't import encrypted SSV keys for service " + serviceID + ": " + err);
}
}
async importSSVUnencryptedKeys(serviceID, unencrypted_secret_key) {
try {
const totalConfig = await this.getSSVTotalConfig(serviceID);
const user = totalConfig.ssvServiceConfig.user;
const service_config_dir = totalConfig.ssvServiceConfigDir;
const service_config_file = service_config_dir + "/" + totalConfig.serviceID + ".yaml";
const network_config_dir = totalConfig.ssvNetworkConfigDir;
const network_config_file = network_config_dir + "/config.yaml";
const network_config_db = network_config_dir + "/db";
const secrets_dir = totalConfig.ssvSecretsDir;
const keystore_file = secrets_dir + "/encrypted_private_key.json";
const password_file = secrets_dir + "/password";
const private_key = unencrypted_secret_key;
// Check (unencrypted) SSV secret key (private_key)
if (!private_key) {
throw new Error("Given unencrypted SSV secret key (private key) is invalid");
}
if (!StringUtils.isBase64(private_key)) {
throw new Error("Given unencrypted SSV secret key (private key) is invalid (not base 64 encoded)");
}
if (!StringUtils.isValidRsaPrivateKey(StringUtils.base64decode(private_key))) {
throw new Error("Given unencrypted SSV secret key is no valid RSA private key");
}
// Get new public key from secret key (private_key)
const newPubKey = StringUtils.getSSVPublicKeyFromSecretKey(private_key);
// Remove password file and keystore_file from secrets dir
const clean_secrets_dir = await this.sshService.exec(`
rm -f "${password_file}" &>/dev/null ;
rm -f "${keystore_file}" &>/dev/null
`);
if (SSHService.checkExecError(clean_secrets_dir, true)) {
throw new Error(SSHService.extractExecError(clean_secrets_dir));
}
// Write network config
const network_config_read = await this.sshService.exec(`cat ${network_config_file}`);
if (SSHService.checkExecError(network_config_read)) {
throw new Error(SSHService.extractExecError(network_config_read));
}
let network_config_content = network_config_read.stdout;
let replacementString = `OperatorPrivateKey: ${unencrypted_secret_key}`;
network_config_content = network_config_content.replace(/^(KeyStore|OperatorPrivateKey).*/gm, replacementString);
network_config_content = network_config_content.replace(/^\s*(PrivateKeyFile|PasswordFile).*/gm, "");
const escapedNetworkConfigFile = StringUtils.escapeStringForShell(network_config_content.trim());
const network_config_write = await this.sshService.exec(`
mkdir -p ${network_config_dir} &&
echo ${escapedNetworkConfigFile} > ${network_config_file} &&
chown ${user}:${user} ${network_config_file} &&
chmod 0644 ${network_config_file}
`);
if (SSHService.checkExecError(network_config_write, true)) {
throw new Error(SSHService.extractExecError(network_config_write));
}
// Remove sk/pk from service config (if exists) and add new sk/pk to service config
const service_config_read = await this.sshService.exec(`cat ${service_config_file}`);
if (SSHService.checkExecError(service_config_read)) {
throw new Error(SSHService.extractExecError(service_config_read));
}
let service_config_content = service_config_read.stdout;
if (totalConfig.ssvServiceConfig?.ssv_pk || totalConfig.ssvServiceConfig?.ssv_sk) {
service_config_content = service_config_content.replace(
/^(ssv_pk|ssv_sk|# BEGIN ANSIBLE MANAGED BLOCK|# END ANSIBLE MANAGED BLOCK).*/gm,
""
);
}
service_config_content = service_config_content.trim();
service_config_content += `\n\n`;
service_config_content += `# BEGIN ANSIBLE MANAGED BLOCK\n`;
service_config_content += `ssv_pk: "${newPubKey}"\n`;
service_config_content += `ssv_sk: "${private_key}"\n`;
service_config_content += `# END ANSIBLE MANAGED BLOCK\n`;
const escapedServiceConfigFile = StringUtils.escapeStringForShell(service_config_content.trim());
const service_config_write = await this.sshService.exec(`
mkdir -p ${service_config_dir} &&
echo ${escapedServiceConfigFile} > ${service_config_file} &&
chown ${user}:${user} ${service_config_file} &&
chmod 0644 ${service_config_file}
`);
if (SSHService.checkExecError(service_config_write, true)) {
throw new Error(SSHService.extractExecError(service_config_write));
}
// Set last backed public key
await this.setSSVLastBackedPublicKey(totalConfig.serviceID, newPubKey);
// Remove database
const remove_db = await this.sshService.exec(`rm -rf ${network_config_db}`);
if (SSHService.checkExecError(remove_db, true)) {
throw new Error(SSHService.extractExecError(remove_db));
}
// Write last known public key file
return await this.writeSSVLastKnownPublicKeyFile(
totalConfig.serviceID,
newPubKey,
totalConfig.getSsvServiceConfig,
totalConfig.getSsvNetworkConfig
);
} catch (err) {
log.error("Can't import unencrypted SSV keys for service " + serviceID, err);
throw new Error("Can't import unencrypted SSV keys for service " + serviceID + ": " + err);
}
}
async migrateToSSVEncryptedKeys(serviceID, password, unencrypted_secret_key = null) {
try {
const totalConfig = await this.getSSVTotalConfig(serviceID);
const docker_image = totalConfig.ssvServiceConfig.image;
const user = totalConfig.ssvServiceConfig.user;
const service_config_dir = totalConfig.ssvServiceConfigDir;
const service_config_file = service_config_dir + "/" + totalConfig.serviceID + ".yaml";
const network_config_dir = totalConfig.ssvNetworkConfigDir;
const network_config_db = network_config_dir + "/db";
const network_config_file = network_config_dir + "/config.yaml";
const secrets_dir = totalConfig.ssvSecretsDir;
const keystore_file = secrets_dir + "/encrypted_private_key.json";
const password_file = secrets_dir + "/password";
const private_key = unencrypted_secret_key ? unencrypted_secret_key : totalConfig.deprecatedSecretKey;
const private_key_file = secrets_dir + "/private-key";
const keystore_file_cfg = "/" + secrets_dir.split("/").pop() + "/encrypted_private_key.json";
const password_file_cfg = "/" + secrets_dir.split("/").pop() + "/password";
// Check (unencrypted) SSV secret key (private_key)
if (!private_key) {
throw new Error("Unencrypted SSV secret key (private key) is invalid (neither given as argument nor found on the server)");
}
if (!StringUtils.isBase64(private_key)) {
throw new Error("Unencrypted SSV secret key (private key) is invalid (not base 64 encoded)");
}
if (!StringUtils.isValidRsaPrivateKey(StringUtils.base64decode(private_key))) {
throw new Error("Unencrypted SSV secret key is no valid RSA private key");
}
// Create secrets dir, password file and private_key_file
const escapedPassword = StringUtils.escapeStringForShell(password);
const escapedPrivateKey = StringUtils.escapeStringForShell(private_key);
const password_write = await this.sshService.exec(`
mkdir -p ${secrets_dir} &&
chown ${user}:${user} ${secrets_dir} &&
chmod 0755 ${secrets_dir} &&
echo ${escapedPassword} > ${password_file} &&
chown ${user}:${user} ${password_file} &&
chmod 0600 ${password_file} &&
echo ${escapedPrivateKey} > ${private_key_file} &&
chown ${user}:${user} ${private_key_file} &&
chmod 0600 ${private_key_file}
`);
if (SSHService.checkExecError(password_write, true)) {
throw new Error(SSHService.extractExecError(password_write));
}
// Create keystore from unencrypted secret key
// Without "-it" https://stackoverflow.com/a/43099210
const keystore_write = await this.sshService.exec(`
docker run --name ssv-node-key-generation -v '${password_file}':/password -v '${private_key_file}':/private-key '${docker_image}' /go/bin/ssvnode generate-operator-keys --password-file=/password --operator-key-file=/private-key &&
docker cp ssv-node-key-generation:/encrypted_private_key.json '${keystore_file}' &&
docker rm ssv-node-key-generation &&
rm '${private_key_file}' &&
chown ${user}:${user} ${keystore_file} &&
chmod 0600 ${keystore_file}
`);
if (SSHService.checkExecError(keystore_write)) {
throw new Error(SSHService.extractExecError(keystore_write));
}
// Get new public key from keystore
const keystore_read = await this.sshService.exec(`cat ${keystore_file}`);
if (SSHService.checkExecError(keystore_read)) {
throw new Error(SSHService.extractExecError(keystore_read));
}
const keystore_content = keystore_read.stdout;
const keystore_data = JSON.parse(keystore_content);
keystore_data.publicKey = keystore_data?.publicKey ? keystore_data.publicKey : keystore_data?.pubKey;
const newPubKey = keystore_data.publicKey;
// Write network config
const network_config_read = await this.sshService.exec(`cat ${network_config_file}`);