1
0
Fork 0
mirror of https://github.com/Ylianst/MeshCentral.git synced 2025-03-09 15:40:18 +00:00

Compare commits

...

118 commits

Author SHA1 Message Date
si458
88a765bb13 add agentupdate to console agent actions #6869
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-03-08 18:37:18 +00:00
Daniel Hammerschmidt
7ad4b917be
print stack trace on plugin error and add space for readability of error message (#6859)
* add space for readability of error message

* print stack trace on plugin error
2025-03-08 17:50:39 +00:00
si458
d10173a018 fix sharing-mobile view only having control #6764
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-03-08 17:20:30 +00:00
si458
0e3a6b4915 fix logoutOnIdleSessionTimeout spelling and extra translations #6851
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-03-08 16:48:37 +00:00
Ylian Saint-Hilaire
b949cecc5f Version 1.1.42 2025-03-07 09:06:50 -08:00
Ylian Saint-Hilaire
c7cbf2f12a Updated Windows x86-32 and 64 agents. 2025-03-07 09:05:07 -08:00
si458
d49afdd7bf report version/size correctly to control panel #6860
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-03-07 16:31:11 +00:00
Ylian Saint-Hilaire
133e77c8c6 Version 1.1.41 2025-03-05 18:09:42 -08:00
Ylian Saint-Hilaire
e404e86b9f Updated Windows Agents 2025-03-05 18:06:30 -08:00
si458
c6da201af8 fix duo 2fa redirect when session changes
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-03-05 10:37:39 +00:00
Roman
9a27d7637c
Improvements to the German translation in various areas (#6849) 2025-03-04 20:44:36 +00:00
Daniel Hammerschmidt
5aa2467409
add comment about meshrelay ping-pong in docs(#6842) 2025-03-04 18:47:00 +00:00
si458
9398afd07e fix getDeviceDetails asking for all devices not including lastconnect #6833
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-03-03 14:13:34 +00:00
Ylian Saint-Hilaire
b2cd84035b Version 1.1.40 2025-03-02 10:47:32 -08:00
Ylian Saint-Hilaire
97547d72a3 Updated MeshCmd 2025-03-02 10:46:13 -08:00
si458
7faf043c35 recording not recoding
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-27 18:35:11 +00:00
Daniel Hammerschmidt
9df0330896
avoid double logging in debug console (#6827) 2025-02-27 18:23:36 +00:00
si458
42f61ea46e fix bootstrap padding #6755
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-27 18:08:12 +00:00
ijustw0rkhere
0d65080a8a
fix runcommands in a peering environment (#6825)
* fix adding meshes and user groups in a peering environment

* fix runcommands in a peering environment
2025-02-27 15:12:18 +00:00
si458
bd4d8b12d4 fix consent with oldstyle: true and rdp sessions #6816
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-26 20:51:24 +00:00
si458
18ae8bdbf4 fix relaystate for entra #6822
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-26 20:32:38 +00:00
si458
46c76f7234 smoothing not smooting #6818
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-26 15:36:23 +00:00
Ylian Saint-Hilaire
e65bf77111 Version 1.1.39 2025-02-25 19:58:15 -08:00
Ylian Saint-Hilaire
f19ad6c664 Extra argument validation. 2025-02-25 19:57:27 -08:00
Ylian Saint-Hilaire
fe2f12149d Updated French Translations. 2025-02-25 19:20:43 -08:00
si458
91bd5ae702 fix minify files and log minify errors
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-25 17:21:50 +00:00
Daniel Hammerschmidt
38f5bf2e0f
Fix parameter names in usage message (#6810) 2025-02-25 13:08:51 +00:00
Daniel Hammerschmidt
79f00bcaab
fix evaluation of config.settings.agentlogdump (#6812) 2025-02-25 12:51:52 +00:00
si458
c55065505b fix relaylog ip order again
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-23 01:13:20 +00:00
PTR
e0e8a3fcaa
Add comma to escapeFieldName for NeDBv4 (#6803) 2025-02-22 16:59:41 +00:00
Daniel Hammerschmidt
3f77cfa93a
Add collectors to monitoring (#6777)
* Add collectors to monitoring

* Pass request and response objects to collectors
2025-02-20 22:37:14 +00:00
Jakub Maruszczak
5ee9aa2410
fix meshctrl tag filter search (#6798) 2025-02-20 22:16:15 +00:00
Jakub Maruszczak
0ab3f01ca6
prevent runcommand with --reply from terminating other ws connections (#6797) 2025-02-20 22:09:02 +00:00
Daniel Hammerschmidt
4b621a01fb
Fix gauge typo (#6778) 2025-02-20 21:59:36 +00:00
si458
f2681de87d fix webrtc viewonly mode #6792
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-19 14:03:31 +00:00
PTR
c90fa55c99
Init webstate with empty object (#6788) 2025-02-18 11:35:23 +00:00
si458
edeef03f00 track/show locked active users #6782
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-14 15:42:43 +00:00
si458
d7fe87d1db fix sessionrecording ip addresses wrong way round
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-13 21:39:15 +00:00
Martin Mädler
9d4f51e970
Add support for logoutOnIdleSessionTimeout (#6773) 2025-02-12 10:04:10 +00:00
si458
0b376fe5a0 fix player for windows and terminal #6761
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-11 17:04:19 +00:00
si458
9fd40751b2 fix remote desktop consent for rdp sessions #6710
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-09 21:41:08 +00:00
si458
d246307fae translation improvements
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-09 21:03:54 +00:00
Simon Smith
711bb56a93
autoAcceptIfNoUser (#6759)
* autoAcceptIfNoUser for desktop

* autoAcceptIfNoUser for terminal

* autoAcceptIfNoUser for files

* forgot few extra files

---------

Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-09 19:54:51 +00:00
Simon Smith
5734bcc33a
UI Toggle between Classic and Modern (#6763)
* [ENH] Add toggle switch for new MeshCentral UI in settings and top header of the classic UI

* [ENH] Add toggle for new MeshCentral UI in settings and in top headbar of the modern UI

* add showModernUIToggle and store uiviewmode in db

---------

Co-authored-by: kambereBr <brunokambere@gmail.com>
2025-02-09 19:41:47 +00:00
si458
1310c57397 return more than 100 groups for azure oidc #6669
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-05 21:21:39 +00:00
si458
854d6c00d2 fix view chunksize being too big causing pixelation
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-05 11:44:23 +00:00
si458
c96d7ff1ca remove CSP for web relay as apps dont load properly with the default set #6456
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-02-05 11:32:56 +00:00
Simon Smith
712f06db3c
fix meshcentral-config-schema.json for ace editor 2025-01-27 23:02:56 +00:00
si458
cac505e2cd few more translations
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-26 18:10:26 +00:00
interfect
9d962bc523
Note maximum password length in USB key dialog (#6735) 2025-01-26 18:02:42 +00:00
si458
f079692b16 change dnslytics.com to maclookup.app for mac address lookup #6704
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-26 14:57:41 +00:00
nmmclwhitehead
3ee06abfe8
Update webserver.js - allow saml relaystate in POST request (#6685)
added check for relaystate saml and regex check

added in rest of allowed params

correct formatting on regex string - now evaluates correctly

set relaystate on get request

check for ipv6
2025-01-26 14:42:48 +00:00
PTR
b46ddf2f70
Update console info command (#6722)
* Add human readable option (h) to info command

* Add option to helptext
2025-01-26 14:35:18 +00:00
PTR
f7b958d28b
Autobackup update (#6695)
* add backupHours option and many debug messages

* Cleanup debug messages, add backupinfo

* Add full path to remove log message

* Put backupcheck after config init, check proper backuppath

* Handle absolute backuppath, check access in checkBackupCapability, seperated expired files check to function, more message edits, serverwarnings

* Revert fallback to default backuppath

* Cleanup checkBackupCapability and messages

* add WebDAV messages
2025-01-26 14:24:40 +00:00
KevinBK1998
64c8d2c238
include username for amt direct connect in logs 2025-01-26 14:07:37 +00:00
si458
31f2224a93 add notransval to fix select options translate issues
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-26 13:54:04 +00:00
petervanv
de685556c8
Dutch language update 1.1.38 (#6716)
update and cleaned up some useless strings
2025-01-26 12:52:04 +00:00
si458
92375ddc93 add lastbootuptime to csv and fix spaces in csv translations #6723
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-26 12:42:30 +00:00
si458
ea80f8595e fix some functions not being called in sitestyle=3 #6733
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-26 10:59:08 +00:00
Ylian Saint-Hilaire
763f76b68f Version 1.1.38 2025-01-09 17:08:31 -08:00
nmmclwhitehead
1a02539f23
Added support for &gotodeviceip=x.x.x.x (#6672) 2025-01-08 11:27:50 +00:00
si458
90b71e924f properly fix multiple dialog popups in a row
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-07 16:52:19 +00:00
si458
73c18c4dd5 fix deviceaction multiple modals not working
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-07 16:35:13 +00:00
si458
def62075c7 fix theme switch to default bug and include google fonts in csp #6665
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-06 16:02:10 +00:00
Ylian Saint-Hilaire
998769a888 Version 1.1.37 2025-01-05 15:37:41 -08:00
si458
ca6ec5ebc9 fix delete node bootstrap ui
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-05 22:16:09 +00:00
si458
0dd56d5708 improve translations all around
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-05 21:37:56 +00:00
si458
95729d2a88 set default minify to false in docker
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-05 17:47:21 +00:00
si458
1ae7b9f641 fix minify in bootstrap #6662
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-05 17:38:03 +00:00
si458
c66a9a12ef i hate sundays, fix passport module again
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-05 14:48:51 +00:00
si458
2c310450cf fix passport module not installing for multiple domains
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-05 14:40:19 +00:00
Ylian Saint-Hilaire
b6e022c01e Version 1.1.36 2025-01-03 17:22:49 -08:00
si458
e66776c5da if no nodes return nothing for getDeviceDetails #6637
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-03 16:59:29 +00:00
si458
d1cb184e9e fix deleting user with no events causes page to not change
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-03 16:18:42 +00:00
si458
6aa60d556f fix reload issue with # in url
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-03 16:03:17 +00:00
Noah Zalev
8d4e9bcede
Re-enable autobackups by default (#6644) (#6653) 2025-01-03 15:54:47 +00:00
si458
eb0d24cf0b fix trafficstats with novnc
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-02 23:55:43 +00:00
si458
fe02d3158d add pwr,conn,agct,cict to getDeviceDetails #6650
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-02 23:49:02 +00:00
Simon Smith
61d3487f8a
add prometheus metrics (#6654)
Signed-off-by: si458 <simonsmith5521@gmail.com>
2025-01-02 23:38:13 +00:00
Simon Smith
a23725eb40
fix trafficstats relaycount NaN 2025-01-02 20:13:51 +00:00
Ylian Saint-Hilaire
9b60271f31
Update index.md
Added Duo link
2025-01-01 17:22:03 -08:00
Ylian Saint-Hilaire
31f328086e
Update security.md
JSON fix
2025-01-01 17:18:59 -08:00
Ylian Saint-Hilaire
7aa4061cad
Update security.md
Added Duo installation steps.
2025-01-01 17:18:38 -08:00
Ylian Saint-Hilaire
54bb0177ee
Update index.md
Minor fixes
2025-01-01 17:03:30 -08:00
Jason N. White
ce70f4ac08
Update LICENSE, fix license year (#6646)
Signed-off-by: JasonnnW3000 <sufssl04@gmail.com>
2025-01-01 16:52:53 -08:00
Pablo Henrique Batista
f712cd9425
Fixes multi domain using default domain cert without trying to recreate for new domains (#6645) 2025-01-01 20:04:32 +00:00
Ylian Saint-Hilaire
c4592dcc4f Fixed Duo Boost UI. 2024-12-31 14:11:21 -08:00
Ylian Saint-Hilaire
2a274fe569 More Duo UI improvements. 2024-12-31 11:48:30 -08:00
Ylian Saint-Hilaire
5d0b5acdfb Duo UI improvements. 2024-12-31 11:40:08 -08:00
Ylian Saint-Hilaire
f80ba62cfc Fixed Duo 2FA security. 2024-12-31 10:37:09 -08:00
dev6699
5da849063b
fix: db.js expire server stats comment typo (#6633) 2024-12-29 12:39:50 -08:00
si458
68ac8cf86c fix duo and theme switcher
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-24 11:20:58 +00:00
Sammy Ndabo
8e70cd7187
[NEW] Add Theme Switcher with Bootstrap/Bootswatch Themes (#6622) 2024-12-24 10:15:45 +00:00
si458
5cf468159d fix duo and package.json
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-23 13:13:37 +00:00
Ylian Saint-Hilaire
c92b88a374 Duo changes, but not yet fully tested. 2024-12-22 19:10:35 -08:00
si458
1b01b90cd6 bootstrap3: dark mode fixes, buttons replaced, more translate fixes #6496
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-22 01:28:31 +00:00
si458
6a366fe174 bootstrap3: fix translations, fix button styling, new contextmenus, mouse disable cursor #6496
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-21 19:42:50 +00:00
Simon Smith
e2362a0547
add duo authentication support (#6609)
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-21 13:52:54 +00:00
Simon Smith
59fcc0dbc6
fix bootstrap 3 record session formatting #6618 2024-12-21 11:24:12 +00:00
Simon Smith
988983b880
alpine 3.21 and node 22 in docker 2024-12-18 18:58:32 +00:00
Simon Smith
a1854fa074
fix createmesh with email as userid #6596 2024-12-18 18:31:20 +00:00
Ylian Saint-Hilaire
22fc95926a Fixed module update for modules like firebase-admin.js 2024-12-15 00:24:18 -08:00
Ylian Saint-Hilaire
c2eb1f2516 Updated to MeshCentral Firebase support, updated to using firebase-admin module. 2024-12-14 21:56:36 -08:00
si458
832d11739b fix defender not showing
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-09 13:17:35 +00:00
si458
ab7be919a0 fix meshcmd amtinfo UNCAUGHT EXCEPTION #4135
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-07 14:41:19 +00:00
si458
624d61db43 move windows_volumes and bitlocker to win-volumes
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-06 13:56:15 +00:00
si458
b0d8e3fe48 package updates
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-06 13:34:24 +00:00
si458
a33047747a add OS Descripton to Details #6556
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-06 12:34:06 +00:00
PTR
39e81befe1
fix bitlocker/manage-bde cmdline (#6586) 2024-12-05 17:40:20 +00:00
Roman
8eeb96fb0d
Spelling mistake in German translation (#6585) 2024-12-05 13:45:23 +00:00
PTR
f9228ad0eb
connectinArgs.Database > connectinArgs.database typo (#6576) 2024-12-02 14:06:58 +00:00
si458
ce4217c346 fix messenger background notifications #2440
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-01 23:19:41 +00:00
si458
d9262f7c9d update translate, fix bootstrap version panel, deskbackground
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-12-01 22:26:03 +00:00
Ylian Saint-Hilaire
8e8ec4f88a Version 1.1.35 2024-12-01 10:28:35 -08:00
Ikko Eltociear Ashimine
18167499d9
chore: update pluginHandler.js (#6569)
ocurred -> occurred
2024-11-30 22:41:06 +00:00
si458
da5d03b0e7 fix annoying firefox paste option with clipboard #6571
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-11-30 16:14:35 +00:00
si458
c41eb72a2c fix win7+server2008r2 powershell/wmi
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-11-30 13:50:02 +00:00
si458
ef4d764ab4 Revert "swap powershell write to command instead" to fix win7/server2008r2
Signed-off-by: si458 <simonsmith5521@gmail.com>
2024-11-30 00:21:44 +00:00
106 changed files with 19246 additions and 12905 deletions

View file

@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier same "printed page" as the copyright notice for easier
identification within third-party archives. identification within third-party archives.
Copyright 2017-2021 Intel Corporation Copyright 2017-2025 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

View file

@ -594,12 +594,14 @@
<Content Include="readme.md" /> <Content Include="readme.md" />
<Content Include="sample-config-advanced.json" /> <Content Include="sample-config-advanced.json" />
<Content Include="sample-config.json" /> <Content Include="sample-config.json" />
<Content Include="SECURITY.md" />
<Content Include="SourceFileList.txt" /> <Content Include="SourceFileList.txt" />
<Content Include="translate\readme.txt" /> <Content Include="translate\readme.txt" />
<Content Include="translate\translate.json" /> <Content Include="translate\translate.json" />
<Content Include="views\agentinvite.handlebars" /> <Content Include="views\agentinvite.handlebars" />
<Content Include="views\default-mobile.handlebars" /> <Content Include="views\default-mobile.handlebars" />
<Content Include="views\default.handlebars" /> <Content Include="views\default.handlebars" />
<Content Include="views\default3.handlebars" />
<Content Include="views\download.handlebars" /> <Content Include="views\download.handlebars" />
<Content Include="views\download2.handlebars" /> <Content Include="views\download2.handlebars" />
<Content Include="views\error404-mobile.handlebars" /> <Content Include="views\error404-mobile.handlebars" />

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -588,7 +588,7 @@ function run(argv) {
} }
amtMei.getProvisioningState(function (result) { if (result) { mestate.ProvisioningState = result; } }); amtMei.getProvisioningState(function (result) { if (result) { mestate.ProvisioningState = result; } });
amtMei.getProvisioningMode(function (result) { if (result) { mestate.ProvisioningMode = result; } }); amtMei.getProvisioningMode(function (result) { if (result) { mestate.ProvisioningMode = result; } });
amtMei.getEHBCState(function (result) { mestate.ehbc = ((result === true) || (typeof result == 'object') && (result.EHBC === true)); }); amtMei.getEHBCState(function (result) { if (result) { mestate.ehbc = ((result === true) || (typeof result == 'object') && (result.EHBC === true)); } });
amtMei.getControlMode(function (result) { if (result) { mestate.controlmode = result; } }); amtMei.getControlMode(function (result) { if (result) { mestate.controlmode = result; } });
amtMei.getMACAddresses(function (result) { if (result) { mestate.mac = result; } }); amtMei.getMACAddresses(function (result) { if (result) { mestate.mac = result; } });
amtMei.getLanInterfaceSettings(0, function (result) { if (result) { mestate.net0 = result; } }); amtMei.getLanInterfaceSettings(0, function (result) { if (result) { mestate.net0 = result; } });

View file

@ -249,7 +249,7 @@ function lockDesktop(uid) {
case 'win32': case 'win32':
{ {
var options = { type: 1, uid: uid }; var options = { type: 1, uid: uid };
var child = require('child_process').execFile(process.env['windir'] + '\\system32\\cmd.exe', ['cmd', '/c', 'RunDll32.exe user32.dll,LockWorkStation'], options); var child = require('child_process').execFile(process.env['windir'] + '\\system32\\cmd.exe', ['/c', 'RunDll32.exe user32.dll,LockWorkStation'], options);
child.waitExit(); child.waitExit();
} }
break; break;
@ -295,8 +295,9 @@ if (process.platform == 'win32' && require('user-sessions').isRoot()) {
// Check the Agent Uninstall MetaData for correctness, as the installer may have written an incorrect value // Check the Agent Uninstall MetaData for correctness, as the installer may have written an incorrect value
try { try {
var writtenSize = 0, actualSize = Math.floor(require('fs').statSync(process.execPath).size / 1024); var writtenSize = 0, actualSize = Math.floor(require('fs').statSync(process.execPath).size / 1024);
try { writtenSize = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MeshCentralAgent', 'EstimatedSize'); } catch (ex) { } var serviceName = (_MSH().serviceName ? _MSH().serviceName : (require('_agentNodeId').serviceName() ? require('_agentNodeId').serviceName() : 'Mesh Agent'));
if (writtenSize != actualSize) { try { require('win-registry').WriteKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MeshCentralAgent', 'EstimatedSize', actualSize); } catch (ex) { } } try { writtenSize = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'EstimatedSize'); } catch (ex) { }
if (writtenSize != actualSize) { try { require('win-registry').WriteKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'EstimatedSize', actualSize); } catch (ex) { } }
} catch (ex) { } } catch (ex) { }
// Check to see if we are the Installed Mesh Agent Service, if we are, make sure we can run in Safe Mode // Check to see if we are the Installed Mesh Agent Service, if we are, make sure we can run in Safe Mode
@ -310,6 +311,16 @@ if (process.platform == 'win32' && require('user-sessions').isRoot()) {
try { meshCheck = require('service-manager').manager.getService(svcname).isMe(); } catch (ex) { } try { meshCheck = require('service-manager').manager.getService(svcname).isMe(); } catch (ex) { }
if (meshCheck && require('win-bcd').isSafeModeService && !require('win-bcd').isSafeModeService(svcname)) { require('win-bcd').enableSafeModeService(svcname); } if (meshCheck && require('win-bcd').isSafeModeService && !require('win-bcd').isSafeModeService(svcname)) { require('win-bcd').enableSafeModeService(svcname); }
} catch (ex) { } } catch (ex) { }
// Check the Agent Uninstall MetaData for DisplayVersion and update if not the same and only on windows
if (process.platform == 'win32') {
try {
var writtenDisplayVersion = 0, actualDisplayVersion = process.versions.commitDate.toString();
var serviceName = (_MSH().serviceName ? _MSH().serviceName : (require('_agentNodeId').serviceName() ? require('_agentNodeId').serviceName() : 'Mesh Agent'));
try { writtenDisplayVersion = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'DisplayVersion'); } catch (ex) { }
if (writtenDisplayVersion != actualDisplayVersion) { try { require('win-registry').WriteKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'DisplayVersion', actualDisplayVersion); } catch (ex) { } }
} catch (ex) { }
}
} }
if (process.platform != 'win32') { if (process.platform != 'win32') {
@ -655,33 +666,39 @@ var meshCoreObj = { action: 'coreinfo', value: (require('MeshAgent').coreHash ?
try { require('os').name().then(function (v) { meshCoreObj.osdesc = v; meshCoreObjChanged(); }); } catch (ex) { } try { require('os').name().then(function (v) { meshCoreObj.osdesc = v; meshCoreObjChanged(); }); } catch (ex) { }
// Setup logged in user monitoring (THIS IS BROKEN IN WIN7) // Setup logged in user monitoring (THIS IS BROKEN IN WIN7)
function onUserSessionChanged(user, locked) {
userSession.enumerateUsers().then(function (users) {
if (process.platform == 'linux') {
if (userSession._startTime == null) {
userSession._startTime = Date.now();
userSession._count = users.length;
}
else if (Date.now() - userSession._startTime < 10000 && users.length == userSession._count) {
userSession.removeAllListeners('changed');
return;
}
}
var u = [], a = users.Active;
if(meshCoreObj.lusers == null) { meshCoreObj.lusers = []; }
for (var i = 0; i < a.length; i++) {
var un = a[i].Domain ? (a[i].Domain + '\\' + a[i].Username) : (a[i].Username);
if (user && locked && (JSON.stringify(a[i]) === JSON.stringify(user))) { if (meshCoreObj.lusers.indexOf(un) == -1) { meshCoreObj.lusers.push(un); } }
else if (user && !locked && (JSON.stringify(a[i]) === JSON.stringify(user))) { meshCoreObj.lusers.splice(meshCoreObj.lusers.indexOf(un), 1); }
if (u.indexOf(un) == -1) { u.push(un); } // Only push users in the list once.
}
meshCoreObj.lusers = meshCoreObj.lusers;
meshCoreObj.users = u;
meshCoreObjChanged();
});
}
try { try {
var userSession = require('user-sessions'); var userSession = require('user-sessions');
userSession.on('changed', function onUserSessionChanged() { userSession.on('changed', function () { onUserSessionChanged(null, false); });
userSession.enumerateUsers().then(function (users) {
if (process.platform == 'linux') {
if (userSession._startTime == null) {
userSession._startTime = Date.now();
userSession._count = users.length;
}
else if (Date.now() - userSession._startTime < 10000 && users.length == userSession._count) {
userSession.removeAllListeners('changed');
return;
}
}
var u = [], a = users.Active;
for (var i = 0; i < a.length; i++) {
var un = a[i].Domain ? (a[i].Domain + '\\' + a[i].Username) : (a[i].Username);
if (u.indexOf(un) == -1) { u.push(un); } // Only push users in the list once.
}
meshCoreObj.users = u;
meshCoreObjChanged();
});
});
userSession.emit('changed'); userSession.emit('changed');
//userSession.on('locked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has LOCKED the desktop'); }); userSession.on('locked', function (user) { if(user != undefined && user != null) { onUserSessionChanged(user, true); } });
//userSession.on('unlocked', function (user) { sendConsoleText('[' + (user.Domain ? user.Domain + '\\' : '') + user.Username + '] has UNLOCKED the desktop'); }); userSession.on('unlocked', function (user) { if(user != undefined && user != null) { onUserSessionChanged(user, false); } });
} catch (ex) { } } catch (ex) { }
var meshServerConnectionState = 0; var meshServerConnectionState = 0;
@ -1158,6 +1175,7 @@ function handleServerCommand(data) {
tunnel.soptions = data.soptions; tunnel.soptions = data.soptions;
tunnel.consentTimeout = (tunnel.soptions && tunnel.soptions.consentTimeout) ? tunnel.soptions.consentTimeout : 30; tunnel.consentTimeout = (tunnel.soptions && tunnel.soptions.consentTimeout) ? tunnel.soptions.consentTimeout : 30;
tunnel.consentAutoAccept = (tunnel.soptions && (tunnel.soptions.consentAutoAccept === true)); tunnel.consentAutoAccept = (tunnel.soptions && (tunnel.soptions.consentAutoAccept === true));
tunnel.consentAutoAcceptIfNoUser = (tunnel.soptions && (tunnel.soptions.consentAutoAcceptIfNoUser === true));
tunnel.oldStyle = (tunnel.soptions && tunnel.soptions.oldStyle) ? tunnel.soptions.oldStyle : false; tunnel.oldStyle = (tunnel.soptions && tunnel.soptions.oldStyle) ? tunnel.soptions.oldStyle : false;
tunnel.tcpaddr = data.tcpaddr; tunnel.tcpaddr = data.tcpaddr;
tunnel.tcpport = data.tcpport; tunnel.tcpport = data.tcpport;
@ -1572,7 +1590,7 @@ function handleServerCommand(data) {
mesh.cmdchild = require('child_process').execFile('/bin/sh', ['sh'], options); mesh.cmdchild = require('child_process').execFile('/bin/sh', ['sh'], options);
mesh.cmdchild.descriptorMetadata = 'UserCommandsShell'; mesh.cmdchild.descriptorMetadata = 'UserCommandsShell';
mesh.cmdchild.stdout.on('data', function (c) { replydata += c.toString(); }); mesh.cmdchild.stdout.on('data', function (c) { replydata += c.toString(); });
mesh.cmdchild.stderr.on('data', function (c) { replydata + c.toString(); }); mesh.cmdchild.stderr.on('data', function (c) { replydata += c.toString(); });
mesh.cmdchild.stdin.write(data.cmds.split('\r').join('') + '\nexit\n'); mesh.cmdchild.stdin.write(data.cmds.split('\r').join('') + '\nexit\n');
mesh.cmdchild.on('exit', function () { mesh.cmdchild.on('exit', function () {
if (data.reply) { if (data.reply) {
@ -1936,9 +1954,9 @@ function getSystemInformation(func) {
if (process.platform == 'win32') if (process.platform == 'win32')
{ {
results.pendingReboot = require('win-info').pendingReboot(); // Pending reboot results.pendingReboot = require('win-info').pendingReboot(); // Pending reboot
if (require('computer-identifiers').volumes_promise != null) if (require('win-volumes').volumes_promise != null)
{ {
var p = require('computer-identifiers').volumes_promise(); var p = require('win-volumes').volumes_promise();
p.then(function (res) p.then(function (res)
{ {
results.hardware.windows.volumes = cleanGetBitLockerVolumeInfo(res); results.hardware.windows.volumes = cleanGetBitLockerVolumeInfo(res);
@ -1946,12 +1964,6 @@ function getSystemInformation(func) {
func(results); func(results);
}); });
} }
else if (require('computer-identifiers').volumes != null)
{
results.hardware.windows.volumes = cleanGetBitLockerVolumeInfo(require('computer-identifiers').volumes());
results.hash = hasher.syncHash(JSON.stringify(results)).toString('hex');
func(results);
}
else else
{ {
results.hash = hasher.syncHash(JSON.stringify(results)).toString('hex'); results.hash = hasher.syncHash(JSON.stringify(results)).toString('hex');
@ -2303,6 +2315,59 @@ function terminal_end()
} }
function terminal_consent_ask(ws) {
ws.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 }));
var consentMessage = currentTranslation['terminalConsent'].replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username);
var consentTitle = 'MeshCentral';
if (ws.httprequest.soptions != null) {
if (ws.httprequest.soptions.consentTitle != null) { consentTitle = ws.httprequest.soptions.consentTitle; }
if (ws.httprequest.soptions.consentMsgTerminal != null) { consentMessage = ws.httprequest.soptions.consentMsgTerminal.replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username); }
}
if (process.platform == 'win32') {
var enhanced = false;
if (ws.httprequest.oldStyle === false) {
try { require('win-userconsent'); enhanced = true; } catch (ex) { }
}
if (enhanced) {
var ipr = server_getUserImage(ws.httprequest.userid);
ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage;
ipr.consentTimeout = ws.httprequest.consentTimeout;
ipr.consentAutoAccept = ws.httprequest.consentAutoAccept;
ipr.username = ws.httprequest.realname;
ipr.tsid = ws.tsid;
ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
ws.httprequest.tpromise._consent = ipr.then(function (img) {
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), uid: this.tsid, timeout: this.consentTimeout * 1000, timeoutAutoAccept: this.consentAutoAccept, translations: this.translations, background: color_options.background, foreground: color_options.foreground });
this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent);
});
} else {
ws.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, ws.httprequest.consentTimeout);
}
} else {
ws.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, ws.httprequest.consentTimeout);
}
ws.httprequest.tpromise._consent.retPromise = ws.httprequest.tpromise;
ws.httprequest.tpromise._consent.then(function (always) {
if (always && process.platform == 'win32') { server_set_consentTimer(this.retPromise.httprequest.userid); }
// Success
MeshServerLogEx(27, null, "Local user accepted remote terminal request (" + this.retPromise.httprequest.remoteaddr + ")", this.retPromise.that.httprequest);
this.retPromise.that.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: null, msgid: 0 }));
this.retPromise._consent = null;
this.retPromise._res();
}, function (e) {
if (this.retPromise.that) {
if(this.retPromise.that.httprequest){ // User Consent Denied
MeshServerLogEx(28, null, "Local user rejected remote terminal request (" + this.retPromise.that.httprequest.remoteaddr + ")", this.retPromise.that.httprequest);
} else { } // Connection was closed server side, maybe log some messages somewhere?
this.retPromise._consent = null;
this.retPromise.that.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: e.toString(), msgid: 2 }));
} else { } // no websocket, maybe log some messages somewhere?
this.retPromise._rej(e.toString());
});
}
function terminal_promise_connection_rejected(e) function terminal_promise_connection_rejected(e)
{ {
// FAILED to connect terminal // FAILED to connect terminal
@ -2615,6 +2680,101 @@ function kvm_tunnel_consentpromise_closehandler()
if (this._consentpromise && this._consentpromise.close) { this._consentpromise.close(); } if (this._consentpromise && this._consentpromise.close) { this._consentpromise.close(); }
} }
function kvm_consent_ok(ws) {
// User Consent Prompt is not required because no user is present
if (ws.httprequest.consent && (ws.httprequest.consent & 1)){
// User Notifications is required
MeshServerLogEx(35, null, "Started remote desktop with toast notification (" + ws.httprequest.remoteaddr + ")", ws.httprequest);
var notifyMessage = currentTranslation['desktopNotify'].replace('{0}', ws.httprequest.realname);
var notifyTitle = "MeshCentral";
if (ws.httprequest.soptions != null) {
if (ws.httprequest.soptions.notifyTitle != null) { notifyTitle = ws.httprequest.soptions.notifyTitle; }
if (ws.httprequest.soptions.notifyMsgDesktop != null) { notifyMessage = ws.httprequest.soptions.notifyMsgDesktop.replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username); }
}
try { require('toaster').Toast(notifyTitle, notifyMessage, ws.tsid); } catch (ex) { }
} else {
MeshServerLogEx(36, null, "Started remote desktop without notification (" + ws.httprequest.remoteaddr + ")", ws.httprequest);
}
if (ws.httprequest.consent && (ws.httprequest.consent & 0x40)) {
// Connection Bar is required
if (ws.httprequest.desktop.kvm.connectionBar) {
ws.httprequest.desktop.kvm.connectionBar.removeAllListeners('close');
ws.httprequest.desktop.kvm.connectionBar.close();
}
try {
ws.httprequest.desktop.kvm.connectionBar = require('notifybar-desktop')(ws.httprequest.privacybartext.replace('{0}', ws.httprequest.desktop.kvm.rusers.join(', ')).replace('{1}', ws.httprequest.desktop.kvm.users.join(', ')).replace(/'/g, "\\'\\"), require('MeshAgent')._tsid, color_options);
MeshServerLogEx(31, null, "Remote Desktop Connection Bar Activated/Updated (" + ws.httprequest.remoteaddr + ")", ws.httprequest);
} catch (ex) {
MeshServerLogEx(32, null, "Remote Desktop Connection Bar Failed or not Supported (" + ws.httprequest.remoteaddr + ")", ws.httprequest);
}
if (ws.httprequest.desktop.kvm.connectionBar) {
ws.httprequest.desktop.kvm.connectionBar.state = {
userid: ws.httprequest.userid,
xuserid: ws.httprequest.xuserid,
username: ws.httprequest.username,
sessionid: ws.httprequest.sessionid,
remoteaddr: ws.httprequest.remoteaddr,
guestname: ws.httprequest.guestname,
desktop: ws.httprequest.desktop
};
ws.httprequest.desktop.kvm.connectionBar.on('close', function () {
console.info1('Connection Bar Forcefully closed');
MeshServerLogEx(29, null, "Remote Desktop Connection forcefully closed by local user (" + this.state.remoteaddr + ")", this.state);
for (var i in this.state.desktop.kvm._pipedStreams) {
this.state.desktop.kvm._pipedStreams[i].end();
}
this.state.desktop.kvm.end();
});
}
}
ws.httprequest.desktop.kvm.pipe(ws, { dataTypeSkip: 1 });
if (ws.httprequest.autolock) {
destopLockHelper_pipe(ws.httprequest);
}
}
function kvm_consent_ask(ws){
// Send a console message back using the console channel, "\n" is supported.
ws.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 }));
var consentMessage = currentTranslation['desktopConsent'].replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username);
var consentTitle = 'MeshCentral';
if (ws.httprequest.soptions != null) {
if (ws.httprequest.soptions.consentTitle != null) { consentTitle = ws.httprequest.soptions.consentTitle; }
if (ws.httprequest.soptions.consentMsgDesktop != null) { consentMessage = ws.httprequest.soptions.consentMsgDesktop.replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username); }
}
var pr;
if (process.platform == 'win32') {
var enhanced = false;
if (ws.httprequest.oldStyle === false) {
try { require('win-userconsent'); enhanced = true; } catch (ex) { }
}
if (enhanced) {
var ipr = server_getUserImage(ws.httprequest.userid);
ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage;
ipr.consentTimeout = ws.httprequest.consentTimeout;
ipr.consentAutoAccept = ws.httprequest.consentAutoAccept;
ipr.tsid = ws.tsid;
ipr.username = ws.httprequest.realname;
ipr.translation = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
pr = ipr.then(function (img) {
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), uid: this.tsid, timeout: this.consentTimeout * 1000, timeoutAutoAccept: this.consentAutoAccept, translations: this.translation, background: color_options.background, foreground: color_options.foreground });
this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent);
});
} else {
pr = require('message-box').create(consentTitle, consentMessage, ws.httprequest.consentTimeout, null, ws.tsid);
}
} else {
pr = require('message-box').create(consentTitle, consentMessage, ws.httprequest.consentTimeout, null, ws.tsid);
}
pr.ws = ws;
ws.pause();
ws._consentpromise = pr;
ws.prependOnceListener('end', kvm_tunnel_consentpromise_closehandler);
pr.then(kvm_consentpromise_resolved, kvm_consentpromise_rejected);
}
function kvm_consentpromise_rejected(e) function kvm_consentpromise_rejected(e)
{ {
if (this.ws) { if (this.ws) {
@ -2694,6 +2854,67 @@ function kvm_consentpromise_resolved(always)
this.ws = null; this.ws = null;
} }
function files_consent_ok(ws){
// User Consent Prompt is not required
if (ws.httprequest.consent && (ws.httprequest.consent & 4)) {
// User Notifications is required
MeshServerLogEx(42, null, "Started remote files with toast notification (" + ws.httprequest.remoteaddr + ")", ws.httprequest);
var notifyMessage = currentTranslation['fileNotify'].replace('{0}', ws.httprequest.realname);
var notifyTitle = "MeshCentral";
if (ws.httprequest.soptions != null) {
if (ws.httprequest.soptions.notifyTitle != null) { notifyTitle = ws.httprequest.soptions.notifyTitle; }
if (ws.httprequest.soptions.notifyMsgFiles != null) { notifyMessage = ws.httprequest.soptions.notifyMsgFiles.replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username); }
}
try { require('toaster').Toast(notifyTitle, notifyMessage); } catch (ex) { }
} else {
MeshServerLogEx(43, null, "Started remote files without notification (" + ws.httprequest.remoteaddr + ")", ws.httprequest);
}
ws.resume();
}
function files_consent_ask(ws){
// Send a console message back using the console channel, "\n" is supported.
ws.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 }));
var consentMessage = currentTranslation['fileConsent'].replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username);
var consentTitle = 'MeshCentral';
if (ws.httprequest.soptions != null) {
if (ws.httprequest.soptions.consentTitle != null) { consentTitle = ws.httprequest.soptions.consentTitle; }
if (ws.httprequest.soptions.consentMsgFiles != null) { consentMessage = ws.httprequest.soptions.consentMsgFiles.replace('{0}', ws.httprequest.realname).replace('{1}', ws.httprequest.username); }
}
var pr;
if (process.platform == 'win32') {
var enhanced = false;
if (ws.httprequest.oldStyle === false) {
try { require('win-userconsent'); enhanced = true; } catch (ex) { }
}
if (enhanced) {
var ipr = server_getUserImage(ws.httprequest.userid);
ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage;
ipr.consentTimeout = ws.httprequest.consentTimeout;
ipr.consentAutoAccept = ws.httprequest.consentAutoAccept;
ipr.username = ws.httprequest.realname;
ipr.tsid = ws.tsid;
ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
pr = ipr.then(function (img) {
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), uid: this.tsid, timeout: this.consentTimeout * 1000, timeoutAutoAccept: this.consentAutoAccept, translations: this.translations, background: color_options.background, foreground: color_options.foreground });
this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent);
});
} else {
pr = require('message-box').create(consentTitle, consentMessage, ws.httprequest.consentTimeout, null);
}
} else {
pr = require('message-box').create(consentTitle, consentMessage, ws.httprequest.consentTimeout, null);
}
pr.ws = ws;
ws.pause();
ws._consentpromise = pr;
ws.prependOnceListener('end', files_tunnel_endhandler);
pr.then(files_consentpromise_resolved, files_consentpromise_rejected);
}
function files_consentpromise_resolved(always) function files_consentpromise_resolved(always)
{ {
if (always && process.platform == 'win32') { server_set_consentTimer(this.ws.httprequest.userid); } if (always && process.platform == 'win32') { server_set_consentTimer(this.ws.httprequest.userid); }
@ -2807,6 +3028,12 @@ function onTunnelData(data)
this.descriptorMetadata = "Remote Terminal"; this.descriptorMetadata = "Remote Terminal";
// Look for a TSID
var tsid = null;
if ((this.httprequest.xoptions != null) && (typeof this.httprequest.xoptions.tsid == 'number')) { tsid = this.httprequest.xoptions.tsid; }
require('MeshAgent')._tsid = tsid;
this.tsid = tsid;
if (process.platform == 'win32') if (process.platform == 'win32')
{ {
if (!require('win-terminal').PowerShellCapable() && (this.httprequest.protocol == 6 || this.httprequest.protocol == 9)) { if (!require('win-terminal').PowerShellCapable() && (this.httprequest.protocol == 6 || this.httprequest.protocol == 9)) {
@ -2823,76 +3050,31 @@ function onTunnelData(data)
this.end = terminal_end; this.end = terminal_end;
// Perform User-Consent if needed. // Perform User-Consent if needed.
if (this.httprequest.consent && (this.httprequest.consent & 16)) if (this.httprequest.consent && (this.httprequest.consent & 16)) {
{ // User asked for consent so now we check if we can auto accept if no user is present/loggedin
this.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 })); if (this.httprequest.consentAutoAcceptIfNoUser) {
var consentMessage = currentTranslation['terminalConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); var p = require('user-sessions').enumerateUsers();
var consentTitle = 'MeshCentral'; p.sessionid = this.httprequest.sessionid;
p.ws = this;
if (this.httprequest.soptions != null) p.then(function (u) {
{ var v = [];
if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; } for (var i in u) {
if (this.httprequest.soptions.consentMsgTerminal != null) { consentMessage = this.httprequest.soptions.consentMsgTerminal.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); } if (u[i].State == 'Active') { v.push({ tsid: i, type: u[i].StationName, user: u[i].Username, domain: u[i].Domain }); }
} }
if (process.platform == 'win32') if (v.length == 0) { // No user is present, auto accept
{ this.ws.httprequest.tpromise._res();
var enhanced = false; } else {
if (this.httprequest.oldStyle === false) { // User is present so we still need consent
try { require('win-userconsent'); enhanced = true; } catch (ex) { } terminal_consent_ask(this.ws);
} }
if (enhanced)
{
var ipr = server_getUserImage(this.httprequest.userid);
ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage;
ipr.consentTimeout = this.httprequest.consentTimeout;
ipr.consentAutoAccept = this.httprequest.consentAutoAccept;
ipr.username = this.httprequest.realname;
ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
this.httprequest.tpromise._consent = ipr.then(function (img)
{
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), timeout: this.consentTimeout * 1000, timeoutAutoAccept: this.consentAutoAccept, translations: this.translations, background: color_options.background, foreground: color_options.foreground });
this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent);
});
} else
{
this.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, this.httprequest.consentTimeout);
}
} else
{
this.httprequest.tpromise._consent = require('message-box').create(consentTitle, consentMessage, this.httprequest.consentTimeout);
}
this.httprequest.tpromise._consent.retPromise = this.httprequest.tpromise;
this.httprequest.tpromise._consent.then(
function (always)
{
if (always && process.platform == 'win32') { server_set_consentTimer(this.retPromise.httprequest.userid); }
// Success
MeshServerLogEx(27, null, "Local user accepted remote terminal request (" + this.retPromise.httprequest.remoteaddr + ")", this.retPromise.that.httprequest);
this.retPromise.that.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: null, msgid: 0 }));
this.retPromise._consent = null;
this.retPromise._res();
},
function (e) {
if (this.retPromise.that) {
if(this.retPromise.that.httprequest){ // User Consent Denied
MeshServerLogEx(28, null, "Local user rejected remote terminal request (" + this.retPromise.that.httprequest.remoteaddr + ")", this.retPromise.that.httprequest);
} else { } // Connection was closed server side, maybe log some messages somewhere?
this.retPromise._consent = null;
this.retPromise.that.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: e.toString(), msgid: 2 }));
} else { } // no websocket, maybe log some messages somewhere?
this.retPromise._rej(e.toString());
}); });
} } else {
else terminal_consent_ask(this);
{ }
} else {
// User-Consent is not required, so just resolve this promise // User-Consent is not required, so just resolve this promise
this.httprequest.tpromise._res(); this.httprequest.tpromise._res();
} }
this.httprequest.tpromise.then(terminal_promise_consent_resolved, terminal_promise_consent_rejected); this.httprequest.tpromise.then(terminal_promise_consent_resolved, terminal_promise_consent_rejected);
} }
else if (this.httprequest.protocol == 2) else if (this.httprequest.protocol == 2)
@ -2916,6 +3098,7 @@ function onTunnelData(data)
var tsid = null; var tsid = null;
if ((this.httprequest.xoptions != null) && (typeof this.httprequest.xoptions.tsid == 'number')) { tsid = this.httprequest.xoptions.tsid; } if ((this.httprequest.xoptions != null) && (typeof this.httprequest.xoptions.tsid == 'number')) { tsid = this.httprequest.xoptions.tsid; }
require('MeshAgent')._tsid = tsid; require('MeshAgent')._tsid = tsid;
this.tsid = tsid;
// If MacOS, Wake up device with caffeinate // If MacOS, Wake up device with caffeinate
if(process.platform == 'darwin'){ if(process.platform == 'darwin'){
@ -2987,119 +3170,33 @@ function onTunnelData(data)
} }
// Perform notification if needed. Toast messages may not be supported on all platforms. // Perform notification if needed. Toast messages may not be supported on all platforms.
if (this.httprequest.consent && (this.httprequest.consent & 8)) if (this.httprequest.consent && (this.httprequest.consent & 8)) {
{
// User Consent Prompt is required // User asked for consent but now we check if can auto accept if no user is present
// Send a console message back using the console channel, "\n" is supported. if (this.httprequest.consentAutoAcceptIfNoUser) {
this.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 })); // Get list of users to check if we any actual users logged in, and if users logged in, we still need consent
var consentMessage = currentTranslation['desktopConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); var p = require('user-sessions').enumerateUsers();
var consentTitle = 'MeshCentral'; p.sessionid = this.httprequest.sessionid;
if (this.httprequest.soptions != null) p.ws = this;
{ p.then(function (u) {
if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; } var v = [];
if (this.httprequest.soptions.consentMsgDesktop != null) { consentMessage = this.httprequest.soptions.consentMsgDesktop.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); } for (var i in u) {
if (u[i].State == 'Active') { v.push({ tsid: i, type: u[i].StationName, user: u[i].Username, domain: u[i].Domain }); }
}
if (v.length == 0) { // No user is present, auto accept
kvm_consent_ok(this.ws);
} else {
// User is present so we still need consent
kvm_consent_ask(this.ws);
}
});
} else {
// User Consent Prompt is required
kvm_consent_ask(this);
} }
var pr; } else {
if (process.platform == 'win32')
{
var enhanced = false;
if (this.httprequest.oldStyle === false) {
try { require('win-userconsent'); enhanced = true; } catch (ex) { }
}
if (enhanced)
{
var ipr = server_getUserImage(this.httprequest.userid);
ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage;
ipr.consentTimeout = this.httprequest.consentTimeout;
ipr.consentAutoAccept = this.httprequest.consentAutoAccept;
ipr.tsid = tsid;
ipr.username = this.httprequest.realname;
ipr.translation = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
pr = ipr.then(function (img)
{
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), uid: this.tsid, timeout: this.consentTimeout * 1000, timeoutAutoAccept: this.consentAutoAccept, translations: this.translation, background: color_options.background, foreground: color_options.foreground });
this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent);
});
}
else
{
pr = require('message-box').create(consentTitle, consentMessage, this.httprequest.consentTimeout, null, tsid);
}
}
else
{
pr = require('message-box').create(consentTitle, consentMessage, this.httprequest.consentTimeout, null, tsid);
}
pr.ws = this;
this.pause();
this._consentpromise = pr;
this.prependOnceListener('end', kvm_tunnel_consentpromise_closehandler);
pr.then(kvm_consentpromise_resolved, kvm_consentpromise_rejected);
}
else
{
// User Consent Prompt is not required // User Consent Prompt is not required
if (this.httprequest.consent && (this.httprequest.consent & 1)) kvm_consent_ok(this);
{
// User Notifications is required
MeshServerLogEx(35, null, "Started remote desktop with toast notification (" + this.httprequest.remoteaddr + ")", this.httprequest);
var notifyMessage = currentTranslation['desktopNotify'].replace('{0}', this.httprequest.realname);
var notifyTitle = "MeshCentral";
if (this.httprequest.soptions != null) {
if (this.httprequest.soptions.notifyTitle != null) { notifyTitle = this.httprequest.soptions.notifyTitle; }
if (this.httprequest.soptions.notifyMsgDesktop != null) { notifyMessage = this.httprequest.soptions.notifyMsgDesktop.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); }
}
try { require('toaster').Toast(notifyTitle, notifyMessage, tsid); } catch (ex) { }
} else
{
MeshServerLogEx(36, null, "Started remote desktop without notification (" + this.httprequest.remoteaddr + ")", this.httprequest);
}
if (this.httprequest.consent && (this.httprequest.consent & 0x40))
{
// Connection Bar is required
if (this.httprequest.desktop.kvm.connectionBar)
{
this.httprequest.desktop.kvm.connectionBar.removeAllListeners('close');
this.httprequest.desktop.kvm.connectionBar.close();
}
try
{
this.httprequest.desktop.kvm.connectionBar = require('notifybar-desktop')(this.httprequest.privacybartext.replace('{0}', this.httprequest.desktop.kvm.rusers.join(', ')).replace('{1}', this.httprequest.desktop.kvm.users.join(', ')).replace(/'/g, "\\'\\"), require('MeshAgent')._tsid, color_options);
MeshServerLogEx(31, null, "Remote Desktop Connection Bar Activated/Updated (" + this.httprequest.remoteaddr + ")", this.httprequest);
} catch (ex) {
MeshServerLogEx(32, null, "Remote Desktop Connection Bar Failed or not Supported (" + this.httprequest.remoteaddr + ")", this.httprequest);
}
if (this.httprequest.desktop.kvm.connectionBar)
{
this.httprequest.desktop.kvm.connectionBar.state =
{
userid: this.httprequest.userid,
xuserid: this.httprequest.xuserid,
username: this.httprequest.username,
sessionid: this.httprequest.sessionid,
remoteaddr: this.httprequest.remoteaddr,
guestname: this.httprequest.guestname,
desktop: this.httprequest.desktop
};
this.httprequest.desktop.kvm.connectionBar.on('close', function ()
{
console.info1('Connection Bar Forcefully closed');
MeshServerLogEx(29, null, "Remote Desktop Connection forcefully closed by local user (" + this.state.remoteaddr + ")", this.state);
for (var i in this.state.desktop.kvm._pipedStreams)
{
this.state.desktop.kvm._pipedStreams[i].end();
}
this.state.desktop.kvm.end();
});
}
}
this.httprequest.desktop.kvm.pipe(this, { dataTypeSkip: 1 });
if (this.httprequest.autolock)
{
destopLockHelper_pipe(this.httprequest);
}
} }
this.removeAllListeners('data'); this.removeAllListeners('data');
@ -3121,6 +3218,12 @@ function onTunnelData(data)
this.descriptorMetadata = "Remote Files"; this.descriptorMetadata = "Remote Files";
// Look for a TSID
var tsid = null;
if ((this.httprequest.xoptions != null) && (typeof this.httprequest.xoptions.tsid == 'number')) { tsid = this.httprequest.xoptions.tsid; }
require('MeshAgent')._tsid = tsid;
this.tsid = tsid;
// Add the files session to the count to update the server // Add the files session to the count to update the server
if (this.httprequest.userid != null) { if (this.httprequest.userid != null) {
var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest); var userid = getUserIdAndGuestNameFromHttpRequest(this.httprequest);
@ -3143,71 +3246,31 @@ function onTunnelData(data)
// Perform notification if needed. Toast messages may not be supported on all platforms. // Perform notification if needed. Toast messages may not be supported on all platforms.
if (this.httprequest.consent && (this.httprequest.consent & 32)) if (this.httprequest.consent && (this.httprequest.consent & 32))
{ {
// User Consent Prompt is required // User asked for consent so now we check if we can auto accept if no user is present/loggedin
// Send a console message back using the console channel, "\n" is supported. if (this.httprequest.consentAutoAcceptIfNoUser) {
this.write(JSON.stringify({ ctrlChannel: '102938', type: 'console', msg: "Waiting for user to grant access...", msgid: 1 })); var p = require('user-sessions').enumerateUsers();
var consentMessage = currentTranslation['fileConsent'].replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); p.sessionid = this.httprequest.sessionid;
var consentTitle = 'MeshCentral'; p.ws = this;
p.then(function (u) {
if (this.httprequest.soptions != null) var v = [];
{ for (var i in u) {
if (this.httprequest.soptions.consentTitle != null) { consentTitle = this.httprequest.soptions.consentTitle; } if (u[i].State == 'Active') { v.push({ tsid: i, type: u[i].StationName, user: u[i].Username, domain: u[i].Domain }); }
if (this.httprequest.soptions.consentMsgFiles != null) { consentMessage = this.httprequest.soptions.consentMsgFiles.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); } }
} if (v.length == 0) { // No user is present, auto accept
var pr; // User Consent Prompt is not required
if (process.platform == 'win32') files_consent_ok(this.ws);
{ } else {
var enhanced = false; // User is present so we still need consent
if (this.httprequest.oldStyle === false) { files_consent_ask(this.ws);
try { require('win-userconsent'); enhanced = true; } catch (ex) { } }
} });
if (enhanced)
{
var ipr = server_getUserImage(this.httprequest.userid);
ipr.consentTitle = consentTitle;
ipr.consentMessage = consentMessage;
ipr.consentTimeout = this.httprequest.consentTimeout;
ipr.consentAutoAccept = this.httprequest.consentAutoAccept;
ipr.username = this.httprequest.realname;
ipr.translations = { Allow: currentTranslation['allow'], Deny: currentTranslation['deny'], Auto: currentTranslation['autoAllowForFive'], Caption: consentMessage };
pr = ipr.then(function (img)
{
this.consent = require('win-userconsent').create(this.consentTitle, this.consentMessage, this.username, { b64Image: img.split(',').pop(), timeout: this.consentTimeout * 1000, timeoutAutoAccept: this.consentAutoAccept, translations: this.translations, background: color_options.background, foreground: color_options.foreground });
this.__childPromise.close = this.consent.close.bind(this.consent);
return (this.consent);
});
} else
{
pr = require('message-box').create(consentTitle, consentMessage, this.httprequest.consentTimeout, null);
}
}
else
{
pr = require('message-box').create(consentTitle, consentMessage, this.httprequest.consentTimeout, null);
}
pr.ws = this;
this.pause();
this._consentpromise = pr;
this.prependOnceListener('end', files_tunnel_endhandler);
pr.then(files_consentpromise_resolved, files_consentpromise_rejected);
}
else
{
// User Consent Prompt is not required
if (this.httprequest.consent && (this.httprequest.consent & 4)) {
// User Notifications is required
MeshServerLogEx(42, null, "Started remote files with toast notification (" + this.httprequest.remoteaddr + ")", this.httprequest);
var notifyMessage = currentTranslation['fileNotify'].replace('{0}', this.httprequest.realname);
var notifyTitle = "MeshCentral";
if (this.httprequest.soptions != null) {
if (this.httprequest.soptions.notifyTitle != null) { notifyTitle = this.httprequest.soptions.notifyTitle; }
if (this.httprequest.soptions.notifyMsgFiles != null) { notifyMessage = this.httprequest.soptions.notifyMsgFiles.replace('{0}', this.httprequest.realname).replace('{1}', this.httprequest.username); }
}
try { require('toaster').Toast(notifyTitle, notifyMessage); } catch (ex) { }
} else { } else {
MeshServerLogEx(43, null, "Started remote files without notification (" + this.httprequest.remoteaddr + ")", this.httprequest); // User Consent Prompt is required
files_consent_ask(this);
} }
this.resume(); } else {
// User Consent Prompt is not required
files_consent_ok(this);
} }
// Setup files // Setup files
@ -3695,7 +3758,14 @@ function onTunnelControlData(data, ws) {
{ // Desktop { // Desktop
// Switch the user input from websocket to webrtc at this point. // Switch the user input from websocket to webrtc at this point.
ws.unpipe(ws.httprequest.desktop.kvm); ws.unpipe(ws.httprequest.desktop.kvm);
try { ws.webrtc.rtcchannel.pipe(ws.httprequest.desktop.kvm, { dataTypeSkip: 1, end: false }); } catch (ex) { sendConsoleText('EX2'); } // 0 = Binary, 1 = Text. if ((ws.httprequest.desktopviewonly != true) && ((ws.httprequest.rights == 0xFFFFFFFF) || (((ws.httprequest.rights & MESHRIGHT_REMOTECONTROL) != 0) && ((ws.httprequest.rights & MESHRIGHT_REMOTEVIEW) == 0)))) {
// If we have remote control rights, pipe the KVM input
try { ws.webrtc.rtcchannel.pipe(ws.httprequest.desktop.kvm, { dataTypeSkip: 1, end: false }); } catch (ex) { sendConsoleText('EX2'); } // 0 = Binary, 1 = Text.
} else {
// We need to only pipe non-mouse & non-keyboard inputs.
// sendConsoleText('Warning: No Remote Desktop Input Rights.');
// TODO!!!
}
ws.resume(); // Resume the websocket to keep receiving control data ws.resume(); // Resume the websocket to keep receiving control data
} }
ws.write('{\"ctrlChannel\":\"102938\",\"type\":\"webrtc2\"}'); // Indicates we will no longer get any data on websocket, switching to WebRTC at this point. ws.write('{\"ctrlChannel\":\"102938\",\"type\":\"webrtc2\"}'); // Indicates we will no longer get any data on websocket, switching to WebRTC at this point.
@ -3881,7 +3951,7 @@ function processConsoleCommand(cmd, args, rights, sessionid) {
if (require('os').dns != null) { availcommands += ',dnsinfo'; } if (require('os').dns != null) { availcommands += ',dnsinfo'; }
try { require('linux-dhcp'); availcommands += ',dhcp'; } catch (ex) { } try { require('linux-dhcp'); availcommands += ',dhcp'; } catch (ex) { }
if (process.platform == 'win32') { if (process.platform == 'win32') {
availcommands += ',bitlocker,cs,wpfhwacceleration,uac,volumes,rdpport'; availcommands += ',bitlocker,cs,wpfhwacceleration,uac,volumes,rdpport,deskbackground';
if (bcdOK()) { availcommands += ',safemode'; } if (bcdOK()) { availcommands += ',safemode'; }
if (require('notifybar-desktop').DefaultPinned != null) { availcommands += ',privacybar'; } if (require('notifybar-desktop').DefaultPinned != null) { availcommands += ',privacybar'; }
try { require('win-utils'); availcommands += ',taskbar'; } catch (ex) { } try { require('win-utils'); availcommands += ',taskbar'; } catch (ex) { }
@ -4044,12 +4114,9 @@ function processConsoleCommand(cmd, args, rights, sessionid) {
break; break;
case 'bitlocker': case 'bitlocker':
if (process.platform == 'win32') { if (process.platform == 'win32') {
if (require('computer-identifiers').volumes_promise != null) { if (require('win-volumes').volumes_promise != null) {
var p = require('computer-identifiers').volumes_promise(); var p = require('win-volumes').volumes_promise();
p.then(function (res) { sendConsoleText(JSON.stringify(cleanGetBitLockerVolumeInfo(res), null, 1), this.session); }); p.then(function (res) { sendConsoleText(JSON.stringify(cleanGetBitLockerVolumeInfo(res), null, 1), this.session); });
response = "Please wait...";
} else if (require('computer-identifiers').volumes != null) {
sendConsoleText(JSON.stringify(cleanGetBitLockerVolumeInfo(require('computer-identifiers').volumes()), null, 1), this.session);
} }
} }
break; break;
@ -4299,7 +4366,7 @@ function processConsoleCommand(cmd, args, rights, sessionid) {
} }
case 'agentmsg': { case 'agentmsg': {
if (args['_'].length == 0) { if (args['_'].length == 0) {
response = "Proper usage:\r\n agentmsg add \"[message]\" [iconIndex]\r\n agentmsg remove [index]\r\n agentmsg list"; // Display usage response = "Proper usage:\r\n agentmsg add \"[message]\" [iconIndex]\r\n agentmsg remove [id]\r\n agentmsg list"; // Display usage
} else { } else {
if ((args['_'][0] == 'add') && (args['_'].length > 1)) { if ((args['_'][0] == 'add') && (args['_'].length > 1)) {
var msgID, iconIndex = 0; var msgID, iconIndex = 0;
@ -4517,10 +4584,11 @@ function processConsoleCommand(cmd, args, rights, sessionid) {
if (process.platform == 'win32') { if (process.platform == 'win32') {
// Check the Agent Uninstall MetaData for correctness, as the installer may have written an incorrect value // Check the Agent Uninstall MetaData for correctness, as the installer may have written an incorrect value
var writtenSize = 0; var writtenSize = 0;
try { writtenSize = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MeshCentralAgent', 'EstimatedSize'); } catch (ex) { response = ex; } var serviceName = (_MSH().serviceName ? _MSH().serviceName : (require('_agentNodeId').serviceName() ? require('_agentNodeId').serviceName() : 'Mesh Agent'));
try { writtenSize = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'EstimatedSize'); } catch (ex) { response = ex; }
if (writtenSize != actualSize) { if (writtenSize != actualSize) {
response = "Size updated from: " + writtenSize + " to: " + actualSize; response = "Size updated from: " + writtenSize + " to: " + actualSize;
try { require('win-registry').WriteKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MeshCentralAgent', 'EstimatedSize', actualSize); } catch (ex) { response = ex; } try { require('win-registry').WriteKey(require('win-registry').HKEY.LocalMachine, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\' + serviceName, 'EstimatedSize', actualSize); } catch (ex) { response = ex; }
} else } else
{ response = "Agent Size: " + actualSize + " kb"; } { response = "Agent Size: " + actualSize + " kb"; }
} else } else

View file

@ -422,106 +422,6 @@ function windows_wmic_results(str)
return (result); return (result);
} }
function windows_volumes()
{
var promise = require('promise');
var p1 = new promise(function (res, rej) { this._res = res; this._rej = rej; });
var p2 = new promise(function (res, rej) { this._res = res; this._rej = rej; });
p1._p2 = p2;
p2._p1 = p1;
var cmd = '"Get-Volume | Select-Object -Property DriveLetter,FileSystemLabel,FileSystemType,Size,SizeRemaining,DriveType | ConvertTo-Csv -NoTypeInformation"';
var child = require('child_process').execFile(process.env['windir'] + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['powershell', '-noprofile', '-nologo', '-command', cmd]);
p1.child = child;
child.promise = p1;
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.str = ''; child.stderr.on('data', function (c) { this.str += c.toString(); });
child.on('exit', function (c)
{
var a, i, tokens, key;
var ret = {};
a = this.stdout.str.trim().split('\r\n');
for (i = 1; i < a.length; ++i)
{
tokens = a[i].split(',');
if (tokens[0] != '' && tokens[1] != undefined)
{
ret[tokens[0].split('"')[1]] =
{
name: tokens[1].split('"')[1],
type: tokens[2].split('"')[1],
size: tokens[3].split('"')[1],
sizeremaining: tokens[4].split('"')[1],
removable: tokens[5].split('"')[1] == 'Removable',
cdrom: tokens[5].split('"')[1] == 'CD-ROM'
};
}
}
this.promise._res({ r: ret, t: tokens });
});
p1.then(function (j)
{
var ret = j.r;
var tokens = j.t;
var cmd = '"Get-BitLockerVolume | Select-Object -Property MountPoint,VolumeStatus,ProtectionStatus | ConvertTo-Csv -NoTypeInformation"';
var child = require('child_process').execFile(process.env['windir'] + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['powershell', '-noprofile', '-nologo', '-command', cmd]);
p2.child = child;
child.promise = p2;
child.tokens = tokens;
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.str = ''; child.stderr.on('data', function (c) { this.str += c.toString(); });
child.on('exit', function ()
{
var i;
var a = this.stdout.str.trim().split('\r\n');
for (i = 1; i < a.length; ++i)
{
tokens = a[i].split(',');
key = tokens[0].split(':').shift().split('"').pop();
if (ret[key] != null)
{
ret[key].volumeStatus = tokens[1].split('"')[1];
ret[key].protectionStatus = tokens[2].split('"')[1];
try {
var foundIDMarkedLine = false, foundMarkedLine = false, identifier = '', password = '';
var keychild = require('child_process').execFile(process.env['windir'] + '\\system32\\cmd.exe', ['cmd', '/c', 'manage-bde -protectors -get ', tokens[0].split('"')[1], ' -Type recoverypassword'], {});
keychild.stdout.str = ''; keychild.stdout.on('data', function (c) { this.str += c.toString(); });
keychild.waitExit();
var lines = keychild.stdout.str.trim().split('\r\n');
for (var x = 0; x < lines.length; x++) { // Loop each line
var abc = lines[x].trim();
var englishidpass = (abc !== '' && abc.includes('Numerical Password:')); // English ID
var germanidpass = (abc !== '' && abc.includes('Numerisches Kennwort:')); // German ID
var frenchidpass = (abc !== '' && abc.includes('Mot de passe num')); // French ID
var englishpass = (abc !== '' && abc.includes('Password:') && !abc.includes('Numerical Password:')); // English Password
var germanpass = (abc !== '' && abc.includes('Kennwort:') && !abc.includes('Numerisches Kennwort:')); // German Password
var frenchpass = (abc !== '' && abc.includes('Mot de passe :') && !abc.includes('Mot de passe num')); // French Password
if (englishidpass || germanidpass || frenchidpass|| englishpass || germanpass || frenchpass) {
var nextline = lines[x + 1].trim();
if (x + 1 < lines.length && (nextline !== '' && (nextline.startsWith('ID:') || nextline.startsWith('ID :')) )) {
identifier = nextline.replace('ID:','').replace('ID :', '').trim();
foundIDMarkedLine = true;
}else if (x + 1 < lines.length && nextline !== '') {
password = nextline;
foundMarkedLine = true;
}
}
}
ret[key].identifier = (foundIDMarkedLine ? identifier : ''); // Set Bitlocker Identifier
ret[key].recoveryPassword = (foundMarkedLine ? password : ''); // Set Bitlocker Password
} catch(ex) { }
}
}
this.promise._res(ret);
});
});
return (p2);
}
function windows_identifiers() function windows_identifiers()
{ {
var ret = { windows: {} }; var ret = { windows: {} };
@ -803,12 +703,13 @@ function hexToAscii(hexString) {
function win_chassisType() function win_chassisType()
{ {
// needs to be replaced with win-wmi but due to bug in win-wmi it doesnt handle arrays correctly // needs to be replaced with win-wmi but due to bug in win-wmi it doesnt handle arrays correctly
var cmd = '"Get-CimInstance Win32_SystemEnclosure | Select-Object -ExpandProperty ChassisTypes"'; var child = require('child_process').execFile(process.env['windir'] + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['powershell', '-noprofile', '-nologo', '-command', '-'], {});
var child = require('child_process').execFile(process.env['windir'] + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['powershell', '-noprofile', '-nologo', '-command', cmd], {});
if (child == null) { return ([]); } if (child == null) { return ([]); }
child.descriptorMetadata = 'process-manager'; child.descriptorMetadata = 'process-manager';
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); }); child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.str = ''; child.stderr.on('data', function (c) { this.str += c.toString(); }); child.stderr.str = ''; child.stderr.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('Get-WmiObject Win32_SystemEnclosure | Select-Object -ExpandProperty ChassisTypes\r\n');
child.stdin.write('exit\r\n');
child.waitExit(); child.waitExit();
try { try {
return (parseInt(child.stdout.str)); return (parseInt(child.stdout.str));
@ -992,11 +893,6 @@ module.exports.isVM = function isVM()
return (ret); return (ret);
}; };
if (process.platform == 'win32')
{
module.exports.volumes_promise = windows_volumes;
}
// bios_date = BIOS->ReleaseDate // bios_date = BIOS->ReleaseDate
// bios_vendor = BIOS->Manufacturer // bios_vendor = BIOS->Manufacturer
// bios_version = BIOS->SMBIOSBIOSVersion // bios_version = BIOS->SMBIOSBIOSVersion

View file

@ -243,15 +243,20 @@ function installedApps()
function defender(){ function defender(){
var promise = require('promise'); var promise = require('promise');
var ret = new promise(function (a, r) { this._resolve = a; this._reject = r; }); var ret = new promise(function (a, r) { this._resolve = a; this._reject = r; });
var cmd = '"Get-MpComputerStatus | Select-Object RealTimeProtectionEnabled,IsTamperProtected | ConvertTo-JSON"'; ret.child = require('child_process').execFile(process.env['windir'] + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['powershell', '-noprofile', '-nologo', '-command', '-'], {});
ret.child = require('child_process').execFile(process.env['windir'] + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['powershell', '-noprofile', '-nologo', '-command', cmd], {});
ret.child.promise = ret; ret.child.promise = ret;
ret.child.stdout.str = ''; ret.child.stdout.on('data', function (c) { this.str += c.toString(); }); ret.child.stdout.str = ''; ret.child.stdout.on('data', function (c) { this.str += c.toString(); });
ret.child.stderr.str = ''; ret.child.stderr.on('data', function (c) { this.str += c.toString(); }); ret.child.stderr.str = ''; ret.child.stderr.on('data', function (c) { this.str += c.toString(); });
ret.child.stdin.write('Get-MpComputerStatus | Select-Object RealTimeProtectionEnabled,IsTamperProtected | ConvertTo-JSON\r\n');
ret.child.stdin.write('exit\r\n');
ret.child.on('exit', function (c) { ret.child.on('exit', function (c) {
if (this.stdout.str == '') { this.promise._resolve({}); return; } if (this.stdout.str == '') { this.promise._resolve({}); return; }
var abc = JSON.parse(this.stdout.str.trim()) try {
this.promise._resolve({ RealTimeProtection: abc.RealTimeProtectionEnabled, TamperProtected: abc.IsTamperProtected }); var abc = JSON.parse(this.stdout.str.trim());
this.promise._resolve({ RealTimeProtection: abc.RealTimeProtectionEnabled, TamperProtected: abc.IsTamperProtected });
} catch (ex) {
this.promise._resolve({}); return;
}
}); });
return (ret); return (ret);
} }

View file

@ -39,17 +39,90 @@ function getVolumes()
{ {
ret[v[i].DeviceID] = trimObject(v[i]); ret[v[i].DeviceID] = trimObject(v[i]);
} }
try {
v = require('win-wmi').query('ROOT\\CIMV2\\Security\\MicrosoftVolumeEncryption', 'SELECT * FROM Win32_EncryptableVolume'); v = require('win-wmi').query('ROOT\\CIMV2\\Security\\MicrosoftVolumeEncryption', 'SELECT * FROM Win32_EncryptableVolume');
for (i in v) for (i in v)
{
var tmp = trimObject(v[i]);
for (var k in tmp)
{ {
ret[tmp.DeviceID][k] = tmp[k]; var tmp = trimObject(v[i]);
for (var k in tmp)
{
ret[tmp.DeviceID][k] = tmp[k];
}
} }
} } catch (ex) { }
return (ret); return (ret);
} }
module.exports = { getVolumes: function () { try { return (getVolumes()); } catch (x) { return ({}); } } }; function windows_volumes()
{
var promise = require('promise');
var p1 = new promise(function (res, rej) { this._res = res; this._rej = rej; });
var ret = {};
var values = require('win-wmi').query('ROOT\\CIMV2', 'SELECT * FROM Win32_LogicalDisk', ['DeviceID', 'VolumeName', 'FileSystem', 'Size', 'FreeSpace', 'DriveType']);
if(values[0]){
for (var i = 0; i < values.length; ++i) {
var drive = values[i]['DeviceID'].slice(0,-1);
ret[drive] = {
name: (values[i]['VolumeName'] ? values[i]['VolumeName'] : ""),
type: (values[i]['FileSystem'] ? values[i]['FileSystem'] : "Unknown"),
size: (values[i]['Size'] ? values[i]['Size'] : 0),
sizeremaining: (values[i]['FreeSpace'] ? values[i]['FreeSpace'] : 0),
removable: (values[i]['DriveType'] == 2),
cdrom: (values[i]['DriveType'] == 5)
};
}
}
try {
values = require('win-wmi').query('ROOT\\CIMV2\\Security\\MicrosoftVolumeEncryption', 'SELECT * FROM Win32_EncryptableVolume', ['DriveLetter','ConversionStatus','ProtectionStatus']);
if(values[0]){
for (var i = 0; i < values.length; ++i) {
var drive = values[i]['DriveLetter'].slice(0,-1);
var statuses = {
0: 'FullyDecrypted',
1: 'FullyEncrypted',
2: 'EncryptionInProgress',
3: 'DecryptionInProgress',
4: 'EncryptionPaused',
5: 'DecryptionPaused'
};
ret[drive].volumeStatus = statuses.hasOwnProperty(values[i].ConversionStatus) ? statuses[values[i].ConversionStatus] : 'FullyDecrypted';
ret[drive].protectionStatus = (values[i].ProtectionStatus == 0 ? 'Off' : (values[i].ProtectionStatus == 1 ? 'On' : 'Unknown'));
try {
var foundIDMarkedLine = false, foundMarkedLine = false, identifier = '', password = '';
var keychild = require('child_process').execFile(process.env['windir'] + '\\system32\\cmd.exe', ['/c', 'manage-bde -protectors -get ' + drive + ': -Type recoverypassword'], {});
keychild.stdout.str = ''; keychild.stdout.on('data', function (c) { this.str += c.toString(); });
keychild.waitExit();
var lines = keychild.stdout.str.trim().split('\r\n');
for (var x = 0; x < lines.length; x++) { // Loop each line
var abc = lines[x].trim();
var englishidpass = (abc !== '' && abc.includes('Numerical Password:')); // English ID
var germanidpass = (abc !== '' && abc.includes('Numerisches Kennwort:')); // German ID
var frenchidpass = (abc !== '' && abc.includes('Mot de passe num')); // French ID
var englishpass = (abc !== '' && abc.includes('Password:') && !abc.includes('Numerical Password:')); // English Password
var germanpass = (abc !== '' && abc.includes('Kennwort:') && !abc.includes('Numerisches Kennwort:')); // German Password
var frenchpass = (abc !== '' && abc.includes('Mot de passe :') && !abc.includes('Mot de passe num')); // French Password
if (englishidpass || germanidpass || frenchidpass|| englishpass || germanpass || frenchpass) {
var nextline = lines[x + 1].trim();
if (x + 1 < lines.length && (nextline !== '' && (nextline.startsWith('ID:') || nextline.startsWith('ID :')) )) {
identifier = nextline.replace('ID:','').replace('ID :', '').trim();
foundIDMarkedLine = true;
}else if (x + 1 < lines.length && nextline !== '') {
password = nextline;
foundMarkedLine = true;
}
}
}
ret[drive].identifier = (foundIDMarkedLine ? identifier : ''); // Set Bitlocker Identifier
ret[drive].recoveryPassword = (foundMarkedLine ? password : ''); // Set Bitlocker Password
} catch(ex) { } // just carry on as we cant get bitlocker key
}
}
p1._res(ret);
} catch (ex) { p1._res(ret); } // just return volumes as cant get encryption/bitlocker
return (p1);
}
module.exports = {
getVolumes: function () { try { return (getVolumes()); } catch (x) { return ({}); } },
volumes_promise: windows_volumes
};

View file

@ -870,7 +870,7 @@ function onTunnelControlData(data, ws) {
if (process.platform == 'win32') { if (process.platform == 'win32') {
MeshServerLog("Locking remote user out of desktop", ws.httprequest); MeshServerLog("Locking remote user out of desktop", ws.httprequest);
var child = require('child_process'); var child = require('child_process');
child.execFile(process.env['windir'] + '\\system32\\cmd.exe', ['cmd', '/c', 'RunDll32.exe user32.dll,LockWorkStation'], { type: 1 }); child.execFile(process.env['windir'] + '\\system32\\cmd.exe', ['/c', 'RunDll32.exe user32.dll,LockWorkStation'], { type: 1 });
} }
} catch (e) { } } catch (e) { }
break; break;

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -719,7 +719,8 @@ module.exports.CreateWebRelay = function (parent, db, args, domain, mtype) {
} }
else if (blockHeaders.indexOf(i) == -1) { obj.res.set(i.trim(), header[i]); } // Set the headers if not blocked else if (blockHeaders.indexOf(i) == -1) { obj.res.set(i.trim(), header[i]); } // Set the headers if not blocked
} }
obj.res.set('Content-Security-Policy', "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob:;"); // Set an "allow all" policy, see if the can restrict this in the future // Dont set any Content-Security-Policy at all because some applications like Node-Red, access external websites from there javascript which would be forbidden by the below CSP
//obj.res.set('Content-Security-Policy', "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob:;"); // Set an "allow all" policy, see if the can restrict this in the future
//obj.res.set('Content-Security-Policy', "default-src * 'unsafe-inline' 'unsafe-eval'; script-src * 'unsafe-inline' 'unsafe-eval'; connect-src * 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src *; style-src * 'unsafe-inline';"); // Set an "allow all" policy, see if the can restrict this in the future //obj.res.set('Content-Security-Policy', "default-src * 'unsafe-inline' 'unsafe-eval'; script-src * 'unsafe-inline' 'unsafe-eval'; connect-src * 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src *; style-src * 'unsafe-inline';"); // Set an "allow all" policy, see if the can restrict this in the future
obj.res.set('Cache-Control', 'no-store'); // Tell the browser not to cache the responses since since the relay port can be used for many relays obj.res.set('Cache-Control', 'no-store'); // Tell the browser not to cache the responses since since the relay port can be used for many relays
} }

View file

@ -1049,6 +1049,7 @@ module.exports.CertificateOperations = function (parent) {
config.domains[i].certs = r.dns[i]; config.domains[i].certs = r.dns[i];
} else { } else {
console.log("WARNING: File \"webserver-" + i + "-cert-public.crt\" missing, domain \"" + i + "\" will not work correctly."); console.log("WARNING: File \"webserver-" + i + "-cert-public.crt\" missing, domain \"" + i + "\" will not work correctly.");
rcountmax++;
} }
} else { } else {
// If the web certificate already exist, load it. Load both certificate and private key // If the web certificate already exist, load it. Load both certificate and private key

View file

@ -155,12 +155,12 @@ module.exports.objKeysToLower = function (obj, exceptions, parent) {
return obj; return obj;
}; };
// Escape and unescape field names so there are no invalid characters for MongoDB // Escape and unescape field names so there are no invalid characters for MongoDB/NeDB ("$", ",", ".", see https://github.com/seald/nedb/tree/master?tab=readme-ov-file#inserting-documents)
module.exports.escapeFieldName = function (name) { if ((name.indexOf('%') == -1) && (name.indexOf('.') == -1) && (name.indexOf('$') == -1)) return name; return name.split('%').join('%25').split('.').join('%2E').split('$').join('%24'); }; module.exports.escapeFieldName = function (name) { if ((name.indexOf(',') == -1) && (name.indexOf('%') == -1) && (name.indexOf('.') == -1) && (name.indexOf('$') == -1)) return name; return name.split('%').join('%25').split('.').join('%2E').split('$').join('%24').split(',').join('%2C'); };
module.exports.unEscapeFieldName = function (name) { if (name.indexOf('%') == -1) return name; return name.split('%2E').join('.').split('%24').join('$').split('%25').join('%'); }; module.exports.unEscapeFieldName = function (name) { if (name.indexOf('%') == -1) return name; return name.split('%2C').join(',').split('%2E').join('.').split('%24').join('$').split('%25').join('%'); };
// Escape all links, SSH and RDP usernames // Escape all links, SSH and RDP usernames
// This is required for databases like NeDB that don't accept "." as part of a field name. // This is required for databases like NeDB that don't accept "." or "," as part of a field name.
module.exports.escapeLinksFieldNameEx = function (docx) { if ((docx.links == null) && (docx.ssh == null) && (docx.rdp == null)) { return docx; } return module.exports.escapeLinksFieldName(docx); }; module.exports.escapeLinksFieldNameEx = function (docx) { if ((docx.links == null) && (docx.ssh == null) && (docx.rdp == null)) { return docx; } return module.exports.escapeLinksFieldName(docx); };
module.exports.escapeLinksFieldName = function (docx) { module.exports.escapeLinksFieldName = function (docx) {
var doc = Object.assign({}, docx); var doc = Object.assign({}, docx);

302
db.js
View file

@ -30,7 +30,7 @@ module.exports.CreateDB = function (parent, func) {
var Datastore = null; var Datastore = null;
var expireEventsSeconds = (60 * 60 * 24 * 20); // By default, expire events after 20 days (1728000). (Seconds * Minutes * Hours * Days) var expireEventsSeconds = (60 * 60 * 24 * 20); // By default, expire events after 20 days (1728000). (Seconds * Minutes * Hours * Days)
var expirePowerEventsSeconds = (60 * 60 * 24 * 10); // By default, expire power events after 10 days (864000). (Seconds * Minutes * Hours * Days) var expirePowerEventsSeconds = (60 * 60 * 24 * 10); // By default, expire power events after 10 days (864000). (Seconds * Minutes * Hours * Days)
var expireServerStatsSeconds = (60 * 60 * 24 * 30); // By default, expire power events after 30 days (2592000). (Seconds * Minutes * Hours * Days) var expireServerStatsSeconds = (60 * 60 * 24 * 30); // By default, expire server stats after 30 days (2592000). (Seconds * Minutes * Hours * Days)
const common = require('./common.js'); const common = require('./common.js');
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
@ -781,10 +781,10 @@ module.exports.CreateDB = function (parent, func) {
parent.debug('db', 'SQlite config options: ' + JSON.stringify(obj.sqliteConfig, null, 4)); parent.debug('db', 'SQlite config options: ' + JSON.stringify(obj.sqliteConfig, null, 4));
if (obj.sqliteConfig.journalMode == 'memory') { console.log('[WARNING] journal_mode=memory: this can lead to database corruption if there is a crash during a transaction. See https://www.sqlite.org/pragma.html#pragma_journal_mode') }; if (obj.sqliteConfig.journalMode == 'memory') { console.log('[WARNING] journal_mode=memory: this can lead to database corruption if there is a crash during a transaction. See https://www.sqlite.org/pragma.html#pragma_journal_mode') };
//.cached not usefull //.cached not usefull
obj.file = new sqlite3.Database(parent.path.join(parent.datapath, databaseName + '.sqlite'), sqlite3.OPEN_READWRITE, function (err) { obj.file = new sqlite3.Database(path.join(parent.datapath, databaseName + '.sqlite'), sqlite3.OPEN_READWRITE, function (err) {
if (err && (err.code == 'SQLITE_CANTOPEN')) { if (err && (err.code == 'SQLITE_CANTOPEN')) {
// Database needs to be created // Database needs to be created
obj.file = new sqlite3.Database(parent.path.join(parent.datapath, databaseName + '.sqlite'), function (err) { obj.file = new sqlite3.Database(path.join(parent.datapath, databaseName + '.sqlite'), function (err) {
if (err) { console.log("SQLite Error: " + err); process.exit(1); } if (err) { console.log("SQLite Error: " + err); process.exit(1); }
obj.file.exec(` obj.file.exec(`
CREATE TABLE main (id VARCHAR(256) PRIMARY KEY NOT NULL, type CHAR(32), domain CHAR(64), extra CHAR(255), extraex CHAR(255), doc JSON); CREATE TABLE main (id VARCHAR(256) PRIMARY KEY NOT NULL, type CHAR(32), domain CHAR(64), extra CHAR(255), extraex CHAR(255), doc JSON);
@ -909,7 +909,7 @@ module.exports.CreateDB = function (parent, func) {
} else if (parent.args.postgres) { } else if (parent.args.postgres) {
// Postgres SQL // Postgres SQL
let connectinArgs = parent.args.postgres; let connectinArgs = parent.args.postgres;
connectinArgs.Database = (databaseName = (connectinArgs.database != null) ? connectinArgs.database : 'meshcentral'); connectinArgs.database = (databaseName = (connectinArgs.database != null) ? connectinArgs.database : 'meshcentral');
let DatastoreTest; let DatastoreTest;
obj.databaseType = DB_POSTGRESQL; obj.databaseType = DB_POSTGRESQL;
@ -975,7 +975,7 @@ module.exports.CreateDB = function (parent, func) {
} else { } else {
if ((info.versionArray[0] < 3) || ((info.versionArray[0] == 3) && (info.versionArray[1] < 6))) { if ((info.versionArray[0] < 3) || ((info.versionArray[0] == 3) && (info.versionArray[1] < 6))) {
// We are running with mongoDB older than 3.6, this is not good. // We are running with mongoDB older than 3.6, this is not good.
parent.addServerWarning("Current version of MongoDB (" + info.version + ") is too old, please upgrade to MongoDB 3.6 or better."); parent.addServerWarning("Current version of MongoDB (" + info.version + ") is too old, please upgrade to MongoDB 3.6 or better.", true);
} }
} }
}); });
@ -1294,7 +1294,7 @@ module.exports.CreateDB = function (parent, func) {
// Setup the SMBIOS collection, for NeDB we don't setup SMBIOS since NeDB will corrupt the database. Remove any existing ones. // Setup the SMBIOS collection, for NeDB we don't setup SMBIOS since NeDB will corrupt the database. Remove any existing ones.
//obj.smbiosfile = new Datastore({ filename: parent.getConfigFilePath('meshcentral-smbios.db'), autoload: true, corruptAlertThreshold: 1 }); //obj.smbiosfile = new Datastore({ filename: parent.getConfigFilePath('meshcentral-smbios.db'), autoload: true, corruptAlertThreshold: 1 });
parent.fs.unlink(parent.getConfigFilePath('meshcentral-smbios.db'), function () { }); fs.unlink(parent.getConfigFilePath('meshcentral-smbios.db'), function () { });
// Setup the server stats collection and setup indexes // Setup the server stats collection and setup indexes
obj.serverstatsfile = new Datastore({ filename: parent.getConfigFilePath('meshcentral-stats.db'), autoload: true, corruptAlertThreshold: 1 }); obj.serverstatsfile = new Datastore({ filename: parent.getConfigFilePath('meshcentral-stats.db'), autoload: true, corruptAlertThreshold: 1 });
@ -3187,7 +3187,6 @@ module.exports.CreateDB = function (parent, func) {
// Return a human readable string with current backup configuration // Return a human readable string with current backup configuration
obj.getBackupConfig = function () { obj.getBackupConfig = function () {
var r = '', backupPath = parent.backuppath; var r = '', backupPath = parent.backuppath;
if (parent.config.settings.autobackup && parent.config.settings.autobackup.backuppath) { backupPath = parent.config.settings.autobackup.backuppath; }
let dbname = 'meshcentral'; let dbname = 'meshcentral';
if (parent.args.mongodbname) { dbname = parent.args.mongodbname; } if (parent.args.mongodbname) { dbname = parent.args.mongodbname; }
@ -3197,7 +3196,7 @@ module.exports.CreateDB = function (parent, func) {
const currentDate = new Date(); const currentDate = new Date();
const fileSuffix = currentDate.getFullYear() + '-' + padNumber(currentDate.getMonth() + 1, 2) + '-' + padNumber(currentDate.getDate(), 2) + '-' + padNumber(currentDate.getHours(), 2) + '-' + padNumber(currentDate.getMinutes(), 2); const fileSuffix = currentDate.getFullYear() + '-' + padNumber(currentDate.getMonth() + 1, 2) + '-' + padNumber(currentDate.getDate(), 2) + '-' + padNumber(currentDate.getHours(), 2) + '-' + padNumber(currentDate.getMinutes(), 2);
obj.newAutoBackupFile = ((typeof parent.config.settings.autobackup.backupname == 'string') ? parent.config.settings.autobackup.backupname : 'meshcentral-autobackup-') + fileSuffix; obj.newAutoBackupFile = parent.config.settings.autobackup.backupname + fileSuffix;
r += 'DB Name: ' + dbname + '\r\n'; r += 'DB Name: ' + dbname + '\r\n';
r += 'DB Type: ' + DB_LIST[obj.databaseType] + '\r\n'; r += 'DB Type: ' + DB_LIST[obj.databaseType] + '\r\n';
@ -3207,15 +3206,14 @@ module.exports.CreateDB = function (parent, func) {
if (parent.config.settings.autobackup == null) { if (parent.config.settings.autobackup == null) {
r += 'No Settings/AutoBackup\r\n'; r += 'No Settings/AutoBackup\r\n';
} else { } else {
if (parent.config.settings.autobackup.backuphour != null && parent.config.settings.autobackup.backuphour != -1) {
r += 'Backup between: ' + parent.config.settings.autobackup.backuphour + 'H-' + (parent.config.settings.autobackup.backuphour + 1) + 'H\r\n';
}
if (parent.config.settings.autobackup.backupintervalhours != null) { if (parent.config.settings.autobackup.backupintervalhours != null) {
r += 'Backup Interval (Hours): '; r += 'Backup Interval (Hours): ' + parent.config.settings.autobackup.backupintervalhours + '\r\n';
if (typeof parent.config.settings.autobackup.backupintervalhours != 'number') { r += 'Bad backupintervalhours type\r\n'; }
else { r += parent.config.settings.autobackup.backupintervalhours + '\r\n'; }
} }
if (parent.config.settings.autobackup.keeplastdaysbackup != null) { if (parent.config.settings.autobackup.keeplastdaysbackup != null) {
r += 'Keep Last Backups (Days): '; r += 'Keep Last Backups (Days): ' + parent.config.settings.autobackup.keeplastdaysbackup + '\r\n';
if (typeof parent.config.settings.autobackup.keeplastdaysbackup != 'number') { r += 'Bad keeplastdaysbackup type\r\n'; }
else { r += parent.config.settings.autobackup.keeplastdaysbackup + '\r\n'; }
} }
if (parent.config.settings.autobackup.zippassword != null) { if (parent.config.settings.autobackup.zippassword != null) {
r += 'ZIP Password: '; r += 'ZIP Password: ';
@ -3330,48 +3328,70 @@ module.exports.CreateDB = function (parent, func) {
} }
// Check that the server is capable of performing a backup // Check that the server is capable of performing a backup
// Tries configured custom location with fallback to default location
// Now runs after autobackup config init in meshcentral.js so config options are checked
obj.checkBackupCapability = function (func) { obj.checkBackupCapability = function (func) {
if ((parent.config.settings.autobackup == null) || (parent.config.settings.autobackup == false)) { func(); return; }; if ((parent.config.settings.autobackup == null) || (parent.config.settings.autobackup == false)) { return; };
//block backup until validated. Gets put back if all checks are ok.
let backupInterval = parent.config.settings.autobackup.backupintervalhours;
parent.config.settings.autobackup.backupintervalhours = -1;
let backupPath = parent.backuppath; let backupPath = parent.backuppath;
if (parent.config.settings.autobackup && parent.config.settings.autobackup.backuppath) { backupPath = parent.config.settings.autobackup.backuppath; }
try { parent.fs.mkdirSync(backupPath); } catch (e) { }
if (parent.fs.existsSync(backupPath) == false) { func(1, "Backup folder \"" + backupPath + "\" does not exist, auto-backup will not be performed."); return; }
if (backupPath.startsWith(parent.datapath)) {
func(1, "Backup path can't be set within meshcentral-data folder. No backups will be made.");
return;
}
// Check create/write backupdir
try { fs.mkdirSync(backupPath); }
catch (e) {
// EEXIST error = dir already exists
if (e.code != 'EEXIST' ) {
//Unable to create backuppath
console.error(e.message);
func(1, 'Unable to create ' + backupPath + '. No backups will be made. Error: ' + e.message);
return;
}
}
const testFile = path.join(backupPath, (parent.config.settings.autobackup.backupname + ".test"));
try { fs.writeFileSync( testFile, "DeleteMe"); }
catch (e) {
//Unable to create file
console.error (e.message);
func(1, "Backuppath (" + backupPath + ") can't be written to. No backups will be made. Error: " + e.message);
return;
}
try { fs.unlinkSync(testFile); parent.debug('backup', 'Backuppath ' + backupPath + ' accesscheck successful');}
catch (e) {
console.error (e.message);
func(1, "Backuppathtestfile (" + testFile + ") can't be deleted, check filerights. Error: " + e.message);
// Assume write rights, no delete rights. Continue with warning.
//return;
}
// Check database dumptools
if ((obj.databaseType == DB_MONGOJS) || (obj.databaseType == DB_MONGODB)) { if ((obj.databaseType == DB_MONGOJS) || (obj.databaseType == DB_MONGODB)) {
// Check that we have access to MongoDump // Check that we have access to MongoDump
var cmd = buildMongoDumpCommand(); var cmd = buildMongoDumpCommand();
cmd += (parent.platform == 'win32') ? ' --archive=\"nul\"' : ' --archive=\"/dev/null\"'; cmd += (parent.platform == 'win32') ? ' --archive=\"nul\"' : ' --archive=\"/dev/null\"';
const child_process = require('child_process'); const child_process = require('child_process');
child_process.exec(cmd, { cwd: backupPath }, function (error, stdout, stderr) { child_process.exec(cmd, { cwd: backupPath }, function (error, stdout, stderr) {
try { if ((error != null) && (error != '')) {
if ((error != null) && (error != '')) { func(1, "Unable to find mongodump tool, backup will not be performed. Command tried: " + cmd);
if (parent.platform == 'win32') { return;
func(1, "Unable to find mongodump.exe, MongoDB database auto-backup will not be performed."); } else {parent.config.settings.autobackup.backupintervalhours = backupInterval;}
} else {
func(1, "Unable to find mongodump, MongoDB database auto-backup will not be performed.");
}
} else {
func();
}
} catch (ex) { console.log(ex); }
}); });
} else if ((obj.databaseType == DB_MARIADB) || (obj.databaseType == DB_MYSQL)) { } else if ((obj.databaseType == DB_MARIADB) || (obj.databaseType == DB_MYSQL)) {
// Check that we have access to mysqldump // Check that we have access to mysqldump
var cmd = buildSqlDumpCommand(); var cmd = buildSqlDumpCommand();
cmd += ' > ' + ((parent.platform == 'win32') ? '\"nul\"' : '\"/dev/null\"'); cmd += ' > ' + ((parent.platform == 'win32') ? '\"nul\"' : '\"/dev/null\"');
const child_process = require('child_process'); const child_process = require('child_process');
child_process.exec(cmd, { cwd: backupPath }, function(error, stdout, stdin) { child_process.exec(cmd, { cwd: backupPath, timeout: 1000*30 }, function(error, stdout, stdin) {
try { if ((error != null) && (error != '')) {
if ((error != null) && (error != '')) { func(1, "Unable to find mysqldump tool, backup will not be performed. Command tried: " + cmd);
if (parent.platform == 'win32') { return;
func(1, "Unable to find mysqldump.exe, MySQL/MariaDB database auto-backup will not be performed."); } else {parent.config.settings.autobackup.backupintervalhours = backupInterval;}
} else {
func(1, "Unable to find mysqldump, MySQL/MariaDB database auto-backup will not be performed.");
}
} else {
func();
}
} catch (ex) { console.log(ex); }
}); });
} else if (obj.databaseType == DB_POSTGRESQL) { } else if (obj.databaseType == DB_POSTGRESQL) {
// Check that we have access to pg_dump // Check that we have access to pg_dump
@ -3382,17 +3402,14 @@ module.exports.CreateDB = function (parent, func) {
+ ' > ' + ((parent.platform == 'win32') ? '\"nul\"' : '\"/dev/null\"'); + ' > ' + ((parent.platform == 'win32') ? '\"nul\"' : '\"/dev/null\"');
const child_process = require('child_process'); const child_process = require('child_process');
child_process.exec(cmd, { cwd: backupPath }, function(error, stdout, stdin) { child_process.exec(cmd, { cwd: backupPath }, function(error, stdout, stdin) {
try { if ((error != null) && (error != '')) {
if ((error != null) && (error != '')) { func(1, "Unable to find pg_dump tool, backup will not be performed. Command tried: " + cmd);
func(1, "Unable to find pg_dump, PostgreSQL database auto-backup will not be performed."); return;
} else { } else {parent.config.settings.autobackup.backupintervalhours = backupInterval;}
func();
}
} catch (ex) { console.log(ex); }
}); });
} else { } else {
func(); //all ok, enable backup
} parent.config.settings.autobackup.backupintervalhours = backupInterval;}
} }
// MongoDB pending bulk read operation, perform fast bulk document reads. // MongoDB pending bulk read operation, perform fast bulk document reads.
@ -3506,19 +3523,18 @@ module.exports.CreateDB = function (parent, func) {
// Perform a server backup // Perform a server backup
obj.performBackup = function (func) { obj.performBackup = function (func) {
parent.debug('db','Entering performBackup'); parent.debug('backup','Entering performBackup');
try { try {
if (obj.performingBackup) return 'Backup alreay in progress.'; if (obj.performingBackup) return 'Backup alreay in progress.';
if (parent.config.settings.autobackup.backupintervalhours == -1) { if (func) { func('Unable to create backup if backuppath is set to the data folder.'); return 'Backup aborted.' }}; if (parent.config.settings.autobackup.backupintervalhours == -1) { if (func) { func('Backup disabled.'); return 'Backup disabled.' }};
obj.performingBackup = true; obj.performingBackup = true;
let backupPath = parent.backuppath; let backupPath = parent.backuppath;
let dataPath = parent.datapath; let dataPath = parent.datapath;
if (parent.config.settings.autobackup && parent.config.settings.autobackup.backuppath) { backupPath = parent.config.settings.autobackup.backuppath; }
try { parent.fs.mkdirSync(backupPath); } catch (e) { }
const currentDate = new Date(); const currentDate = new Date();
const fileSuffix = currentDate.getFullYear() + '-' + padNumber(currentDate.getMonth() + 1, 2) + '-' + padNumber(currentDate.getDate(), 2) + '-' + padNumber(currentDate.getHours(), 2) + '-' + padNumber(currentDate.getMinutes(), 2); const fileSuffix = currentDate.getFullYear() + '-' + padNumber(currentDate.getMonth() + 1, 2) + '-' + padNumber(currentDate.getDate(), 2) + '-' + padNumber(currentDate.getHours(), 2) + '-' + padNumber(currentDate.getMinutes(), 2);
obj.newAutoBackupFile = path.join(backupPath, ((typeof parent.config.settings.autobackup.backupname == 'string') ? parent.config.settings.autobackup.backupname : 'meshcentral-autobackup-') + fileSuffix + '.zip'); obj.newAutoBackupFile = path.join(backupPath, parent.config.settings.autobackup.backupname + fileSuffix + '.zip');
parent.debug('backup','newAutoBackupFile=' + obj.newAutoBackupFile);
if ((obj.databaseType == DB_MONGOJS) || (obj.databaseType == DB_MONGODB)) { if ((obj.databaseType == DB_MONGOJS) || (obj.databaseType == DB_MONGODB)) {
// Perform a MongoDump // Perform a MongoDump
@ -3530,13 +3546,14 @@ module.exports.CreateDB = function (parent, func) {
var cmd = buildMongoDumpCommand(); var cmd = buildMongoDumpCommand();
cmd += (dburl) ? ' --archive=\"' + obj.newDBDumpFile + '\"' : cmd += (dburl) ? ' --archive=\"' + obj.newDBDumpFile + '\"' :
' --db=\"' + dbname + '\" --archive=\"' + obj.newDBDumpFile + '\"'; ' --db=\"' + dbname + '\" --archive=\"' + obj.newDBDumpFile + '\"';
parent.debug('backup','Mongodump cmd: ' + cmd);
const child_process = require('child_process'); const child_process = require('child_process');
const dumpProcess = child_process.exec( const dumpProcess = child_process.exec(
cmd, cmd,
{ cwd: parent.parentpath }, { cwd: parent.parentpath },
(error)=> {if (error) {obj.backupStatus |= BACKUPFAIL_DBDUMP; console.log('ERROR: Unable to perform MongoDB backup: ' + error + '\r\n'); obj.createBackupfile(func);}} (error)=> {if (error) {obj.backupStatus |= BACKUPFAIL_DBDUMP; console.error('ERROR: Unable to perform MongoDB backup: ' + error + '\r\n'); obj.createBackupfile(func);}}
); );
dumpProcess.on('exit', (code) => { dumpProcess.on('exit', (code) => {
if (code != 0) {console.log(`Mongodump child process exited with code ${code}`); obj.backupStatus |= BACKUPFAIL_DBDUMP;} if (code != 0) {console.log(`Mongodump child process exited with code ${code}`); obj.backupStatus |= BACKUPFAIL_DBDUMP;}
obj.createBackupfile(func); obj.createBackupfile(func);
@ -3549,15 +3566,16 @@ module.exports.CreateDB = function (parent, func) {
var cmd = buildSqlDumpCommand(); var cmd = buildSqlDumpCommand();
cmd += ' --result-file=\"' + obj.newDBDumpFile + '\"'; cmd += ' --result-file=\"' + obj.newDBDumpFile + '\"';
parent.debug('backup','Maria/MySQLdump cmd: ' + cmd);
const child_process = require('child_process'); const child_process = require('child_process');
const dumpProcess = child_process.exec( const dumpProcess = child_process.exec(
cmd, cmd,
{ cwd: parent.parentpath }, { cwd: parent.parentpath },
(error)=> {if (error) {obj.backupStatus |= BACKUPFAIL_DBDUMP; console.log('ERROR: Unable to perform MySQL backup: ' + error + '\r\n'); obj.createBackupfile(func);}} (error)=> {if (error) {obj.backupStatus |= BACKUPFAIL_DBDUMP; console.error('ERROR: Unable to perform MySQL backup: ' + error + '\r\n'); obj.createBackupfile(func);}}
); );
dumpProcess.on('exit', (code) => { dumpProcess.on('exit', (code) => {
if (code != 0) {console.log(`MySQLdump child process exited with code ${code}`); obj.backupStatus |= BACKUPFAIL_DBDUMP;} if (code != 0) {console.error(`MySQLdump child process exited with code ${code}`); obj.backupStatus |= BACKUPFAIL_DBDUMP;}
obj.createBackupfile(func); obj.createBackupfile(func);
}); });
@ -3565,8 +3583,9 @@ module.exports.CreateDB = function (parent, func) {
//.db3 suffix to escape escape backupfile glob to exclude the sqlite db files //.db3 suffix to escape escape backupfile glob to exclude the sqlite db files
obj.newDBDumpFile = path.join(backupPath, databaseName + '-sqlitedump-' + fileSuffix + '.db3'); obj.newDBDumpFile = path.join(backupPath, databaseName + '-sqlitedump-' + fileSuffix + '.db3');
// do a VACUUM INTO in favor of the backup API to compress the export, see https://www.sqlite.org/backup.html // do a VACUUM INTO in favor of the backup API to compress the export, see https://www.sqlite.org/backup.html
parent.debug('backup','SQLitedump: VACUUM INTO ' + obj.newDBDumpFile);
obj.file.exec('VACUUM INTO \'' + obj.newDBDumpFile + '\'', function (err) { obj.file.exec('VACUUM INTO \'' + obj.newDBDumpFile + '\'', function (err) {
if (err) { console.log('SQLite start-backup error: ' + err); obj.backupStatus |=BACKUPFAIL_DBDUMP;}; if (err) { console.error('SQLite backup error: ' + err); obj.backupStatus |=BACKUPFAIL_DBDUMP;};
//always finish/clean up //always finish/clean up
obj.createBackupfile(func); obj.createBackupfile(func);
}); });
@ -3578,6 +3597,7 @@ module.exports.CreateDB = function (parent, func) {
+ ' --dbname=postgresql://' + parent.config.settings.postgres.user + ":" +parent.config.settings.postgres.password + ' --dbname=postgresql://' + parent.config.settings.postgres.user + ":" +parent.config.settings.postgres.password
+ "@" + parent.config.settings.postgres.host + ":" + parent.config.settings.postgres.port + "/" + databaseName + "@" + parent.config.settings.postgres.host + ":" + parent.config.settings.postgres.port + "/" + databaseName
+ " --file=" + obj.newDBDumpFile; + " --file=" + obj.newDBDumpFile;
parent.debug('backup','Postgresqldump cmd: ' + cmd);
const child_process = require('child_process'); const child_process = require('child_process');
const dumpProcess = child_process.exec( const dumpProcess = child_process.exec(
cmd, cmd,
@ -3589,15 +3609,15 @@ module.exports.CreateDB = function (parent, func) {
obj.createBackupfile(func); obj.createBackupfile(func);
}); });
} else { } else {
//NeDB backup, no db dump needed, just make a file backup // NeDB/Acebase backup, no db dump needed, just make a file backup
obj.createBackupfile(func); obj.createBackupfile(func);
} }
} catch (ex) { console.log(ex); }; } catch (ex) { console.error(ex); parent.addServerWarning( 'Something went wrong during performBackup, check errorlog: ' +ex.message, true); };
return 'Starting auto-backup...'; return 'Starting auto-backup...';
}; };
obj.createBackupfile = function(func) { obj.createBackupfile = function(func) {
parent.debug('db', 'Entering createFileBackup'); parent.debug('backup', 'Entering createBackupfile');
let archiver = require('archiver'); let archiver = require('archiver');
let archive = null; let archive = null;
let zipLevel = Math.min(Math.max(Number(parent.config.settings.autobackup.zipcompression ? parent.config.settings.autobackup.zipcompression : 5),1),9); let zipLevel = Math.min(Math.max(Number(parent.config.settings.autobackup.zipcompression ? parent.config.settings.autobackup.zipcompression : 5),1),9);
@ -3611,8 +3631,8 @@ module.exports.CreateDB = function (parent, func) {
if (func) { func('Creating encrypted ZIP'); } if (func) { func('Creating encrypted ZIP'); }
} catch (ex) { // registering encryption failed, do not fall back to non-encrypted, fail backup and skip old backup removal as a precaution to not lose any backups } catch (ex) { // registering encryption failed, do not fall back to non-encrypted, fail backup and skip old backup removal as a precaution to not lose any backups
obj.backupStatus |= BACKUPFAIL_ZIPMODULE; obj.backupStatus |= BACKUPFAIL_ZIPMODULE;
if (func) { func('Zipencryptionmodule failed, aborting'); } if (func) { func('Zipencryptionmodule failed, aborting');}
console.log('Zipencryptionmodule failed, aborting'); console.error('Zipencryptionmodule failed, aborting');
} }
} else { } else {
if (func) { func('Creating a NON-ENCRYPTED ZIP'); } if (func) { func('Creating a NON-ENCRYPTED ZIP'); }
@ -3622,51 +3642,36 @@ module.exports.CreateDB = function (parent, func) {
//original behavior, just a filebackup if dbdump fails : (obj.backupStatus == 0 || obj.backupStatus == BACKUPFAIL_DBDUMP) //original behavior, just a filebackup if dbdump fails : (obj.backupStatus == 0 || obj.backupStatus == BACKUPFAIL_DBDUMP)
if (obj.backupStatus == 0) { if (obj.backupStatus == 0) {
// Zip the data directory with the dbdump|NeDB files // Zip the data directory with the dbdump|NeDB files
let output = parent.fs.createWriteStream(obj.newAutoBackupFile); let output = fs.createWriteStream(obj.newAutoBackupFile);
// Archive finalized and closed
output.on('close', function () { output.on('close', function () {
if (obj.backupStatus == 0) { if (obj.backupStatus == 0) {
//remove dump archive file, because zipped and otherwise fills up let mesg = 'Auto-backup completed: ' + obj.newAutoBackupFile + ', backup-size: ' + ((archive.pointer() / 1048576).toFixed(2)) + "Mb";
if (obj.databaseType != DB_NEDB) { console.log(mesg);
try { parent.fs.unlink(obj.newDBDumpFile, function () { }); } catch (ex) {console.log('Failed to clean up dbdump file')}; if (func) { func(mesg); };
};
obj.performCloudBackup(obj.newAutoBackupFile, func); obj.performCloudBackup(obj.newAutoBackupFile, func);
// Remove old backups obj.removeExpiredBackupfiles(func);
if (parent.config.settings.autobackup && (typeof parent.config.settings.autobackup.keeplastdaysbackup == 'number')) {
let cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - parent.config.settings.autobackup.keeplastdaysbackup);
parent.fs.readdir(parent.backuppath, function (err, dir) {
try {
if ((err == null) && (dir.length > 0)) {
let fileName = (typeof parent.config.settings.autobackup.backupname == 'string') ? parent.config.settings.autobackup.backupname : 'meshcentral-autobackup-';
for (var i in dir) {
var name = dir[i];
if (name.startsWith(fileName) && name.endsWith('.zip')) {
var timex = name.substring(23, name.length - 4).split('-');
if (timex.length == 5) {
var fileDate = new Date(parseInt(timex[0]), parseInt(timex[1]) - 1, parseInt(timex[2]), parseInt(timex[3]), parseInt(timex[4]));
if (fileDate && (cutoffDate > fileDate)) { try { parent.fs.unlink(parent.path.join(parent.backuppath, name), function () { }); } catch (ex) { } }
}
}
}
}
} catch (ex) { console.log(ex); }
});
}
console.log('Auto-backup completed.');
if (func) { func('Auto-backup completed.'); };
} else { } else {
console.log('Zipbackup failed ('+ (+obj.backupStatus).toString(16).slice(-4) + '), deleting incomplete backup: ' + obj.newAutoBackupFile ); let mesg = 'Zipbackup failed (' + obj.backupStatus.toString(2).slice(-8) + '), deleting incomplete backup: ' + obj.newAutoBackupFile;
if (func) { func('Zipbackup failed ('+ (+obj.backupStatus).toString(16).slice(-4) + '), deleting incomplete backup: ' + obj.newAutoBackupFile) }; if (func) { func(mesg) }
try { parent.fs.unlink(obj.newAutoBackupFile, function () { }); parent.fs.unlink(obj.newDBDumpFile, function () { }); } catch (ex) {console.log('Failed to delete incomplete backup files')}; else { parent.addServerWarning(mesg, true ) };
if (fs.existsSync(obj.newAutoBackupFile)) { fs.unlink(obj.newAutoBackupFile, function (err) { console.error('Failed to clean up backupfile: ' + err.message) }) };
};
if (obj.databaseType != DB_NEDB) {
//remove dump archive file, because zipped and otherwise fills up
if (fs.existsSync(obj.newDBDumpFile)) { fs.unlink(obj.newDBDumpFile, function (err) { if (err) {console.error('Failed to clean up dbdump file: ' + err.message) } }) };
}; };
obj.performingBackup = false; obj.performingBackup = false;
obj.backupStatus = 0x0; obj.backupStatus = 0x0;
}); }
);
output.on('end', function () { }); output.on('end', function () { });
output.on('error', function (err) { output.on('error', function (err) {
if ((obj.backupStatus & BACKUPFAIL_ZIPCREATE) == 0) { if ((obj.backupStatus & BACKUPFAIL_ZIPCREATE) == 0) {
console.log('Output error: ' + err); console.error('Output error: ' + err.message);
if (func) { func('Output error: ' + err); }; if (func) { func('Output error: ' + err.message); };
obj.backupStatus |= BACKUPFAIL_ZIPCREATE; obj.backupStatus |= BACKUPFAIL_ZIPCREATE;
archive.abort(); archive.abort();
}; };
@ -3676,16 +3681,16 @@ module.exports.CreateDB = function (parent, func) {
//an ENOENT warning is given, but the archiver module has no option to/does not skip/resume //an ENOENT warning is given, but the archiver module has no option to/does not skip/resume
//so the backup needs te be aborted as it otherwise leaves an incomplete zip and never 'ends' //so the backup needs te be aborted as it otherwise leaves an incomplete zip and never 'ends'
if ((obj.backupStatus & BACKUPFAIL_ZIPCREATE) == 0) { if ((obj.backupStatus & BACKUPFAIL_ZIPCREATE) == 0) {
console.log('Zip warning: ' + err); console.log('Zip warning: ' + err.message);
if (func) { func('Zip warning: ' + err); }; if (func) { func('Zip warning: ' + err.message); };
obj.backupStatus |= BACKUPFAIL_ZIPCREATE; obj.backupStatus |= BACKUPFAIL_ZIPCREATE;
archive.abort(); archive.abort();
}; };
}); });
archive.on('error', function (err) { archive.on('error', function (err) {
if ((obj.backupStatus & BACKUPFAIL_ZIPCREATE) == 0) { if ((obj.backupStatus & BACKUPFAIL_ZIPCREATE) == 0) {
console.log('Zip error: ' + err); console.error('Zip error: ' + err.message);
if (func) { func('Zip error: ' + err); }; if (func) { func('Zip error: ' + err.message); };
obj.backupStatus |= BACKUPFAIL_ZIPCREATE; obj.backupStatus |= BACKUPFAIL_ZIPCREATE;
archive.abort(); archive.abort();
} }
@ -3718,22 +3723,67 @@ module.exports.CreateDB = function (parent, func) {
archive.finalize(); archive.finalize();
} else { } else {
//failed somewhere before zipping //failed somewhere before zipping
console.log('Backup failed ('+ (+obj.backupStatus).toString(16).slice(-4) + ')'); console.error('Backup failed ('+ obj.backupStatus.toString(2).slice(-8) + ')');
if (func) { func('Backup failed ('+ (+obj.backupStatus).toString(16).slice(-4) + ')') }; if (func) { func('Backup failed ('+ obj.backupStatus.toString(2).slice(-8) + ')') }
else {
parent.addServerWarning('Backup failed ('+ obj.backupStatus.toString(2).slice(-8) + ')', true);
}
//Just in case something's there //Just in case something's there
try { parent.fs.unlink(obj.newDBDumpFile, function () { }); } catch (ex) { }; if (fs.existsSync(obj.newDBDumpFile)) { fs.unlink(obj.newDBDumpFile, function (err) { if (err) {console.error('Failed to clean up dbdump file: ' + err.message) } }); };
obj.backupStatus = 0x0; obj.backupStatus = 0x0;
obj.performingBackup = false; obj.performingBackup = false;
}; };
}; };
// Remove expired backupfiles by filenamedate
obj.removeExpiredBackupfiles = function (func) {
if (parent.config.settings.autobackup && (typeof parent.config.settings.autobackup.keeplastdaysbackup == 'number')) {
let cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - parent.config.settings.autobackup.keeplastdaysbackup);
fs.readdir(parent.backuppath, function (err, dir) {
try {
if (err == null) {
if (dir.length > 0) {
let fileName = parent.config.settings.autobackup.backupname;
let checked = 0;
let removed = 0;
for (var i in dir) {
var name = dir[i];
parent.debug('backup', "checking file: ", path.join(parent.backuppath, name));
if (name.startsWith(fileName) && name.endsWith('.zip')) {
var timex = name.substring(fileName.length, name.length - 4).split('-');
if (timex.length == 5) {
checked++;
var fileDate = new Date(parseInt(timex[0]), parseInt(timex[1]) - 1, parseInt(timex[2]), parseInt(timex[3]), parseInt(timex[4]));
if (fileDate && (cutoffDate > fileDate)) {
console.log("Removing expired backup file: ", path.join(parent.backuppath, name));
fs.unlink(path.join(parent.backuppath, name), function (err) { if (err) { console.error(err.message); if (func) {func('Error removing: ' + err.message); } } });
removed++;
}
}
else { parent.debug('backup', "file: " + name + " timestamp failure: ", timex); }
}
}
let mesg= 'Checked ' + checked + ' candidates in ' + parent.backuppath + '. Removed ' + removed + ' expired backupfiles using cutoffDate: '+ cutoffDate.toLocaleString('default', { dateStyle: 'short', timeStyle: 'short' });
parent.debug (mesg);
if (func) { func(mesg); }
} else { console.error('No files found in ' + parent.backuppath + '. There should be at least one.')}
}
else
{ console.error(err); parent.addServerWarning( 'Reading files in backup directory ' + parent.backuppath + ' failed, check errorlog: ' + err.message, true); }
} catch (ex) { console.error(ex); parent.addServerWarning( 'Something went wrong during removeExpiredBackupfiles, check errorlog: ' +ex.message, true); }
});
}
}
// Perform cloud backup // Perform cloud backup
obj.performCloudBackup = function (filename, func) { obj.performCloudBackup = function (filename, func) {
// WebDAV Backup // WebDAV Backup
if ((typeof parent.config.settings.autobackup == 'object') && (typeof parent.config.settings.autobackup.webdav == 'object')) { if ((typeof parent.config.settings.autobackup == 'object') && (typeof parent.config.settings.autobackup.webdav == 'object')) {
const xdateTimeSort = function (a, b) { if (a.xdate > b.xdate) return 1; if (a.xdate < b.xdate) return -1; return 0; } parent.debug( 'backup', 'Entering WebDAV backup');
if (func) { func('Entering WebDAV backup.'); }
const xdateTimeSort = function (a, b) { if (a.xdate > b.xdate) return 1; if (a.xdate < b.xdate) return -1; return 0; }
// Fetch the folder name // Fetch the folder name
var webdavfolderName = 'MeshCentral-Backups'; var webdavfolderName = 'MeshCentral-Backups';
if (typeof parent.config.settings.autobackup.webdav.foldername == 'string') { webdavfolderName = parent.config.settings.autobackup.webdav.foldername; } if (typeof parent.config.settings.autobackup.webdav.foldername == 'string') { webdavfolderName = parent.config.settings.autobackup.webdav.foldername; }
@ -3741,23 +3791,28 @@ module.exports.CreateDB = function (parent, func) {
// Clean up our WebDAV folder // Clean up our WebDAV folder
function performWebDavCleanup(client) { function performWebDavCleanup(client) {
if ((typeof parent.config.settings.autobackup.webdav.maxfiles == 'number') && (parent.config.settings.autobackup.webdav.maxfiles > 1)) { if ((typeof parent.config.settings.autobackup.webdav.maxfiles == 'number') && (parent.config.settings.autobackup.webdav.maxfiles > 1)) {
let fileName = (typeof parent.config.settings.autobackup.backupname == 'string') ? parent.config.settings.autobackup.backupname : 'meshcentral-autobackup-'; let fileName = parent.config.settings.autobackup.backupname;
//only files matching our backupfilename //only files matching our backupfilename
let directoryItems = client.getDirectoryContents(webdavfolderName, { deep: false, glob: "/**/" + fileName + "*.zip" }); let directoryItems = client.getDirectoryContents(webdavfolderName, { deep: false, glob: "/**/" + fileName + "*.zip" });
directoryItems.then( directoryItems.then(
function (files) { function (files) {
for (var i in files) { files[i].xdate = new Date(files[i].lastmod); } for (var i in files) { files[i].xdate = new Date(files[i].lastmod); }
files.sort(xdateTimeSort); files.sort(xdateTimeSort);
parent.debug('backup','WebDAV filtered directory contents: ' + JSON.stringify(files, null, 4));
while (files.length >= parent.config.settings.autobackup.webdav.maxfiles) { while (files.length >= parent.config.settings.autobackup.webdav.maxfiles) {
client.deleteFile(files.shift().filename).then(function (state) { let delFile = files.shift().filename;
if (func) { func('WebDAV file deleted.'); } client.deleteFile(delFile).then(function (state) {
parent.debug('backup','WebDAV file deleted: ' + delFile);
if (func) { func('WebDAV file deleted: ' + delFile); }
}).catch(function (err) { }).catch(function (err) {
if (func) { func('WebDAV (deleteFile) error: ' + err); } console.error(err);
if (func) { func('WebDAV (deleteFile) error: ' + err.message); }
}); });
} }
} }
).catch(function (err) { ).catch(function (err) {
if (func) { func('WebDAV (getDirectoryContents) error: ' + err); } console.error(err);
if (func) { func('WebDAV (getDirectoryContents) error: ' + err.message); }
}); });
} }
} }
@ -3766,14 +3821,14 @@ module.exports.CreateDB = function (parent, func) {
function performWebDavUpload(client, filepath) { function performWebDavUpload(client, filepath) {
require('fs').stat(filepath, function(err,stat){ require('fs').stat(filepath, function(err,stat){
var fileStream = require('fs').createReadStream(filepath); var fileStream = require('fs').createReadStream(filepath);
fileStream.on('close', function () { if (func) { func('WebDAV upload completed'); } }) fileStream.on('close', function () { console.log('WebDAV upload completed: ' + webdavfolderName + '/' + require('path').basename(filepath)); if (func) { func('WebDAV upload completed: ' + webdavfolderName + '/' + require('path').basename(filepath)); } })
fileStream.on('error', function (err) { if (func) { func('WebDAV (fileUpload) error: ' + err); } }) fileStream.on('error', function (err) { console.error(err); if (func) { func('WebDAV (fileUpload) error: ' + err.message); } })
fileStream.pipe(client.createWriteStream('/' + webdavfolderName + '/' + require('path').basename(filepath), { headers: { "Content-Length": stat.size } })); fileStream.pipe(client.createWriteStream('/' + webdavfolderName + '/' + require('path').basename(filepath), { headers: { "Content-Length": stat.size } }));
if (func) { func('Uploading using WebDAV...'); } parent.debug('backup', 'Uploading using WebDAV to: ' + parent.config.settings.autobackup.webdav.url);
if (func) { func('Uploading using WebDAV to: ' + parent.config.settings.autobackup.webdav.url); }
}); });
} }
if (func) { func('Attempting WebDAV upload...'); }
const { createClient } = require('webdav'); const { createClient } = require('webdav');
const client = createClient(parent.config.settings.autobackup.webdav.url, { const client = createClient(parent.config.settings.autobackup.webdav.url, {
username: parent.config.settings.autobackup.webdav.username, username: parent.config.settings.autobackup.webdav.username,
@ -3787,19 +3842,23 @@ module.exports.CreateDB = function (parent, func) {
performWebDavUpload(client, filename); performWebDavUpload(client, filename);
}else{ }else{
client.createDirectory(webdavfolderName, {recursive: true}).then(function (a) { client.createDirectory(webdavfolderName, {recursive: true}).then(function (a) {
if (func) { func('WebDAV folder created'); } console.log('backup','WebDAV folder created: ' + webdavfolderName);
if (func) { func('WebDAV folder created: ' + webdavfolderName); }
performWebDavUpload(client, filename); performWebDavUpload(client, filename);
}).catch(function (err) { }).catch(function (err) {
if (func) { func('WebDAV (createDirectory) error: ' + err); } console.error(err);
if (func) { func('WebDAV (createDirectory) error: ' + err.message); }
}); });
} }
}).catch(function (err) { }).catch(function (err) {
if (func) { func('WebDAV (exists) error: ' + err); } console.error(err);
if (func) { func('WebDAV (exists) error: ' + err.message); }
}); });
} }
// Google Drive Backup // Google Drive Backup
if ((typeof parent.config.settings.autobackup == 'object') && (typeof parent.config.settings.autobackup.googledrive == 'object')) { if ((typeof parent.config.settings.autobackup == 'object') && (typeof parent.config.settings.autobackup.googledrive == 'object')) {
parent.debug( 'backup', 'Entering Google Drive backup');
obj.Get('GoogleDriveBackup', function (err, docs) { obj.Get('GoogleDriveBackup', function (err, docs) {
if ((err != null) || (docs.length != 1) || (docs[0].state != 3)) return; if ((err != null) || (docs.length != 1) || (docs[0].state != 3)) return;
if (func) { func('Attempting Google Drive upload...'); } if (func) { func('Attempting Google Drive upload...'); }
@ -3878,6 +3937,7 @@ module.exports.CreateDB = function (parent, func) {
// S3 Backup // S3 Backup
if ((typeof parent.config.settings.autobackup == 'object') && (typeof parent.config.settings.autobackup.s3 == 'object')) { if ((typeof parent.config.settings.autobackup == 'object') && (typeof parent.config.settings.autobackup.s3 == 'object')) {
parent.debug( 'backup', 'Entering S3 backup');
var s3folderName = 'MeshCentral-Backups'; var s3folderName = 'MeshCentral-Backups';
if (typeof parent.config.settings.autobackup.s3.foldername == 'string') { s3folderName = parent.config.settings.autobackup.s3.foldername; } if (typeof parent.config.settings.autobackup.s3.foldername == 'string') { s3folderName = parent.config.settings.autobackup.s3.foldername; }
// Construct the config object // Construct the config object

View file

@ -2,9 +2,9 @@
"archiver": "7.0.1", "archiver": "7.0.1",
"body-parser": "1.20.3", "body-parser": "1.20.3",
"cbor": "5.2.0", "cbor": "5.2.0",
"compression": "1.7.4", "compression": "1.7.5",
"cookie-session": "2.1.0", "cookie-session": "2.1.0",
"express": "4.21.1", "express": "4.21.2",
"express-handlebars": "7.1.3", "express-handlebars": "7.1.3",
"express-ws": "5.0.2", "express-ws": "5.0.2",
"ipcheck": "0.1.0", "ipcheck": "0.1.0",

View file

@ -1,4 +1,4 @@
FROM --platform=$BUILDPLATFORM node:20-alpine AS builder FROM --platform=$BUILDPLATFORM node:22-alpine AS builder
RUN mkdir -p /opt/meshcentral/meshcentral RUN mkdir -p /opt/meshcentral/meshcentral
COPY ./ /opt/meshcentral/meshcentral/ COPY ./ /opt/meshcentral/meshcentral/
@ -34,7 +34,7 @@ RUN rm -rf /opt/meshcentral/meshcentral/docker
RUN rm -rf /opt/meshcentral/meshcentral/node_modules RUN rm -rf /opt/meshcentral/meshcentral/node_modules
FROM --platform=$TARGETPLATFORM alpine:3.19 FROM --platform=$TARGETPLATFORM alpine:3.21
#Add non-root user, add installation directories and assign proper permissions #Add non-root user, add installation directories and assign proper permissions
RUN mkdir -p /opt/meshcentral/meshcentral RUN mkdir -p /opt/meshcentral/meshcentral
@ -62,8 +62,8 @@ ENV MONGO_URL=""
ENV HOSTNAME="localhost" ENV HOSTNAME="localhost"
ENV ALLOW_NEW_ACCOUNTS="true" ENV ALLOW_NEW_ACCOUNTS="true"
ENV ALLOWPLUGINS="false" ENV ALLOWPLUGINS="false"
ENV LOCALSESSIONRECORDING="false" ENV LOCALSESSIONRECORDING="true"
ENV MINIFY="true" ENV MINIFY="false"
ENV WEBRTC="false" ENV WEBRTC="false"
ENV IFRAME="false" ENV IFRAME="false"
ENV SESSION_KEY="" ENV SESSION_KEY=""
@ -83,8 +83,8 @@ COPY --from=builder /opt/meshcentral/meshcentral /opt/meshcentral/meshcentral
COPY ./docker/startup.sh ./startup.sh COPY ./docker/startup.sh ./startup.sh
COPY ./docker/config.json.template /opt/meshcentral/config.json.template COPY ./docker/config.json.template /opt/meshcentral/config.json.template
# install dependencies from package.json and nedb # install dependencies from package.json
RUN cd meshcentral && npm install && npm install nedb RUN cd meshcentral && npm install
# NOTE: ALL MODULES MUST HAVE A VERSION NUMBER AND THE VERSION MUST MATCH THAT USED IN meshcentral.js mainStart() # NOTE: ALL MODULES MUST HAVE A VERSION NUMBER AND THE VERSION MUST MATCH THAT USED IN meshcentral.js mainStart()
RUN if ! [ -z "$INCLUDE_MONGODBTOOLS" ]; then cd meshcentral && npm install mongodb@4.13.0 saslprep@1.0.3; fi RUN if ! [ -z "$INCLUDE_MONGODBTOOLS" ]; then cd meshcentral && npm install mongodb@4.13.0 saslprep@1.0.3; fi

View file

@ -21,9 +21,9 @@
"": { "": {
"_title": "MyServer", "_title": "MyServer",
"_title2": "Servername", "_title2": "Servername",
"minify": true, "minify": false,
"NewAccounts": true, "NewAccounts": true,
"localSessionRecording": false, "localSessionRecording": true,
"_userNameIsEmail": true, "_userNameIsEmail": true,
"_certUrl": "my.reverse.proxy" "_certUrl": "my.reverse.proxy"
} }

View file

@ -18,7 +18,7 @@ else
sed -i "s/\"NewAccounts\": true/\"NewAccounts\": $ALLOW_NEW_ACCOUNTS/" meshcentral-data/"${CONFIG_FILE}" sed -i "s/\"NewAccounts\": true/\"NewAccounts\": $ALLOW_NEW_ACCOUNTS/" meshcentral-data/"${CONFIG_FILE}"
sed -i "s/\"enabled\": false/\"enabled\": $ALLOWPLUGINS/" meshcentral-data/"${CONFIG_FILE}" sed -i "s/\"enabled\": false/\"enabled\": $ALLOWPLUGINS/" meshcentral-data/"${CONFIG_FILE}"
sed -i "s/\"localSessionRecording\": false/\"localSessionRecording\": $LOCALSESSIONRECORDING/" meshcentral-data/"${CONFIG_FILE}" sed -i "s/\"localSessionRecording\": false/\"localSessionRecording\": $LOCALSESSIONRECORDING/" meshcentral-data/"${CONFIG_FILE}"
sed -i "s/\"minify\": true/\"minify\": $MINIFY/" meshcentral-data/"${CONFIG_FILE}" sed -i "s/\"minify\": false/\"minify\": $MINIFY/" meshcentral-data/"${CONFIG_FILE}"
sed -i "s/\"WebRTC\": false/\"WebRTC\": $WEBRTC/" meshcentral-data/"${CONFIG_FILE}" sed -i "s/\"WebRTC\": false/\"WebRTC\": $WEBRTC/" meshcentral-data/"${CONFIG_FILE}"
sed -i "s/\"AllowFraming\": false/\"AllowFraming\": $IFRAME/" meshcentral-data/"${CONFIG_FILE}" sed -i "s/\"AllowFraming\": false/\"AllowFraming\": $IFRAME/" meshcentral-data/"${CONFIG_FILE}"
if [ -z "$SESSION_KEY" ]; then if [ -z "$SESSION_KEY" ]; then

View file

@ -1,6 +1,6 @@
# Meshcentral2 Guide # MeshCentral Guide
[MeshCentral2 Guide](https://meshcentral.com/docs/MeshCentral2UserGuide.pdf) [MeshCentral Guide](https://meshcentral.com/docs/MeshCentral2UserGuide.pdf)
MeshCmd Guide [as .pdf](https://meshcentral.com/docs/MeshCmdUserGuide.pdf) [as .odt](https://github.com/Ylianst/MeshCentral/blob/master/docs/MeshCentral User's Guide v0.2.9.odt?raw=true) MeshCmd Guide [as .pdf](https://meshcentral.com/docs/MeshCmdUserGuide.pdf) [as .odt](https://github.com/Ylianst/MeshCentral/blob/master/docs/MeshCentral User's Guide v0.2.9.odt?raw=true)
@ -1278,6 +1278,8 @@ And taking authentication to the next step is removing the login page entirely.
<iframe width="320" height="180" src="https://www.youtube.com/embed/-WKY8Wy0Huk" frameborder="0" allowfullscreen></iframe> <iframe width="320" height="180" src="https://www.youtube.com/embed/-WKY8Wy0Huk" frameborder="0" allowfullscreen></iframe>
</div> </div>
You can also setup [Duo 2FA](https://github.com/Ylianst/MeshCentral/blob/master/docs/docs/meshcentral/security.md#duo-2fa-setup) which is a commertial offering.
## Server Backup & Restore ## Server Backup & Restore
Its very important that the server be backed up regularly and that a backup be kept offsite. Luckily, performing a full backup of the MeshCentral server is generally easy to do. For all installations make sure to back up the following two folders and all sub-folders. Its very important that the server be backed up regularly and that a backup be kept offsite. Luckily, performing a full backup of the MeshCentral server is generally easy to do. For all installations make sure to back up the following two folders and all sub-folders.

View file

@ -123,6 +123,10 @@ Use of the optional file `plugin_name.js` in the optional folder `modules_meshco
Much of MeshCentral revolves around returning objects for your structures, and plugins are no different. Within your plugin you can traverse all the way up to the web server and MeshCentral Server classes to access all the functionality those layers provide. This is done by passing the current object to newly created objects, and assigning that reference to a `parent` variable within that object. Much of MeshCentral revolves around returning objects for your structures, and plugins are no different. Within your plugin you can traverse all the way up to the web server and MeshCentral Server classes to access all the functionality those layers provide. This is done by passing the current object to newly created objects, and assigning that reference to a `parent` variable within that object.
## Ping-Pong
If you build a plugin which makes use of `meshrelay.ashx`, keep in mind to either handle ping-pong messages (`serverPing`, `serverPong`) on the control channel or to request MeshCentral to not send such messages through sending the `noping=1` parameter in the connection URL. For a deeper sight search for "PING/PONG" in `meshrelay.js`.
## Versioning ## Versioning
Versioning your plugin correctly and consistently is essential to ensure users of your plugin are prompted to upgrade when it is available. Semantic versioning is recommended. Versioning your plugin correctly and consistently is essential to ensure users of your plugin are prompted to upgrade when it is available. Semantic versioning is recommended.

View file

@ -27,3 +27,29 @@ Adjust these items in your `config.json`
} }
} }
``` ```
## Duo 2FA setup
MeshCentral supports Duo as a way for users to add two-factor authentication and Duo offers free accounts for user 10 users. To get started, go to [Duo.com](https://duo.com/) and create a free account. Once logged into Duo, select "Applications" and "Protect an Application" on the left side. Search for "Web SDK" and hit the "Protect" button. You will see a screen with the following information:
- Client ID
- Client secret
- API hostname
Copy these three values in a safe place and do not share these values with anyone. Then, in your MeshCentral config.json file, add the following in the domains section:
```json
{
"domains": {
"": {
"duo2factor": {
"integrationkey": "ClientId",
"secretkey": "ClientSecret",
"apihostname": "api-xxxxxxxxxxx.duosecurity.com"
}
}
}
}
```
Restart MeshCentral and your server should now be Duo capable. Users will see an option to enable it in the "My Account" tab. When enabling it, users will be walked thru the process of downloading the mobile application and going thru a trial run on 2FA. Users that get setup will be added to your Duo account under the "Users" / "Users" screen in Duo. Note that the "admin" user is not valid in Duo, so, if you have a user with the name "Admin" in MeshCentral, they will get an error trying to setup Duo.

View file

@ -1,7 +1,6 @@
/** /**
* @description MeshCentral Firebase communication module * @description MeshCentral Firebase communication module
* @author Ylian Saint-Hilaire * @author Ylian Saint-Hilaire
* @copyright Intel Corporation 2018-2022
* @license Apache-2.0 * @license Apache-2.0
* @version v0.0.1 * @version v0.0.1
*/ */
@ -14,31 +13,31 @@
/*jshint esversion: 6 */ /*jshint esversion: 6 */
"use strict"; "use strict";
// Construct the Firebase object // Initialize the Firebase Admin SDK
module.exports.CreateFirebase = function (parent, senderid, serverkey) { module.exports.CreateFirebase = function (parent, serviceAccount) {
var obj = {};
// Import the Firebase Admin SDK
const admin = require('firebase-admin');
const obj = {};
obj.messageId = 0; obj.messageId = 0;
obj.relays = {}; obj.relays = {};
obj.stats = { obj.stats = {
mode: "Real", mode: 'Real',
sent: 0, sent: 0,
sendError: 0, sendError: 0,
received: 0, received: 0,
receivedNoRoute: 0, receivedNoRoute: 0,
receivedBadArgs: 0 receivedBadArgs: 0
};
const tokenToNodeMap = {}; // Token --> { nid: nodeid, mid: meshid }
// Initialize Firebase Admin with server key and project ID
if (!admin.apps.length) {
admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });
} }
// In NodeJS v23, add util.isNullOrUndefined() to make node-xcs work correctly.
// Remove this when node-xcs moves to support NodeJS v23
if (require('util').isNullOrUndefined == null) { require('util').isNullOrUndefined = function (v) { return v == null; } }
const Sender = require('node-xcs').Sender;
const Message = require('node-xcs').Message;
const Notification = require('node-xcs').Notification;
const xcs = new Sender(senderid, serverkey);
var tokenToNodeMap = {} // Token --> { nid: nodeid, mid: meshid }
// Setup logging // Setup logging
if (parent.config.firebase && (parent.config.firebase.log === true)) { if (parent.config.firebase && (parent.config.firebase.log === true)) {
obj.logpath = parent.path.join(parent.datapath, 'firebase.txt'); obj.logpath = parent.path.join(parent.datapath, 'firebase.txt');
@ -47,133 +46,85 @@ module.exports.CreateFirebase = function (parent, senderid, serverkey) {
obj.log = function () { } obj.log = function () { }
} }
// Messages received from client (excluding receipts) // Function to send notifications
xcs.on('message', function (messageId, from, data, category) {
const jsonData = JSON.stringify(data);
obj.log('Firebase-Message: ' + jsonData);
parent.debug('email', 'Firebase-Message: ' + jsonData);
if (typeof data.r == 'string') {
// Lookup push relay server
parent.debug('email', 'Firebase-RelayRoute: ' + data.r);
const wsrelay = obj.relays[data.r];
if (wsrelay != null) {
delete data.r;
try { wsrelay.send(JSON.stringify({ from: from, data: data, category: category })); } catch (ex) { }
}
} else {
// Lookup node information from the cache
var ninfo = tokenToNodeMap[from];
if (ninfo == null) { obj.stats.receivedNoRoute++; return; }
if ((data != null) && (data.con != null) && (data.s != null)) { // Console command
obj.stats.received++;
parent.webserver.routeAgentCommand({ action: 'msg', type: 'console', value: data.con, sessionid: data.s }, ninfo.did, ninfo.nid, ninfo.mid);
} else {
obj.stats.receivedBadArgs++;
}
}
});
// Only fired for messages where options.delivery_receipt_requested = true
/*
xcs.on('receipt', function (messageId, from, data, category) { console.log('Firebase-Receipt', messageId, from, data, category); });
xcs.on('connected', function () { console.log('Connected'); });
xcs.on('disconnected', function () { console.log('disconnected'); });
xcs.on('online', function () { console.log('online'); });
xcs.on('error', function (e) { console.log('error', e); });
xcs.on('message-error', function (e) { console.log('message-error', e); });
*/
xcs.start();
obj.log('CreateFirebase-Setup');
parent.debug('email', 'CreateFirebase-Setup');
// EXAMPLE
//var payload = { notification: { title: command.title, body: command.msg }, data: { url: obj.msgurl } };
//var options = { priority: 'High', timeToLive: 5 * 60 }; // TTL: 5 minutes, priority 'Normal' or 'High'
obj.sendToDevice = function (node, payload, options, func) { obj.sendToDevice = function (node, payload, options, func) {
if (typeof node == 'string') { if (typeof node === 'string') {
parent.db.Get(node, function (err, docs) { if ((err == null) && (docs != null) && (docs.length == 1)) { obj.sendToDeviceEx(docs[0], payload, options, func); } else { func(0, 'error'); } }) parent.db.Get(node, function (err, docs) {
if (!err && docs && docs.length === 1) {
obj.sendToDeviceEx(docs[0], payload, options, func);
} else {
func(0, 'error');
}
});
} else { } else {
obj.sendToDeviceEx(node, payload, options, func); obj.sendToDeviceEx(node, payload, options, func);
} }
} };
// Send an outbound push notification // Send an outbound push notification
obj.sendToDeviceEx = function (node, payload, options, func) { obj.sendToDeviceEx = function (node, payload, options, func) {
parent.debug('email', 'Firebase-sendToDevice'); if (!node || typeof node.pmt !== 'string') {
if ((node == null) || (typeof node.pmt != 'string')) return; func(0, 'error');
return;
}
obj.log('sendToDevice, node:' + node._id + ', payload: ' + JSON.stringify(payload) + ', options: ' + JSON.stringify(options)); obj.log('sendToDevice, node:' + node._id + ', payload: ' + JSON.stringify(payload) + ', options: ' + JSON.stringify(options));
// Fill in our lookup table // Fill in our lookup table
if (node._id != null) { tokenToNodeMap[node.pmt] = { nid: node._id, mid: node.meshid, did: node.domain } } if (node._id) {
tokenToNodeMap[node.pmt] = {
// Built the on-screen notification nid: node._id,
var notification = null; mid: node.meshid,
if (payload.notification) { did: node.domain
var notification = new Notification('ic_message') };
.title(payload.notification.title)
.body(payload.notification.body)
.build();
} }
// Build the message const message = {
var message = new Message('msg_' + (++obj.messageId)); token: node.pmt,
if (options.priority) { message.priority(options.priority); } notification: payload.notification,
if (payload.data) { for (var i in payload.data) { message.addData(i, payload.data[i]); } } data: payload.data,
if ((payload.data == null) || (payload.data.shash == null)) { message.addData('shash', parent.webserver.agentCertificateHashBase64); } // Add the server agent hash, new Android agents will reject notifications that don't have this. android: {
if (notification) { message.notification(notification) } priority: options.priority || 'high',
message.build(); ttl: options.timeToLive ? options.timeToLive * 1000 : undefined
}
};
// Send the message admin.messaging().send(message).then(function (response) {
function callback(result) { obj.stats.sent++;
if (result.getError() == null) { obj.stats.sent++; obj.log('Success'); } else { obj.stats.sendError++; obj.log('Fail'); } obj.log('Success');
callback.func(result.getMessageId(), result.getError(), result.getErrorDescription()) func(response);
} }).catch(function (error) {
callback.func = func; obj.stats.sendError++;
parent.debug('email', 'Firebase-sending'); obj.log('Fail: ' + error);
xcs.sendNoRetry(message, node.pmt, callback); func(0, error);
} });
};
// Setup a two way relay // Setup a two way relay
obj.setupRelay = function (ws) { obj.setupRelay = function (ws) {
// Select and set a relay identifier
ws.relayId = getRandomPassword(); ws.relayId = getRandomPassword();
while (obj.relays[ws.relayId] != null) { ws.relayId = getRandomPassword(); } while (obj.relays[ws.relayId]) { ws.relayId = getRandomPassword(); }
obj.relays[ws.relayId] = ws; obj.relays[ws.relayId] = ws;
// On message, parse it
ws.on('message', function (msg) { ws.on('message', function (msg) {
parent.debug('email', 'FBWS-Data(' + this.relayId + '): ' + msg); parent.debug('email', 'FBWS-Data(' + this.relayId + '): ' + msg);
if (typeof msg == 'string') { if (typeof msg === 'string') {
obj.log('Relay: ' + msg); obj.log('Relay: ' + msg);
// Parse the incoming push request let data;
var data = null; try { data = JSON.parse(msg); } catch (ex) { return; }
try { data = JSON.parse(msg) } catch (ex) { return; } if (typeof data !== 'object') return;
if (typeof data != 'object') return; if (!parent.common.validateObjectForMongo(data, 4096)) return;
if (parent.common.validateObjectForMongo(data, 4096) == false) return; // Perform sanity checking on this object. if (typeof data.pmt !== 'string' || typeof data.payload !== 'object') return;
if (typeof data.pmt != 'string') return;
if (typeof data.payload != 'object') return;
if (typeof data.payload.notification == 'object') {
if (typeof data.payload.notification.title != 'string') return;
if (typeof data.payload.notification.body != 'string') return;
}
if (typeof data.options != 'object') return;
if ((data.options.priority != 'Normal') && (data.options.priority != 'High')) return;
if ((typeof data.options.timeToLive != 'number') || (data.options.timeToLive < 1)) return;
if (typeof data.payload.data != 'object') { data.payload.data = {}; }
data.payload.data.r = ws.relayId; // Set the relay id.
// Send the push notification data.payload.data = data.payload.data || {};
obj.sendToDevice({ pmt: data.pmt }, data.payload, data.options, function (id, err, errdesc) { data.payload.data.r = ws.relayId;
if (err == null) {
try { wsrelay.send(JSON.stringify({ sent: true })); } catch (ex) { } obj.sendToDevice({ pmt: data.pmt }, data.payload, data.options, function (id, err) {
if (!err) {
try { ws.send(JSON.stringify({ sent: true })); } catch (ex) { }
} else { } else {
try { wsrelay.send(JSON.stringify({ sent: false })); } catch (ex) { } try { ws.send(JSON.stringify({ sent: false })); } catch (ex) { }
} }
}); });
} }
@ -190,11 +141,12 @@ module.exports.CreateFirebase = function (parent, senderid, serverkey) {
parent.debug('email', 'FBWS-Close(' + this.relayId + ')'); parent.debug('email', 'FBWS-Close(' + this.relayId + ')');
delete obj.relays[this.relayId]; delete obj.relays[this.relayId];
}); });
};
function getRandomPassword() {
return Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').replace(/\//g, '@');
} }
function getRandomPassword() { return Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').split('/').join('@'); }
return obj; return obj;
}; };

View file

@ -321,7 +321,7 @@ function setup() { InstallModules(['image-size'], start); }
function start() { startEx(process.argv); } function start() { startEx(process.argv); }
function startEx(argv) { function startEx(argv) {
if (argv.length > 2) { indexFile(argv[2]); } else { if (argv.length > 2) { indexFile(argv[2]); } else {
log("MeshCentral Session Recodings Processor"); log("MeshCentral Session Recordings Processor");
log("This tool will index a .mcrec file so that the player can seek thru the file."); log("This tool will index a .mcrec file so that the player can seek thru the file.");
log(""); log("");
log(" Usage: node mcrec [file]"); log(" Usage: node mcrec [file]");

View file

@ -1938,6 +1938,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
} }
if ((command.users != null) && (Array.isArray(command.users)) && (device.users != command.users)) { device.users = command.users; change = 1; } // Don't save this to the db. if ((command.users != null) && (Array.isArray(command.users)) && (device.users != command.users)) { device.users = command.users; change = 1; } // Don't save this to the db.
if ((command.lusers != null) && (Array.isArray(command.lusers)) && (device.lusers != command.lusers)) { device.lusers = command.lusers; change = 1; } // Don't save this to the db.
if ((mesh.mtype == 2) && (!args.wanonly)) { if ((mesh.mtype == 2) && (!args.wanonly)) {
// In WAN mode, the hostname of a computer is not important. Don't log hostname changes. // In WAN mode, the hostname of a computer is not important. Don't log hostname changes.
if (device.host != obj.remoteaddr) { device.host = obj.remoteaddr; change = 1; changes.push('host'); } if (device.host != obj.remoteaddr) { device.host = obj.remoteaddr; change = 1; changes.push('host'); }

View file

@ -767,6 +767,14 @@
"default": false, "default": false,
"description": "When set to true, the MPS server will only accept TLS 1.2 and 1.3 connections. Older Intel AMT devices will not be able to connect." "description": "When set to true, the MPS server will only accept TLS 1.2 and 1.3 connections. Older Intel AMT devices will not be able to connect."
}, },
"prometheus": {
"type": [
"boolean",
"number"
],
"default": false,
"description": "When set to true, a prometheus metrics endpoint will be available \"0.0.0.0:9464/metrics\". If you specify a number instead, the prometheus metrics will listen on this port instead of the default 9464."
},
"no2FactorAuth": { "no2FactorAuth": {
"type": "boolean", "type": "boolean",
"default": false "default": false
@ -856,7 +864,7 @@
"boolean", "boolean",
"object" "object"
], ],
"description": "If set to \"true\", automatic backups of your MeshCentral data will be enabled. Alternatively, you can provide an object with additional values such as \"webdav\", \"backupPath\", \"backupIntervalHours\", and more.", "description": "Enabled by default or if set to true. Disabled if set to false. An object can be provided with additional properties to set autobackup options.",
"properties": { "properties": {
"mongoDumpPath": { "mongoDumpPath": {
"type": "string", "type": "string",
@ -878,6 +886,11 @@
"default": 24, "default": 24,
"description": "How often should the autobackup run in hours from the second meshcentral starts up? Default is every 24 hours" "description": "How often should the autobackup run in hours from the second meshcentral starts up? Default is every 24 hours"
}, },
"backupHour": {
"type": "integer",
"default": 0,
"description": "At which hour the autobackup should run. This forces a daily backup, overrules a custom 'backupIntervalHours'."
},
"keepLastDaysBackup": { "keepLastDaysBackup": {
"type": "integer", "type": "integer",
"default": 10, "default": 10,
@ -1160,6 +1173,11 @@
"default": 2, "default": 2,
"description": "Valid numbers are 1 and 2, changes the style of the login page and some secondary pages." "description": "Valid numbers are 1 and 2, changes the style of the login page and some secondary pages."
}, },
"showModernUIToggle": {
"type": "boolean",
"default": false,
"description": "When set to true, the user will be able to toggle between the modern and classic UI."
},
"title": { "title": {
"type": "string", "type": "string",
"default": "MeshCentral", "default": "MeshCentral",
@ -1664,6 +1682,11 @@
"default": true, "default": true,
"description": "Set to false to disable SMS 2FA." "description": "Set to false to disable SMS 2FA."
}, },
"duo2factor": {
"type": "boolean",
"default": true,
"description": "Set to false to disable Duo 2FA."
},
"push2factor": { "push2factor": {
"type": "boolean", "type": "boolean",
"default": true, "default": true,
@ -1949,6 +1972,11 @@
"default": false, "default": false,
"description": "If true, user consent is accepted after the timeout." "description": "If true, user consent is accepted after the timeout."
}, },
"autoAcceptIfNoUser": {
"type": "boolean",
"default": false,
"description": "If true, user consent is accepted if no user is logged in."
},
"oldStyle": { "oldStyle": {
"type": "boolean", "type": "boolean",
"default": false, "default": false,
@ -2152,6 +2180,11 @@
"default": null, "default": null,
"description": "When set, idle users will be disconnected after a set amounts of minutes." "description": "When set, idle users will be disconnected after a set amounts of minutes."
}, },
"logoutOnIdleSessionTimeout": {
"type": "boolean",
"default": true,
"description": "Determines whether MeshCentral should logout after the session idle timeout elapsed or should just disconnect remote desktop, terminal and files."
},
"userConsentFlags": { "userConsentFlags": {
"type": "object", "type": "object",
"description": "Use this section to require user consent for this domain.", "description": "Use this section to require user consent for this domain.",
@ -2684,6 +2717,26 @@
}, },
"description": "This is used to create HTTP redirections. For example setting \"redirects\": { \"example\":\"https://example.com\" } will make it so that anyone accessing /example on the server will get redirected to the specified URL." "description": "This is used to create HTTP redirections. For example setting \"redirects\": { \"example\":\"https://example.com\" } will make it so that anyone accessing /example on the server will get redirected to the specified URL."
}, },
"duo2factor": {
"type": "object",
"properties": {
"integrationkey": {
"type": "string",
"default": "",
"description": "Integration key from Duo"
},
"secretkey": {
"type": "string",
"default": "",
"description": "Secret key from Duo"
},
"apihostname": {
"type": "string",
"default": "",
"description": "API Hostname from Duo"
}
}
},
"yubikey": { "yubikey": {
"type": "object", "type": "object",
"properties": { "properties": {
@ -2862,12 +2915,10 @@
}, },
"user": { "user": {
"type": "string", "type": "string",
"format": "string",
"description": "SMTP username." "description": "SMTP username."
}, },
"pass": { "pass": {
"type": "string", "type": "string",
"format": "string",
"description": "SMTP password." "description": "SMTP password."
}, },
"tls": { "tls": {
@ -3220,7 +3271,6 @@
] ]
} }
], ],
"additionalProperties": false,
"properties": { "properties": {
"newAccounts": { "newAccounts": {
"type": "boolean", "type": "boolean",
@ -3428,8 +3478,7 @@
"required": [ "required": [
"client_id", "client_id",
"client_secret" "client_secret"
], ]
"additionalProperties": false
}, },
"issuer": { "issuer": {
"type": [ "type": [
@ -3519,8 +3568,7 @@
} }
} }
} }
}, }
"additionalProperties": false
}, },
"custom": { "custom": {
"type": "object", "type": "object",
@ -3571,8 +3619,7 @@
"type": "string", "type": "string",
"description": "REQUIRED IF USING GROUPS: Customer ID from Google Workspace Admin Console (https://admin.google.com/ac/accountsettings/profile)" "description": "REQUIRED IF USING GROUPS: Customer ID from Google Workspace Admin Console (https://admin.google.com/ac/accountsettings/profile)"
} }
}, }
"additionalProperties": false
}, },
"groups": { "groups": {
"type": "object", "type": "object",
@ -3624,8 +3671,7 @@
"default": "groups", "default": "groups",
"description": "Custom claim to use." "description": "Custom claim to use."
} }
}, }
"additionalProperties": false
} }
} }
} }
@ -3690,8 +3736,7 @@
"description": "EAB HMAC KEY", "description": "EAB HMAC KEY",
"default": "" "default": ""
} }
}, }
"additionalProperties": false
} }
}, },
"required": [ "required": [
@ -3786,12 +3831,10 @@
}, },
"user": { "user": {
"type": "string", "type": "string",
"format": "string",
"description": "SMTP username." "description": "SMTP username."
}, },
"pass": { "pass": {
"type": "string", "type": "string",
"format": "string",
"description": "SMTP password." "description": "SMTP password."
}, },
"tls": { "tls": {

View file

@ -583,8 +583,11 @@ function CreateMeshCentralServer(config, args) {
// Launch MeshCentral as a child server and monitor it. // Launch MeshCentral as a child server and monitor it.
obj.launchChildServer = function (startArgs) { obj.launchChildServer = function (startArgs) {
const child_process = require('child_process'); const child_process = require('child_process');
const isInspectorAttached = (()=> { try { return require('node:inspector').url() !== undefined; } catch (_) { return false; } }).call();
const logFromChildProcess = isInspectorAttached ? () => {} : console.log.bind(console);
try { if (process.traceDeprecation === true) { startArgs.unshift('--trace-deprecation'); } } catch (ex) { } try { if (process.traceDeprecation === true) { startArgs.unshift('--trace-deprecation'); } } catch (ex) { }
try { if (process.traceProcessWarnings === true) { startArgs.unshift('--trace-warnings'); } } catch (ex) { } try { if (process.traceProcessWarnings === true) { startArgs.unshift('--trace-warnings'); } } catch (ex) { }
if (startArgs[0] != "--disable-proto=delete") startArgs.unshift("--disable-proto=delete")
childProcess = child_process.execFile(process.argv[0], startArgs, { maxBuffer: Infinity, cwd: obj.parentpath }, function (error, stdout, stderr) { childProcess = child_process.execFile(process.argv[0], startArgs, { maxBuffer: Infinity, cwd: obj.parentpath }, function (error, stdout, stderr) {
if (childProcess.xrestart == 1) { if (childProcess.xrestart == 1) {
setTimeout(function () { obj.launchChildServer(startArgs); }, 500); // This is an expected restart. setTimeout(function () { obj.launchChildServer(startArgs); }, 500); // This is an expected restart.
@ -656,12 +659,12 @@ function CreateMeshCentralServer(config, args) {
else if (data.indexOf('Starting self upgrade to: ') >= 0) { obj.args.specificupdate = data.substring(26).split('\r')[0].split('\n')[0]; childProcess.xrestart = 3; } else if (data.indexOf('Starting self upgrade to: ') >= 0) { obj.args.specificupdate = data.substring(26).split('\r')[0].split('\n')[0]; childProcess.xrestart = 3; }
var datastr = data; var datastr = data;
while (datastr.endsWith('\r') || datastr.endsWith('\n')) { datastr = datastr.substring(0, datastr.length - 1); } while (datastr.endsWith('\r') || datastr.endsWith('\n')) { datastr = datastr.substring(0, datastr.length - 1); }
console.log(datastr); logFromChildProcess(datastr);
}); });
childProcess.stderr.on('data', function (data) { childProcess.stderr.on('data', function (data) {
var datastr = data; var datastr = data;
while (datastr.endsWith('\r') || datastr.endsWith('\n')) { datastr = datastr.substring(0, datastr.length - 1); } while (datastr.endsWith('\r') || datastr.endsWith('\n')) { datastr = datastr.substring(0, datastr.length - 1); }
console.log('ERR: ' + datastr); logFromChildProcess('ERR: ' + datastr);
if (data.startsWith('le.challenges[tls-sni-01].loopback')) { return; } // Ignore this error output from GreenLock if (data.startsWith('le.challenges[tls-sni-01].loopback')) { return; } // Ignore this error output from GreenLock
if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); } if (data[data.length - 1] == '\n') { data = data.substring(0, data.length - 1); }
obj.logError(data); obj.logError(data);
@ -1348,7 +1351,7 @@ function CreateMeshCentralServer(config, args) {
} }
// Check if the database is capable of performing a backup // Check if the database is capable of performing a backup
obj.db.checkBackupCapability(function (err, msg) { if (msg != null) { obj.addServerWarning(msg, true) } }); // Moved behind autobackup config init in startex4: obj.db.checkBackupCapability(function (err, msg) { if (msg != null) { obj.addServerWarning(msg, true) } });
// Load configuration for database if needed // Load configuration for database if needed
if (obj.args.loadconfigfromdb) { if (obj.args.loadconfigfromdb) {
@ -1656,7 +1659,7 @@ function CreateMeshCentralServer(config, args) {
} }
// Setup agent error log // Setup agent error log
if ((obj.config) && (obj.config.settings) && (obj.config.settings.agentlogdump != null)) { if ((obj.config) && (obj.config.settings) && (obj.config.settings.agentlogdump)) {
obj.fs.open(obj.path.join(obj.datapath, 'agenterrorlogs.txt'), 'a', function (err, fd) { obj.agentErrorLog = fd; }) obj.fs.open(obj.path.join(obj.datapath, 'agenterrorlogs.txt'), 'a', function (err, fd) { obj.agentErrorLog = fd; })
} }
@ -1998,29 +2001,25 @@ function CreateMeshCentralServer(config, args) {
// Setup Firebase // Setup Firebase
if ((config.firebase != null) && (typeof config.firebase.senderid == 'string') && (typeof config.firebase.serverkey == 'string')) { if ((config.firebase != null) && (typeof config.firebase.senderid == 'string') && (typeof config.firebase.serverkey == 'string')) {
if (nodeVersion >= 23) { addServerWarning('Firebase now requires a service account JSON file, Firebase disabled.', 27);
addServerWarning('Firebase is not supported on this version of NodeJS.', 27); } else if ((config.firebase != null) && (typeof config.firebase.serviceaccountfile == 'string')) {
} else { var serviceAccount;
obj.firebase = require('./firebase').CreateFirebase(obj, config.firebase.senderid, config.firebase.serverkey); try { serviceAccount = JSON.parse(obj.fs.readFileSync(obj.path.join(obj.datapath, config.firebase.serviceaccountfile)).toString()); } catch (ex) { console.log(ex); }
} if (serviceAccount != null) { obj.firebase = require('./firebase').CreateFirebase(obj, serviceAccount); }
} else if ((typeof config.firebaserelay == 'object') && (typeof config.firebaserelay.url == 'string')) { } else if ((typeof config.firebaserelay == 'object') && (typeof config.firebaserelay.url == 'string')) {
if (nodeVersion >= 23) { // Setup the push messaging relay
addServerWarning('Firebase is not supported on this version of NodeJS.', 27); obj.firebase = require('./firebase').CreateFirebaseRelay(obj, config.firebaserelay.url, config.firebaserelay.key);
} else {
// Setup the push messaging relay
obj.firebase = require('./firebase').CreateFirebaseRelay(obj, config.firebaserelay.url, config.firebaserelay.key);
}
} else if (obj.config.settings.publicpushnotifications === true) { } else if (obj.config.settings.publicpushnotifications === true) {
if (nodeVersion >= 23) { // Setup the Firebase push messaging relay using https://alt.meshcentral.com, this is the public push notification server.
addServerWarning('Firebase is not supported on this version of NodeJS.', 27); obj.firebase = require('./firebase').CreateFirebaseRelay(obj, 'https://alt.meshcentral.com/firebaserelay.aspx');
} else {
// Setup the Firebase push messaging relay using https://alt.meshcentral.com, this is the public push notification server.
obj.firebase = require('./firebase').CreateFirebaseRelay(obj, 'https://alt.meshcentral.com/firebaserelay.aspx');
}
} }
// Setup monitoring
obj.monitoring = require('./monitoring.js').CreateMonitoring(obj, obj.args);
// Start periodic maintenance // Start periodic maintenance
obj.maintenanceTimer = setInterval(obj.maintenanceActions, 1000 * 60 * 60); // Run this every hour obj.maintenanceTimer = setInterval(obj.maintenanceActions, 1000 * 60 * 60); // Run this every hour
//obj.maintenanceTimer = setInterval(obj.maintenanceActions, 1000 * 10 * 1); // DEBUG: Run this more often
// Dispatch an event that the server is now running // Dispatch an event that the server is now running
obj.DispatchEvent(['*'], obj, { etype: 'server', action: 'started', msg: 'Server started' }); obj.DispatchEvent(['*'], obj, { etype: 'server', action: 'started', msg: 'Server started' });
@ -2105,23 +2104,24 @@ function CreateMeshCentralServer(config, args) {
obj.updateServerState('state', "running"); obj.updateServerState('state', "running");
// Setup auto-backup defaults // Setup auto-backup defaults
if (obj.config.settings.autobackup == null || obj.config.settings.autobackup == false || obj.config.settings.autobackup == 'false') { obj.config.settings.autobackup = {backupintervalhours: 0}; } //no schedule, but able to console autobackup if (obj.config.settings.autobackup == false || obj.config.settings.autobackup == 'false') { obj.config.settings.autobackup = {backupintervalhours: 0}; } //no schedule, but able to console autobackup
else { else {
if (obj.config.settings.autobackup === true) {obj.config.settings.autobackup = {backupintervalhours: 24, keeplastdaysbackup: 10}; }; if (obj.config.settings.autobackup == null || obj.config.settings.autobackup === true) { obj.config.settings.autobackup = {backupintervalhours: 24, keeplastdaysbackup: 10}; };
if (typeof obj.config.settings.autobackup.backupintervalhours != 'number') { obj.config.settings.autobackup.backupintervalhours = 24; }; if (typeof obj.config.settings.autobackup.backupintervalhours != 'number') { obj.config.settings.autobackup.backupintervalhours = 24; };
if (typeof obj.config.settings.autobackup.keeplastdaysbackup != 'number') { obj.config.settings.autobackup.keeplastdaysbackup = 10; }; if (typeof obj.config.settings.autobackup.keeplastdaysbackup != 'number') { obj.config.settings.autobackup.keeplastdaysbackup = 10; };
if (obj.config.settings.autobackup.backuphour != null ) { obj.config.settings.autobackup.backupintervalhours = 24; if ((typeof obj.config.settings.autobackup.backuphour != 'number') || (obj.config.settings.autobackup.backuphour > 23 || obj.config.settings.autobackup.backuphour < 0 )) { obj.config.settings.autobackup.backuphour = 0; }}
else {obj.config.settings.autobackup.backuphour = -1 };
//arrayfi in case of string and remove possible ', ' space. !! If a string instead of an array is passed, it will be split by ',' so *{.txt,.log} won't work in that case !! //arrayfi in case of string and remove possible ', ' space. !! If a string instead of an array is passed, it will be split by ',' so *{.txt,.log} won't work in that case !!
if (!obj.config.settings.autobackup.backupignorefilesglob) {obj.config.settings.autobackup.backupignorefilesglob = []} if (!obj.config.settings.autobackup.backupignorefilesglob) {obj.config.settings.autobackup.backupignorefilesglob = []}
else if (typeof obj.config.settings.autobackup.backupignorefilesglob == 'string') { obj.config.settings.autobackup.backupignorefilesglob = obj.config.settings.autobackup.backupignorefilesglob.replaceAll(', ', ',').split(','); }; else if (typeof obj.config.settings.autobackup.backupignorefilesglob == 'string') { obj.config.settings.autobackup.backupignorefilesglob = obj.config.settings.autobackup.backupignorefilesglob.replaceAll(', ', ',').split(','); };
if (!obj.config.settings.autobackup.backupskipfoldersglob) {obj.config.settings.autobackup.backupskipfoldersglob = []} if (!obj.config.settings.autobackup.backupskipfoldersglob) {obj.config.settings.autobackup.backupskipfoldersglob = []}
else if (typeof obj.config.settings.autobackup.backupskipfoldersglob == 'string') { obj.config.settings.autobackup.backupskipfoldersglob = obj.config.settings.autobackup.backupskipfoldersglob.replaceAll(', ', ',').split(','); }; else if (typeof obj.config.settings.autobackup.backupskipfoldersglob == 'string') { obj.config.settings.autobackup.backupskipfoldersglob = obj.config.settings.autobackup.backupskipfoldersglob.replaceAll(', ', ',').split(','); };
if (typeof obj.config.settings.autobackup.backuppath == 'string') { obj.backuppath = (obj.config.settings.autobackup.backuppath = (obj.path.resolve(obj.config.settings.autobackup.backuppath))) } else { obj.config.settings.autobackup.backuppath = obj.backuppath };
if (typeof obj.config.settings.autobackup.backupname != 'string') { obj.config.settings.autobackup.backupname = 'meshcentral-autobackup-'};
} }
// Check that autobackup path is not within the "meshcentral-data" folder. // Check if the database is capable of performing a backup
if ((typeof obj.config.settings.autobackup == 'object') && (typeof obj.config.settings.autobackup.backuppath == 'string') && (obj.path.normalize(obj.config.settings.autobackup.backuppath).startsWith(obj.path.normalize(obj.datapath)))) { obj.db.checkBackupCapability(function (err, msg) { if (msg != null) { obj.addServerWarning(msg, true) } });
addServerWarning("Backup path can't be set within meshcentral-data folder, backup settings ignored.", 21);
obj.config.settings.autobackup = {backupintervalhours: -1}; //block console autobackup
}
// Load Intel AMT passwords from the "amtactivation.log" file // Load Intel AMT passwords from the "amtactivation.log" file
obj.loadAmtActivationLogPasswords(function (amtPasswords) { obj.loadAmtActivationLogPasswords(function (amtPasswords) {
@ -2283,14 +2283,19 @@ function CreateMeshCentralServer(config, args) {
// Check if we need to perform an automatic backup // Check if we need to perform an automatic backup
function checkAutobackup() { function checkAutobackup() {
if (obj.config.settings.autobackup.backupintervalhours >= 1) { if (obj.config.settings.autobackup.backupintervalhours >= 1 ) {
obj.db.Get('LastAutoBackupTime', function (err, docs) { obj.db.Get('LastAutoBackupTime', function (err, docs) {
if (err != null) return; if (err != null) { console.error("checkAutobackup: Error getting LastBackupTime from DB"); return}
var lastBackup = 0; var lastBackup = 0;
const now = new Date().getTime(); const currentdate = new Date();
let currentHour = currentdate.getHours();
let now = currentdate.getTime();
if (docs.length == 1) { lastBackup = docs[0].value; } if (docs.length == 1) { lastBackup = docs[0].value; }
const delta = now - lastBackup; const delta = now - lastBackup;
if (delta > (obj.config.settings.autobackup.backupintervalhours * 60 * 60 * 1000)) { //const delta = 9999999999; // DEBUG: backup always
obj.debug ('backup', 'Entering checkAutobackup, lastAutoBackupTime: ' + new Date(lastBackup).toLocaleString('default', { dateStyle: 'medium', timeStyle: 'short' }) + ', delta: ' + (delta/(1000*60*60)).toFixed(2) + ' hours');
//start autobackup if interval has passed or at configured hour, whichever comes first. When an hour schedule is missed, it will make a backup immediately.
if ((delta > (obj.config.settings.autobackup.backupintervalhours * 60 * 60 * 1000)) || ((currentHour == obj.config.settings.autobackup.backuphour) && (delta >= 2 * 60 * 60 * 1000))) {
// A new auto-backup is required. // A new auto-backup is required.
obj.db.Set({ _id: 'LastAutoBackupTime', value: now }); // Save the current time in the database obj.db.Set({ _id: 'LastAutoBackupTime', value: now }); // Save the current time in the database
obj.db.performBackup(); // Perform the backup obj.db.performBackup(); // Perform the backup
@ -2412,6 +2417,10 @@ function CreateMeshCentralServer(config, args) {
storeEvent.links = Object.assign({}, storeEvent.links); storeEvent.links = Object.assign({}, storeEvent.links);
for (var i in storeEvent.links) { var ue = obj.common.escapeFieldName(i); if (ue !== i) { storeEvent.links[ue] = storeEvent.links[i]; delete storeEvent.links[i]; } } for (var i in storeEvent.links) { var ue = obj.common.escapeFieldName(i); if (ue !== i) { storeEvent.links[ue] = storeEvent.links[i]; delete storeEvent.links[i]; } }
} }
if (storeEvent.mesh) {
// Escape "mesh" names that may have "." and/or "$"
storeEvent.mesh = obj.common.escapeLinksFieldNameEx(storeEvent.mesh);
}
storeEvent.ids = ids; storeEvent.ids = ids;
obj.db.StoreEvent(storeEvent); obj.db.StoreEvent(storeEvent);
} }
@ -3937,6 +3946,7 @@ function CreateMeshCentralServer(config, args) {
function logWarnEvent(msg) { if (obj.servicelog != null) { obj.servicelog.warn(msg); } console.log(msg); } function logWarnEvent(msg) { if (obj.servicelog != null) { obj.servicelog.warn(msg); } console.log(msg); }
function logErrorEvent(msg) { if (obj.servicelog != null) { obj.servicelog.error(msg); } console.error(msg); } function logErrorEvent(msg) { if (obj.servicelog != null) { obj.servicelog.error(msg); } console.error(msg); }
obj.getServerWarnings = function () { return serverWarnings; } obj.getServerWarnings = function () { return serverWarnings; }
// TODO: migrate from other addServerWarning function and add timestamp
obj.addServerWarning = function (msg, id, args, print) { serverWarnings.push({ msg: msg, id: id, args: args }); if (print !== false) { console.log("WARNING: " + msg); } } obj.addServerWarning = function (msg, id, args, print) { serverWarnings.push({ msg: msg, id: id, args: args }); if (print !== false) { console.log("WARNING: " + msg); } }
// auth.log functions // auth.log functions
@ -4049,7 +4059,16 @@ function InstallModules(modules, args, func) {
try { try {
// Does the module need a specific version? // Does the module need a specific version?
if (moduleVersion) { if (moduleVersion) {
if (require(`${moduleName}/package.json`).version != moduleVersion) { throw new Error(); } var versionMatch = false;
var modulePath = null;
// This is the first way to test if a module is already installed.
try { versionMatch = (require(`${moduleName}/package.json`).version == moduleVersion) } catch (ex) {
if (ex.code == "ERR_PACKAGE_PATH_NOT_EXPORTED") { modulePath = ("" + ex).split(' ').at(-1); } else { throw new Error(); }
}
// If the module is not installed, but we get the ERR_PACKAGE_PATH_NOT_EXPORTED error, try a second way.
if ((versionMatch == false) && (modulePath != null)) {
if (JSON.parse(require('fs').readFileSync(modulePath, 'utf8')).version != moduleVersion) { throw new Error(); }
}
} else { } else {
// For all other modules, do the check here. // For all other modules, do the check here.
// Is the module in package.json? Install exact version. // Is the module in package.json? Install exact version.
@ -4098,6 +4117,7 @@ function InstallModuleEx(modulenames, args, func) {
process.on('SIGINT', function () { if (meshserver != null) { meshserver.Stop(); meshserver = null; } console.log('Server Ctrl-C exit...'); process.exit(); }); process.on('SIGINT', function () { if (meshserver != null) { meshserver.Stop(); meshserver = null; } console.log('Server Ctrl-C exit...'); process.exit(); });
// Add a server warning, warnings will be shown to the administrator on the web application // Add a server warning, warnings will be shown to the administrator on the web application
// TODO: migrate to obj.addServerWarning?
const serverWarnings = []; const serverWarnings = [];
function addServerWarning(msg, id, args, print) { serverWarnings.push({ msg: msg, id: id, args: args }); if (print !== false) { console.log("WARNING: " + msg); } } function addServerWarning(msg, id, args, print) { serverWarnings.push({ msg: msg, id: id, args: args }); if (print !== false) { console.log("WARNING: " + msg); } }
@ -4129,7 +4149,7 @@ var ServerWarnings = {
24: "Unable to load agent logo file: {0}.", 24: "Unable to load agent logo file: {0}.",
25: "This NodeJS version does not support OpenID.", 25: "This NodeJS version does not support OpenID.",
26: "This NodeJS version does not support Discord.js.", 26: "This NodeJS version does not support Discord.js.",
27: "Firebase is not supported on this version of NodeJS." 27: "Firebase now requires a service account JSON file, Firebase disabled."
}; };
*/ */
@ -4183,7 +4203,7 @@ function mainStart() {
// Check if Windows SSPI, LDAP, Passport and YubiKey OTP will be used // Check if Windows SSPI, LDAP, Passport and YubiKey OTP will be used
var sspi = false; var sspi = false;
var ldap = false; var ldap = false;
var passport = null; var passport = [];
var allsspi = true; var allsspi = true;
var yubikey = false; var yubikey = false;
var ssh = false; var ssh = false;
@ -4204,7 +4224,7 @@ function mainStart() {
if (mstsc == false) { config.domains[i].mstsc = false; } if (mstsc == false) { config.domains[i].mstsc = false; }
if (config.domains[i].ssh == true) { ssh = true; } if (config.domains[i].ssh == true) { ssh = true; }
if ((typeof config.domains[i].authstrategies == 'object')) { if ((typeof config.domains[i].authstrategies == 'object')) {
if (passport == null) { passport = ['passport','connect-flash']; } // Passport v0.6.0 requires a patch, see https://github.com/jaredhanson/passport/issues/904 and include connect-flash here to display errors if (passport.indexOf('passport') == -1) { passport.push('passport','connect-flash'); } // Passport v0.6.0 requires a patch, see https://github.com/jaredhanson/passport/issues/904 and include connect-flash here to display errors
if ((typeof config.domains[i].authstrategies.twitter == 'object') && (typeof config.domains[i].authstrategies.twitter.clientid == 'string') && (typeof config.domains[i].authstrategies.twitter.clientsecret == 'string') && (passport.indexOf('passport-twitter') == -1)) { passport.push('passport-twitter'); } if ((typeof config.domains[i].authstrategies.twitter == 'object') && (typeof config.domains[i].authstrategies.twitter.clientid == 'string') && (typeof config.domains[i].authstrategies.twitter.clientsecret == 'string') && (passport.indexOf('passport-twitter') == -1)) { passport.push('passport-twitter'); }
if ((typeof config.domains[i].authstrategies.google == 'object') && (typeof config.domains[i].authstrategies.google.clientid == 'string') && (typeof config.domains[i].authstrategies.google.clientsecret == 'string') && (passport.indexOf('passport-google-oauth20') == -1)) { passport.push('passport-google-oauth20'); } if ((typeof config.domains[i].authstrategies.google == 'object') && (typeof config.domains[i].authstrategies.google.clientid == 'string') && (typeof config.domains[i].authstrategies.google.clientsecret == 'string') && (passport.indexOf('passport-google-oauth20') == -1)) { passport.push('passport-google-oauth20'); }
if ((typeof config.domains[i].authstrategies.github == 'object') && (typeof config.domains[i].authstrategies.github.clientid == 'string') && (typeof config.domains[i].authstrategies.github.clientsecret == 'string') && (passport.indexOf('passport-github2') == -1)) { passport.push('passport-github2'); } if ((typeof config.domains[i].authstrategies.github == 'object') && (typeof config.domains[i].authstrategies.github.clientid == 'string') && (typeof config.domains[i].authstrategies.github.clientsecret == 'string') && (passport.indexOf('passport-github2') == -1)) { passport.push('passport-github2'); }
@ -4225,11 +4245,12 @@ function mainStart() {
if (config.domains[i].sessionrecording != null) { sessionRecording = true; } if (config.domains[i].sessionrecording != null) { sessionRecording = true; }
if ((config.domains[i].passwordrequirements != null) && (config.domains[i].passwordrequirements.bancommonpasswords == true)) { wildleek = true; } if ((config.domains[i].passwordrequirements != null) && (config.domains[i].passwordrequirements.bancommonpasswords == true)) { wildleek = true; }
if ((config.domains[i].newaccountscaptcha != null) && (config.domains[i].newaccountscaptcha !== false)) { captcha = true; } if ((config.domains[i].newaccountscaptcha != null) && (config.domains[i].newaccountscaptcha !== false)) { captcha = true; }
if ((typeof config.domains[i].duo2factor == 'object') && (passport.indexOf('@duosecurity/duo_universal') == -1)) { passport.push('@duosecurity/duo_universal'); }
} }
// Build the list of required modules // Build the list of required modules
// NOTE: ALL MODULES MUST HAVE A VERSION NUMBER AND THE VERSION MUST MATCH THAT USED IN Dockerfile // NOTE: ALL MODULES MUST HAVE A VERSION NUMBER AND THE VERSION MUST MATCH THAT USED IN Dockerfile
var modules = ['archiver@7.0.1', 'body-parser@1.20.3', 'cbor@5.2.0', 'compression@1.7.4', 'cookie-session@2.1.0', 'express@4.21.1', 'express-handlebars@7.1.3', 'express-ws@5.0.2', 'ipcheck@0.1.0', 'minimist@1.2.8', 'multiparty@4.2.3', '@seald-io/nedb', 'node-forge@1.3.1', 'ua-parser-js@1.0.39', 'ws@8.18.0', 'yauzl@2.10.0']; var modules = ['archiver@7.0.1', 'body-parser@1.20.3', 'cbor@5.2.0', 'compression@1.7.5', 'cookie-session@2.1.0', 'express@4.21.2', 'express-handlebars@7.1.3', 'express-ws@5.0.2', 'ipcheck@0.1.0', 'minimist@1.2.8', 'multiparty@4.2.3', '@seald-io/nedb', 'node-forge@1.3.1', 'ua-parser-js@1.0.39', 'ws@8.18.0', 'yauzl@2.10.0'];
if (require('os').platform() == 'win32') { modules.push('node-windows@0.1.14'); modules.push('loadavg-windows@1.1.1'); if (sspi == true) { modules.push('node-sspi@0.2.10'); } } // Add Windows modules if (require('os').platform() == 'win32') { modules.push('node-windows@0.1.14'); modules.push('loadavg-windows@1.1.1'); if (sspi == true) { modules.push('node-sspi@0.2.10'); } } // Add Windows modules
if (ldap == true) { modules.push('ldapauth-fork@5.0.5'); } if (ldap == true) { modules.push('ldapauth-fork@5.0.5'); }
if (ssh == true) { modules.push('ssh2@1.16.0'); } if (ssh == true) { modules.push('ssh2@1.16.0'); }
@ -4250,10 +4271,11 @@ function mainStart() {
if (config.settings.plugins != null) { modules.push('semver@7.5.4'); } // Required for version compat testing and update checks if (config.settings.plugins != null) { modules.push('semver@7.5.4'); } // Required for version compat testing and update checks
if ((config.settings.plugins != null) && (config.settings.plugins.proxy != null)) { modules.push('https-proxy-agent@7.0.2'); } // Required for HTTP/HTTPS proxy support if ((config.settings.plugins != null) && (config.settings.plugins.proxy != null)) { modules.push('https-proxy-agent@7.0.2'); } // Required for HTTP/HTTPS proxy support
else if (config.settings.xmongodb != null) { modules.push('mongojs@3.1.0'); } // Add MongoJS, old driver. else if (config.settings.xmongodb != null) { modules.push('mongojs@3.1.0'); } // Add MongoJS, old driver.
if (nodemailer || ((config.smtp != null) && (config.smtp.name != 'console')) || (config.sendmail != null)) { modules.push('nodemailer@6.9.15'); } // Add SMTP support if (nodemailer || ((config.smtp != null) && (config.smtp.name != 'console')) || (config.sendmail != null)) { modules.push('nodemailer@6.9.16'); } // Add SMTP support
if (sendgrid || (config.sendgrid != null)) { modules.push('@sendgrid/mail'); } // Add SendGrid support if (sendgrid || (config.sendgrid != null)) { modules.push('@sendgrid/mail'); } // Add SendGrid support
if ((args.translate || args.dev) && (Number(process.version.match(/^v(\d+\.\d+)/)[1]) >= 16)) { modules.push('jsdom@22.1.0'); modules.push('esprima@4.0.1'); modules.push('html-minifier@4.0.0'); } // Translation support if ((args.translate || args.dev) && (Number(process.version.match(/^v(\d+\.\d+)/)[1]) >= 16)) { modules.push('jsdom@22.1.0'); modules.push('esprima@4.0.1'); modules.push('html-minifier@4.0.0'); } // Translation support
if (typeof config.settings.crowdsec == 'object') { modules.push('@crowdsec/express-bouncer@0.1.0'); } // Add CrowdSec bounser module (https://www.npmjs.com/package/@crowdsec/express-bouncer) if (typeof config.settings.crowdsec == 'object') { modules.push('@crowdsec/express-bouncer@0.1.0'); } // Add CrowdSec bounser module (https://www.npmjs.com/package/@crowdsec/express-bouncer)
if (config.settings.prometheus != null) { modules.push('prom-client'); } // Add Prometheus Metrics support
if (typeof config.settings.autobackup == 'object') { if (typeof config.settings.autobackup == 'object') {
// Setup encrypted zip support if needed // Setup encrypted zip support if needed
@ -4265,7 +4287,7 @@ function mainStart() {
if ((typeof config.settings.autobackup.webdav.url != 'string') || (typeof config.settings.autobackup.webdav.username != 'string') || (typeof config.settings.autobackup.webdav.password != 'string')) { addServerWarning("Missing WebDAV parameters.", 2, null, !args.launch); } else { modules.push('webdav@4.11.4'); } if ((typeof config.settings.autobackup.webdav.url != 'string') || (typeof config.settings.autobackup.webdav.username != 'string') || (typeof config.settings.autobackup.webdav.password != 'string')) { addServerWarning("Missing WebDAV parameters.", 2, null, !args.launch); } else { modules.push('webdav@4.11.4'); }
} }
// Enable S3 Support // Enable S3 Support
if (typeof config.settings.autobackup.s3 == 'object') { modules.push('minio@8.0.1'); } if (typeof config.settings.autobackup.s3 == 'object') { modules.push('minio@8.0.2'); }
} }
// Setup common password blocking // Setup common password blocking
@ -4301,8 +4323,7 @@ function mainStart() {
if ((typeof config.settings.webpush == 'object') && (typeof config.settings.webpush.email == 'string')) { modules.push('web-push@3.6.6'); } if ((typeof config.settings.webpush == 'object') && (typeof config.settings.webpush.email == 'string')) { modules.push('web-push@3.6.6'); }
// Firebase Support // Firebase Support
// Avoid 0.1.8 due to bugs: https://github.com/guness/node-xcs/issues/43 if ((config.firebase != null) && (typeof config.firebase.serviceaccountfile == 'string')) { modules.push('firebase-admin@12.7.0'); }
if (config.firebase != null) { modules.push('node-xcs@0.1.8'); }
// Syslog support // Syslog support
if ((require('os').platform() != 'win32') && (config.settings.syslog || config.settings.syslogjson)) { modules.push('modern-syslog@1.2.0'); } if ((require('os').platform() != 'win32') && (config.settings.syslog || config.settings.syslogjson)) { modules.push('modern-syslog@1.2.0'); }

View file

@ -2243,6 +2243,7 @@ function serverConnect() {
case 'removeDeviceShare': case 'removeDeviceShare':
case 'userbroadcast': { // BROADCAST case 'userbroadcast': { // BROADCAST
if ((settings.cmd == 'shell') || (settings.cmd == 'upload') || (settings.cmd == 'download')) return; if ((settings.cmd == 'shell') || (settings.cmd == 'upload') || (settings.cmd == 'download')) return;
if ((data.type == 'runcommands') && (settings.cmd != 'runcommand')) return;
if ((settings.multiresponse != null) && (settings.multiresponse > 1)) { settings.multiresponse--; break; } if ((settings.multiresponse != null) && (settings.multiresponse > 1)) { settings.multiresponse--; break; }
if (data.responseid == 'meshctrl') { if (data.responseid == 'meshctrl') {
if (data.meshid) { console.log(data.result, data.meshid); } if (data.meshid) { console.log(data.result, data.meshid); }
@ -2665,8 +2666,8 @@ function getDevicesThatMatchFilter(nodes, x) {
} else if (tagSearch != null) { } else if (tagSearch != null) {
// Tag filter // Tag filter
for (var d in nodes) { for (var d in nodes) {
if ((nodes[d].tags == null) && (tagSearch == '')) { r.push(d); } if ((nodes[d].tags == null) && (tagSearch == '')) { r.push(nodes[d]); }
else if (nodes[d].tags != null) { for (var j in nodes[d].tags) { if (nodes[d].tags[j].toLowerCase() == tagSearch) { r.push(d); break; } } } else if (nodes[d].tags != null) { for (var j in nodes[d].tags) { if (nodes[d].tags[j].toLowerCase() == tagSearch) { r.push(nodes[d]); break; } } }
} }
} else if (agentTagSearch != null) { } else if (agentTagSearch != null) {
// Agent Tag filter // Agent Tag filter

View file

@ -847,7 +847,7 @@ function CreateDesktopMultiplexor(parent, domain, nodeid, id, func) {
return; return;
} }
// Write the recording file header // Write the recording file header
parent.parent.debug('relay', 'Relay: Started recoding to file: ' + recFullFilename); parent.parent.debug('relay', 'Relay: Started recording to file: ' + recFullFilename);
var metadata = { magic: 'MeshCentralRelaySession', ver: 1, nodeid: obj.nodeid, meshid: obj.meshid, time: new Date().toLocaleString(), protocol: 2, devicename: obj.name, devicegroup: obj.meshname }; var metadata = { magic: 'MeshCentralRelaySession', ver: 1, nodeid: obj.nodeid, meshid: obj.meshid, time: new Date().toLocaleString(), protocol: 2, devicename: obj.name, devicegroup: obj.meshname };
var firstBlock = JSON.stringify(metadata); var firstBlock = JSON.stringify(metadata);
recordingEntry(fd, 1, 0, firstBlock, function () { recordingEntry(fd, 1, 0, firstBlock, function () {
@ -1347,6 +1347,7 @@ function CreateMeshRelayEx2(parent, ws, req, domain, user, cookie) {
if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; } if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; } if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; } if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; } if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
} }
if (typeof domain.notificationmessages == 'object') { if (typeof domain.notificationmessages == 'object') {

View file

@ -120,6 +120,9 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
if ((typeof sr == 'number') && (sr > 0) && (sr < 1000)) { obj.ws.slowRelay = sr; } if ((typeof sr == 'number') && (sr > 0) && (sr < 1000)) { obj.ws.slowRelay = sr; }
} }
// Check if protocol is set in the cookie and if so replace req.query.p but only if its not already set or blank
if ((cookie != null) && (typeof cookie.p == 'number') && (obj.req.query.p === undefined || obj.req.query.p === "")) { obj.req.query.p = cookie.p; }
// Mesh Rights // Mesh Rights
const MESHRIGHT_EDITMESH = 1; const MESHRIGHT_EDITMESH = 1;
const MESHRIGHT_MANAGEUSERS = 2; const MESHRIGHT_MANAGEUSERS = 2;
@ -442,15 +445,15 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
relayinfo.peer1.sendPeerImage(); relayinfo.peer1.sendPeerImage();
} else { } else {
// Write the recording file header // Write the recording file header
parent.parent.debug('relay', 'Relay: Started recoding to file: ' + recFullFilename); parent.parent.debug('relay', 'Relay: Started recording to file: ' + recFullFilename);
var metadata = { var metadata = {
magic: 'MeshCentralRelaySession', magic: 'MeshCentralRelaySession',
ver: 1, ver: 1,
userid: sessionUser._id, userid: sessionUser._id,
username: sessionUser.name, username: sessionUser.name,
sessionid: obj.id, sessionid: obj.id,
ipaddr1: (obj.req == null) ? null : obj.req.clientIp, ipaddr1: ((obj.peer == null) || (obj.peer.req == null)) ? null : obj.peer.req.clientIp,
ipaddr2: ((obj.peer == null) || (obj.peer.req == null)) ? null : obj.peer.req.clientIp, ipaddr2: (obj.req == null) ? null : obj.req.clientIp,
time: new Date().toLocaleString(), time: new Date().toLocaleString(),
protocol: (((obj.req == null) || (obj.req.query == null)) ? null : obj.req.query.p), protocol: (((obj.req == null) || (obj.req.query == null)) ? null : obj.req.query.p),
nodeid: (((obj.req == null) || (obj.req.query == null)) ? null : obj.req.query.nodeid) nodeid: (((obj.req == null) || (obj.req.query == null)) ? null : obj.req.query.nodeid)
@ -884,7 +887,7 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; } if (user != null) { rcookieData.ruserid = user._id; } else if (obj.nouser === true) { rcookieData.nouser = 1; }
const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey); const rcookie = parent.parent.encodeCookie(rcookieData, parent.parent.loginCookieEncryptionKey);
if (obj.id == null) { obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); } // If there is no connection id, generate one. if (obj.id == null) { obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); } // If there is no connection id, generate one.
const command = { nodeid: cookie.nodeid, action: 'msg', type: 'tunnel', value: '*/' + xdomain + 'meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, tcpport: cookie.tcpport, tcpaddr: cookie.tcpaddr, soptions: {} }; const command = { nodeid: cookie.nodeid, action: 'msg', type: 'tunnel', value: '*/' + xdomain + 'meshrelay.ashx?' + (obj.req.query.p != null ? ('p=' + obj.req.query.p + '&') : '') + 'id=' + obj.id + '&rauth=' + rcookie, tcpport: cookie.tcpport, tcpaddr: cookie.tcpaddr, soptions: {} };
if (user) { command.userid = user._id; } if (user) { command.userid = user._id; }
if (typeof domain.consentmessages == 'object') { if (typeof domain.consentmessages == 'object') {
if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; } if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
@ -893,6 +896,7 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; } if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; } if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; } if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; } if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
} }
if (typeof domain.notificationmessages == 'object') { if (typeof domain.notificationmessages == 'object') {
@ -923,7 +927,7 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
if (obj.id == null) { obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); } // If there is no connection id, generate one. if (obj.id == null) { obj.id = parent.crypto.randomBytes(9).toString('base64').replace(/\+/g, '@').replace(/\//g, '$'); } // If there is no connection id, generate one.
const rcookie = parent.parent.encodeCookie({ ruserid: user._id }, parent.parent.loginCookieEncryptionKey); const rcookie = parent.parent.encodeCookie({ ruserid: user._id }, parent.parent.loginCookieEncryptionKey);
if (obj.req.query.tcpport != null) { if (obj.req.query.tcpport != null) {
const command = { nodeid: obj.req.query.nodeid, action: 'msg', type: 'tunnel', userid: user._id, value: '*/' + xdomain + 'meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, tcpport: obj.req.query.tcpport, tcpaddr: ((obj.req.query.tcpaddr == null) ? '127.0.0.1' : obj.req.query.tcpaddr), soptions: {} }; const command = { nodeid: obj.req.query.nodeid, action: 'msg', type: 'tunnel', userid: user._id, value: '*/' + xdomain + 'meshrelay.ashx?' + (obj.req.query.p != null ? ('p=' + obj.req.query.p + '&') : '') + 'id=' + obj.id + '&rauth=' + rcookie, tcpport: obj.req.query.tcpport, tcpaddr: ((obj.req.query.tcpaddr == null) ? '127.0.0.1' : obj.req.query.tcpaddr), soptions: {} };
if (typeof domain.consentmessages == 'object') { if (typeof domain.consentmessages == 'object') {
if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; } if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; } if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
@ -931,6 +935,7 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; } if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; } if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; } if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; } if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
} }
if (typeof domain.notificationmessages == 'object') { if (typeof domain.notificationmessages == 'object') {
@ -942,14 +947,14 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
parent.parent.debug('relay', 'Relay: Sending agent TCP tunnel command: ' + JSON.stringify(command)); parent.parent.debug('relay', 'Relay: Sending agent TCP tunnel command: ' + JSON.stringify(command));
if (obj.sendAgentMessage(command, user._id, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); } if (obj.sendAgentMessage(command, user._id, domain.id) == false) { delete obj.id; parent.parent.debug('relay', 'Relay: Unable to contact this agent (' + obj.req.clientIp + ')'); }
} else if (obj.req.query.udpport != null) { } else if (obj.req.query.udpport != null) {
const command = { nodeid: obj.req.query.nodeid, action: 'msg', type: 'tunnel', userid: user._id, value: '*/' + xdomain + 'meshrelay.ashx?id=' + obj.id + '&rauth=' + rcookie, udpport: obj.req.query.udpport, udpaddr: ((obj.req.query.udpaddr == null) ? '127.0.0.1' : obj.req.query.udpaddr), soptions: {} }; const command = { nodeid: obj.req.query.nodeid, action: 'msg', type: 'tunnel', userid: user._id, value: '*/' + xdomain + 'meshrelay.ashx?' + (obj.req.query.p != null ? ('p=' + obj.req.query.p + '&') : '') + 'id=' + obj.id + '&rauth=' + rcookie, udpport: obj.req.query.udpport, udpaddr: ((obj.req.query.udpaddr == null) ? '127.0.0.1' : obj.req.query.udpaddr), soptions: {} }; if (typeof domain.consentmessages == 'object') {
if (typeof domain.consentmessages == 'object') {
if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; } if (typeof domain.consentmessages.title == 'string') { command.soptions.consentTitle = domain.consentmessages.title; }
if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; } if (typeof domain.consentmessages.desktop == 'string') { command.soptions.consentMsgDesktop = domain.consentmessages.desktop; }
if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; } if (typeof domain.consentmessages.terminal == 'string') { command.soptions.consentMsgTerminal = domain.consentmessages.terminal; }
if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; } if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; } if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; } if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; } if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
} }
if (typeof domain.notificationmessages == 'object') { if (typeof domain.notificationmessages == 'object') {
@ -1002,6 +1007,7 @@ function CreateMeshRelayEx(parent, ws, req, domain, user, cookie) {
if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; } if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; } if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; } if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; } if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
} }
if (typeof domain.notificationmessages == 'object') { if (typeof domain.notificationmessages == 'object') {
@ -1231,6 +1237,7 @@ function CreateLocalRelayEx(parent, ws, req, domain, user, cookie) {
else if (req.query.p == 11) { protocolStr = 'SSH-TERM'; } else if (req.query.p == 11) { protocolStr = 'SSH-TERM'; }
else if (req.query.p == 12) { protocolStr = 'VNC'; } else if (req.query.p == 12) { protocolStr = 'VNC'; }
else if (req.query.p == 13) { protocolStr = 'SSH-FILES'; } else if (req.query.p == 13) { protocolStr = 'SSH-FILES'; }
else if (req.query.p == 14) { protocolStr = 'Web-TCP'; }
var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msgid: 121, msgArgs: [obj.id, protocolStr, obj.host, Math.floor((Date.now() - obj.time) / 1000)], msg: 'Ended local relay session \"' + obj.id + '\", protocol ' + protocolStr + ' to ' + obj.host + ', ' + Math.floor((Date.now() - obj.time) / 1000) + ' second(s)', nodeid: obj.req.query.nodeid, protocol: req.query.p, in: inTraffc, out: outTraffc }; var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msgid: 121, msgArgs: [obj.id, protocolStr, obj.host, Math.floor((Date.now() - obj.time) / 1000)], msg: 'Ended local relay session \"' + obj.id + '\", protocol ' + protocolStr + ' to ' + obj.host + ', ' + Math.floor((Date.now() - obj.time) / 1000) + ' second(s)', nodeid: obj.req.query.nodeid, protocol: req.query.p, in: inTraffc, out: outTraffc };
if (obj.guestname) { event.guestname = obj.guestname; } // If this is a sharing session, set the guest name here. if (obj.guestname) { event.guestname = obj.guestname; } // If this is a sharing session, set the guest name here.
parent.parent.DispatchEvent(['*', user._id], obj, event); parent.parent.DispatchEvent(['*', user._id], obj, event);
@ -1285,6 +1292,7 @@ function CreateLocalRelayEx(parent, ws, req, domain, user, cookie) {
else if (req.query.p == 11) { protocolStr = 'SSH-TERM'; } else if (req.query.p == 11) { protocolStr = 'SSH-TERM'; }
else if (req.query.p == 12) { protocolStr = 'VNC'; } else if (req.query.p == 12) { protocolStr = 'VNC'; }
else if (req.query.p == 13) { protocolStr = 'SSH-FILES'; } else if (req.query.p == 13) { protocolStr = 'SSH-FILES'; }
else if (req.query.p == 14) { protocolStr = 'Web-TCP'; }
obj.time = Date.now(); obj.time = Date.now();
var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msgid: 120, msgArgs: [obj.id, protocolStr, obj.host], msg: 'Started local relay session \"' + obj.id + '\", protocol ' + protocolStr + ' to ' + obj.host, nodeid: req.query.nodeid, protocol: req.query.p }; var event = { etype: 'relay', action: 'relaylog', domain: domain.id, userid: obj.user._id, username: obj.user.name, msgid: 120, msgArgs: [obj.id, protocolStr, obj.host], msg: 'Started local relay session \"' + obj.id + '\", protocol ' + protocolStr + ' to ' + obj.host, nodeid: req.query.nodeid, protocol: req.query.p };
if (obj.guestname) { event.guestname = obj.guestname; } // If this is a sharing session, set the guest name here. if (obj.guestname) { event.guestname = obj.guestname; } // If this is a sharing session, set the guest name here.

View file

@ -600,7 +600,13 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
} }
} }
if (typeof domain.userconsentflags == 'number') { serverinfo.consent = domain.userconsentflags; } if (typeof domain.userconsentflags == 'number') { serverinfo.consent = domain.userconsentflags; }
if ((typeof domain.usersessionidletimeout == 'number') && (domain.usersessionidletimeout > 0)) { serverinfo.timeout = (domain.usersessionidletimeout * 60 * 1000); } if ((typeof domain.usersessionidletimeout == 'number') && (domain.usersessionidletimeout > 0)) {serverinfo.timeout = (domain.usersessionidletimeout * 60 * 1000); }
if (typeof domain.logoutonidlesessiontimeout == 'boolean') {
serverinfo.logoutonidlesessiontimeout = domain.logoutonidlesessiontimeout;
} else {
// Default
serverinfo.logoutonidlesessiontimeout = true;
}
if (user.siteadmin === SITERIGHT_ADMIN) { if (user.siteadmin === SITERIGHT_ADMIN) {
if (parent.parent.config.settings.managealldevicegroups.indexOf(user._id) >= 0) { serverinfo.manageAllDeviceGroups = true; } if (parent.parent.config.settings.managealldevicegroups.indexOf(user._id) >= 0) { serverinfo.manageAllDeviceGroups = true; }
if (obj.crossDomain === true) { serverinfo.crossDomain = []; for (var i in parent.parent.config.domains) { serverinfo.crossDomain.push(i); } } if (obj.crossDomain === true) { serverinfo.crossDomain = []; for (var i in parent.parent.config.domains) { serverinfo.crossDomain.push(i); } }
@ -922,7 +928,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
// Get a short file and send it back on the web socket // Get a short file and send it back on the web socket
if (common.validateString(command.file, 1, 4096) == false) return; if (common.validateString(command.file, 1, 4096) == false) return;
const scpath = meshPathToRealPath(command.path, user); // This will also check access rights const scpath = meshPathToRealPath(command.path, user); // This will also check access rights
if (scpath == null) break; if ((scpath == null) || (command.file !== parent.path.basename(command.file))) break;
const filePath = parent.path.join(scpath, command.file); const filePath = parent.path.join(scpath, command.file);
fs.stat(filePath, function (err, stat) { fs.stat(filePath, function (err, stat) {
if ((err != null) || (stat == null) || (stat.size >= 204800)) return; if ((err != null) || (stat == null) || (stat.size >= 204800)) return;
@ -937,7 +943,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
if (common.validateString(command.file, 1, 4096) == false) return; if (common.validateString(command.file, 1, 4096) == false) return;
if (typeof command.data != 'string') return; if (typeof command.data != 'string') return;
const scpath = meshPathToRealPath(command.path, user); // This will also check access rights const scpath = meshPathToRealPath(command.path, user); // This will also check access rights
if (scpath == null) break; if ((scpath == null) || (command.file !== parent.path.basename(command.file))) break;
const filePath = parent.path.join(scpath, command.file); const filePath = parent.path.join(scpath, command.file);
var data = null; var data = null;
try { data = Buffer.from(command.data, 'base64'); } catch (ex) { return; } try { data = Buffer.from(command.data, 'base64'); } catch (ex) { return; }
@ -997,6 +1003,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; } if (typeof domain.consentmessages.files == 'string') { command.soptions.consentMsgFiles = domain.consentmessages.files; }
if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; } if ((typeof domain.consentmessages.consenttimeout == 'number') && (domain.consentmessages.consenttimeout > 0)) { command.soptions.consentTimeout = domain.consentmessages.consenttimeout; }
if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; } if (domain.consentmessages.autoacceptontimeout === true) { command.soptions.consentAutoAccept = true; }
if (domain.consentmessages.autoacceptifnouser === true) { command.soptions.consentAutoAcceptIfNoUser = true; }
if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; } if (domain.consentmessages.oldstyle === true) { command.soptions.oldStyle = true; }
} }
if (typeof domain.notificationmessages == 'object') { if (typeof domain.notificationmessages == 'object') {
@ -3072,7 +3079,16 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
} }
if (commandsOk == true) { if (commandsOk == true) {
var theCommand = { action: 'runcommands', type: command.type, cmds: command.cmds, runAsUser: command.runAsUser, reply: command.reply, responseid: command.responseid }; var theCommand = { action: 'runcommands', type: command.type, cmds: command.cmds, runAsUser: command.runAsUser, reply: command.reply, responseid: command.responseid };
if (parent.parent.multiServer != null) { // peering setup var agent = parent.wsagents[node._id];
if ((agent != null) && (agent.authenticated == 2) && (agent.agentInfo != null)) {
// Send the commands to the agent
try { agent.send(JSON.stringify(theCommand)); } catch (ex) { }
if (command.responseid != null && command.reply == false) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'OK' })); } catch (ex) { } }
// Send out an event that these commands where run on this device
var targets = parent.CreateNodeDispatchTargets(node.meshid, node._id, ['server-users', user._id]);
var event = { etype: 'node', userid: user._id, username: user.name, nodeid: node._id, action: 'runcommands', msg: 'Running commands', msgid: msgid, cmds: command.cmds, cmdType: command.type, runAsUser: command.runAsUser, domain: domain.id };
parent.parent.DispatchEvent(targets, obj, event);
} else if (parent.parent.multiServer != null) { // peering setup
// Send the commands to the agent // Send the commands to the agent
parent.parent.multiServer.DispatchMessage({ action: 'agentCommand', nodeid: node._id, command: theCommand}); parent.parent.multiServer.DispatchMessage({ action: 'agentCommand', nodeid: node._id, command: theCommand});
if (command.responseid != null && command.reply == false) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'OK' })); } catch (ex) { } } if (command.responseid != null && command.reply == false) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'OK' })); } catch (ex) { } }
@ -3080,20 +3096,8 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
var targets = parent.CreateNodeDispatchTargets(node.meshid, node._id, ['server-users', user._id]); var targets = parent.CreateNodeDispatchTargets(node.meshid, node._id, ['server-users', user._id]);
var event = { etype: 'node', userid: user._id, username: user.name, nodeid: node._id, action: 'runcommands', msg: 'Running commands', msgid: msgid, cmds: command.cmds, cmdType: command.type, runAsUser: command.runAsUser, domain: domain.id }; var event = { etype: 'node', userid: user._id, username: user.name, nodeid: node._id, action: 'runcommands', msg: 'Running commands', msgid: msgid, cmds: command.cmds, cmdType: command.type, runAsUser: command.runAsUser, domain: domain.id };
parent.parent.multiServer.DispatchEvent(targets, obj, event); parent.parent.multiServer.DispatchEvent(targets, obj, event);
} else { // normal setup } else {
// Get the agent and run the commands if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'Agent not connected' })); } catch (ex) { } }
var agent = parent.wsagents[node._id];
if ((agent != null) && (agent.authenticated == 2) && (agent.agentInfo != null)) {
// Send the commands to the agent
try { agent.send(JSON.stringify(theCommand)); } catch (ex) { }
if (command.responseid != null && command.reply == false) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'OK' })); } catch (ex) { } }
// Send out an event that these commands where run on this device
var targets = parent.CreateNodeDispatchTargets(node.meshid, node._id, ['server-users', user._id]);
var event = { etype: 'node', userid: user._id, username: user.name, nodeid: node._id, action: 'runcommands', msg: 'Running commands', msgid: msgid, cmds: command.cmds, cmdType: command.type, runAsUser: command.runAsUser, domain: domain.id };
parent.parent.DispatchEvent(targets, obj, event);
} else {
if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'Agent not connected' })); } catch (ex) { } }
}
} }
} else { } else {
if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'Invalid command type' })); } catch (ex) { } } if (command.responseid != null) { try { ws.send(JSON.stringify({ action: 'runcommands', responseid: command.responseid, result: 'Invalid command type' })); } catch (ex) { } }
@ -3628,6 +3632,41 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
parent.parent.DispatchEvent(targets, obj, event); parent.parent.DispatchEvent(targets, obj, event);
break; break;
} }
case 'otpduo':
{
// Do not allow this command if 2FA's are locked
if ((domain.passwordrequirements) && (domain.passwordrequirements.lock2factor == true)) return;
// Do not allow if Duo is not supported
if ((typeof domain.duo2factor != 'object') || (typeof domain.duo2factor.integrationkey != 'string') || (typeof domain.duo2factor.secretkey != 'string') || (typeof domain.duo2factor.apihostname != 'string')) return;
// Do not allow if Duo is disabled
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.duo2factor == false)) return;
// Do not allow this command when logged in using a login token
if (req.session.loginToken != null) break;
if ((user.siteadmin != 0xFFFFFFFF) && ((user.siteadmin & 1024) != 0)) return; // If this account is settings locked, return here.
// Check input
if ((typeof command.enabled != 'boolean') || (command.enabled != false)) return;
// See if we really need to change the state
if ((command.enabled === false) && (user.otpduo == null)) return;
// Change the duo 2FA of this user
delete user.otpduo;
parent.db.SetUser(user);
ws.send(JSON.stringify({ action: 'otpduo', success: true, enabled: command.enabled })); // Report success
// Notify change
var targets = ['*', 'server-users', user._id];
if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
var event = { etype: 'user', userid: user._id, username: user.name, account: parent.CloneSafeUser(user), action: 'accountchange', msgid: command.enabled ? 160 : 161, msg: command.enabled ? "Enabled duo two-factor authentication." : "Disabled duo two-factor authentication.", domain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
parent.parent.DispatchEvent(targets, obj, event);
break;
}
case 'otpauth-request': case 'otpauth-request':
{ {
// Do not allow this command if 2FA's are locked // Do not allow this command if 2FA's are locked
@ -5038,262 +5077,294 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
if ((common.validateStrArray(command.nodeids, 1) == false) && (command.nodeids != null)) break; // Check nodeids if ((common.validateStrArray(command.nodeids, 1) == false) && (command.nodeids != null)) break; // Check nodeids
if (common.validateString(command.type, 3, 4) == false) break; // Check type if (common.validateString(command.type, 3, 4) == false) break; // Check type
// Create a list of node ids and query them for last device connection time const links = parent.GetAllMeshIdWithRights(user);
const ids = [] const extraids = getUserExtraIds();
for (var i in command.nodeids) { ids.push('lc' + command.nodeids[i]); } db.GetAllTypeNoTypeFieldMeshFiltered(links, extraids, domain.id, 'node', null, obj.deviceSkip, obj.deviceLimit, function (err, docs) {
db.GetAllIdsOfType(ids, domain.id, 'lastconnect', function (err, docs) { if (docs == null) return;
const lastConnects = {}; const ids = [];
if (docs != null) { for (var i in docs) { lastConnects[docs[i]._id] = docs[i]; } } if (command.nodeids != null) {
// Create a list of node ids and query them for last device connection time
for (var i in command.nodeids) { ids.push('lc' + command.nodeids[i]); }
} else {
// Create a list of node ids for this user and query them for last device connection time
for (var i in docs) { ids.push('lc' + docs[i]._id); }
}
db.GetAllIdsOfType(ids, domain.id, 'lastconnect', function (err, docs) {
const lastConnects = {};
if (docs != null) { for (var i in docs) { lastConnects[docs[i]._id] = docs[i]; } }
getDeviceDetailedInfo(command.nodeids, command.type, function (results, type) {
for (var i = 0; i < results.length; i++) {
// Remove any device system and network information is we do not have details rights to this device
if ((parent.GetNodeRights(user, results[i].node.meshid, results[i].node._id) & MESHRIGHT_DEVICEDETAILS) == 0) {
delete results[i].sys; delete results[i].net;
}
// Merge any last connection information
const lc = lastConnects['lc' + results[i].node._id];
if (lc != null) { delete lc._id; delete lc.type; delete lc.meshid; delete lc.domain; results[i].lastConnect = lc; }
// Remove any connectivity and power state information, that should not be in the database anyway.
// TODO: Find why these are sometimes saved in the db.
if (results[i].node.conn != null) { delete results[i].node.conn; }
if (results[i].node.pwr != null) { delete results[i].node.pwr; }
if (results[i].node.agct != null) { delete results[i].node.agct; }
if (results[i].node.cict != null) { delete results[i].node.cict; }
// Add the connection state
var state = parent.parent.GetConnectivityState(results[i].node._id);
if (state) {
results[i].node.conn = state.connectivity;
results[i].node.pwr = state.powerState;
if ((state.connectivity & 1) != 0) { var agent = parent.wsagents[results[i].node._id]; if (agent != null) { results[i].node.agct = agent.connectTime; } }
// Use the connection time of the CIRA/Relay connection
if ((state.connectivity & 2) != 0) {
var ciraConnection = parent.parent.mpsserver.GetConnectionToNode(results[i].node._id, null, true);
if ((ciraConnection != null) && (ciraConnection.tag != null)) { results[i].node.cict = ciraConnection.tag.connectTime; }
}
}
getDeviceDetailedInfo(command.nodeids, command.type, function (results, type) {
for (var i = 0; i < results.length; i++) {
// Remove any device system and network information is we do not have details rights to this device
if ((parent.GetNodeRights(user, results[i].node.meshid, results[i].node._id) & MESHRIGHT_DEVICEDETAILS) == 0) {
delete results[i].sys; delete results[i].net;
} }
// Merge any last connection information var output = null;
const lc = lastConnects['lc' + results[i].node._id]; if (type == 'csv') {
if (lc != null) { delete lc._id; delete lc.type;; delete lc.meshid; delete lc.domain; results[i].lastConnect = lc; } try {
} // Create the CSV file
output = 'id,name,rname,host,icon,ip,osdesc,groupname,av,update,firewall,bitlocker,avdetails,tags,lastbootuptime,cpu,osbuild,biosDate,biosVendor,biosVersion,biosSerial,biosMode,boardName,boardVendor,boardVersion,productUuid,tpmversion,tpmmanufacturer,tpmmanufacturerversion,tpmisactivated,tpmisenabled,tpmisowned,totalMemory,agentOpenSSL,agentCommitDate,agentCommitHash,agentCompileTime,netIfCount,macs,addresses,lastConnectTime,lastConnectAddr\r\n';
for (var i = 0; i < results.length; i++) {
const nodeinfo = results[i];
var output = null; // Node information
if (type == 'csv') { if (nodeinfo.node != null) {
try { const n = nodeinfo.node;
// Create the CSV file output += csvClean(n._id) + ',' + csvClean(n.name) + ',' + csvClean(n.rname ? n.rname : '') + ',' + csvClean(n.host ? n.host : '') + ',' + (n.icon ? n.icon : 1) + ',' + (n.ip ? n.ip : '') + ',' + (n.osdesc ? csvClean(n.osdesc) : '') + ',' + csvClean(parent.meshes[n.meshid].name);
output = 'id,name,rname,host,icon,ip,osdesc,groupname,av,update,firewall,bitlocker,avdetails,tags,cpu,osbuild,biosDate,biosVendor,biosVersion,biosSerial,biosMode,boardName,boardVendor,boardVersion,productUuid,tpmversion,tpmmanufacturer,tpmmanufacturerversion,tpmisactivated,tpmisenabled,tpmisowned,totalMemory,agentOpenSSL,agentCommitDate,agentCommitHash,agentCompileTime,netIfCount,macs,addresses,lastConnectTime,lastConnectAddr\r\n'; if (typeof n.wsc == 'object') {
for (var i = 0; i < results.length; i++) { output += ',' + csvClean(n.wsc.antiVirus ? n.wsc.antiVirus : '') + ',' + csvClean(n.wsc.autoUpdate ? n.wsc.autoUpdate : '') + ',' + csvClean(n.wsc.firewall ? n.wsc.firewall : '')
const nodeinfo = results[i]; } else { output += ',,,'; }
if (typeof n.volumes == 'object') {
// Node information var bitlockerdetails = '', firstbitlocker = true;
if (nodeinfo.node != null) { for (var a in n.volumes) { if (typeof n.volumes[a].protectionStatus !== 'undefined') { if (firstbitlocker) { firstbitlocker = false; } else { bitlockerdetails += '|'; } bitlockerdetails += a + '/' + n.volumes[a].volumeStatus; } }
const n = nodeinfo.node; output += ',' + csvClean(bitlockerdetails);
output += csvClean(n._id) + ',' + csvClean(n.name) + ',' + csvClean(n.rname ? n.rname : '') + ',' + csvClean(n.host ? n.host : '') + ',' + (n.icon ? n.icon : 1) + ',' + (n.ip ? n.ip : '') + ',' + (n.osdesc ? csvClean(n.osdesc) : '') + ',' + csvClean(parent.meshes[n.meshid].name); } else {
if (typeof n.wsc == 'object') { output += ',';
output += ',' + csvClean(n.wsc.antiVirus ? n.wsc.antiVirus : '') + ',' + csvClean(n.wsc.autoUpdate ? n.wsc.autoUpdate : '') + ',' + csvClean(n.wsc.firewall ? n.wsc.firewall : '')
} else { output += ',,,'; }
if (typeof n.volumes == 'object') {
var bitlockerdetails = '', firstbitlocker = true;
for (var a in n.volumes) { if (typeof n.volumes[a].protectionStatus !== 'undefined') { if (firstbitlocker) { firstbitlocker = false; } else { bitlockerdetails += '|'; } bitlockerdetails += a + '/' + n.volumes[a].volumeStatus; } }
output += ',' + csvClean(bitlockerdetails);
} else {
output += ',';
}
if (typeof n.av == 'object') {
var avdetails = '', firstav = true;
for (var a in n.av) { if (typeof n.av[a].product == 'string') { if (firstav) { firstav = false; } else { avdetails += '|'; } avdetails += (n.av[a].product + '/' + ((n.av[a].enabled) ? 'enabled' : 'disabled') + '/' + ((n.av[a].updated) ? 'updated' : 'notupdated')); } }
output += ',' + csvClean(avdetails);
} else {
output += ',';
}
if (typeof n.tags == 'object') {
var tagsdetails = '', firsttags = true;
for (var a in n.tags) { if (firsttags) { firsttags = false; } else { tagsdetails += '|'; } tagsdetails += n.tags[a]; }
output += ',' + csvClean(tagsdetails);
} else {
output += ',';
}
} else {
output += ',,,,,,,,,,,,,,,,,,,';
}
// System infomation
if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.windows)) {
// Windows
output += ',';
if (nodeinfo.sys.hardware.windows.cpu && (nodeinfo.sys.hardware.windows.cpu.length > 0) && (typeof nodeinfo.sys.hardware.windows.cpu[0].Name == 'string')) { output += csvClean(nodeinfo.sys.hardware.windows.cpu[0].Name); }
output += ',';
if (nodeinfo.sys.hardware.windows.osinfo && (nodeinfo.sys.hardware.windows.osinfo.BuildNumber)) { output += csvClean(nodeinfo.sys.hardware.windows.osinfo.BuildNumber); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_date)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_date); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_vendor)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_vendor); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_version)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_version); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_serial)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_serial); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_mode)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_mode); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.board_name)) { output += csvClean(nodeinfo.sys.hardware.identifiers.board_name); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.board_vendor)) { output += csvClean(nodeinfo.sys.hardware.identifiers.board_vendor); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.board_version)) { output += csvClean(nodeinfo.sys.hardware.identifiers.board_version); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.product_uuid)) { output += csvClean(nodeinfo.sys.hardware.identifiers.product_uuid); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.SpecVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.SpecVersion); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerId) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerId); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerVersion); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsActivated) { output += csvClean(nodeinfo.sys.hardware.tpm.IsActivated ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsEnabled) { output += csvClean(nodeinfo.sys.hardware.tpm.IsEnabled ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsOwned) { output += csvClean(nodeinfo.sys.hardware.tpm.IsOwned ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.windows.memory) {
var totalMemory = 0;
for (var j in nodeinfo.sys.hardware.windows.memory) {
if (nodeinfo.sys.hardware.windows.memory[j].Capacity) {
if (typeof nodeinfo.sys.hardware.windows.memory[j].Capacity == 'number') { totalMemory += nodeinfo.sys.hardware.windows.memory[j].Capacity; }
if (typeof nodeinfo.sys.hardware.windows.memory[j].Capacity == 'string') { totalMemory += parseInt(nodeinfo.sys.hardware.windows.memory[j].Capacity); }
}
} }
output += csvClean('' + totalMemory); if (typeof n.av == 'object') {
var avdetails = '', firstav = true;
for (var a in n.av) { if (typeof n.av[a].product == 'string') { if (firstav) { firstav = false; } else { avdetails += '|'; } avdetails += (n.av[a].product + '/' + ((n.av[a].enabled) ? 'enabled' : 'disabled') + '/' + ((n.av[a].updated) ? 'updated' : 'notupdated')); } }
output += ',' + csvClean(avdetails);
} else {
output += ',';
}
if (typeof n.tags == 'object') {
var tagsdetails = '', firsttags = true;
for (var a in n.tags) { if (firsttags) { firsttags = false; } else { tagsdetails += '|'; } tagsdetails += n.tags[a]; }
output += ',' + csvClean(tagsdetails);
} else {
output += ',';
}
if (typeof n.lastbootuptime == 'number') { output += ',' + n.lastbootuptime; } else { output += ','; }
} else {
output += ',,,,,,,,,,,,,,,,,,,,';
} }
} else if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.mobile)) {
// Mobile // System infomation
output += ','; if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.windows)) {
output += ','; // Windows
output += ','; output += ',';
output += ','; if (nodeinfo.sys.hardware.windows.cpu && (nodeinfo.sys.hardware.windows.cpu.length > 0) && (typeof nodeinfo.sys.hardware.windows.cpu[0].Name == 'string')) { output += csvClean(nodeinfo.sys.hardware.windows.cpu[0].Name); }
output += ','; output += ',';
if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.bootloader)) { output += csvClean(nodeinfo.sys.hardware.mobile.bootloader); } if (nodeinfo.sys.hardware.windows.osinfo && (nodeinfo.sys.hardware.windows.osinfo.BuildNumber)) { output += csvClean(nodeinfo.sys.hardware.windows.osinfo.BuildNumber); }
output += ','; output += ',';
output += ','; if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_date)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_date); }
output += ','; output += ',';
if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.model)) { output += csvClean(nodeinfo.sys.hardware.mobile.model); } if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_vendor)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_vendor); }
output += ','; output += ',';
if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.brand)) { output += csvClean(nodeinfo.sys.hardware.mobile.brand); } if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_version)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_version); }
output += ','; output += ',';
output += ','; if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_serial)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_serial); }
if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.id)) { output += csvClean(nodeinfo.sys.hardware.mobile.id); } output += ',';
output += ','; if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_mode)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_mode); }
output += ','; output += ',';
output += ','; if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.board_name)) { output += csvClean(nodeinfo.sys.hardware.identifiers.board_name); }
output += ','; output += ',';
output += ','; if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.board_vendor)) { output += csvClean(nodeinfo.sys.hardware.identifiers.board_vendor); }
output += ','; output += ',';
output += ','; if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.board_version)) { output += csvClean(nodeinfo.sys.hardware.identifiers.board_version); }
} else if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.linux)) { output += ',';
// Linux if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.product_uuid)) { output += csvClean(nodeinfo.sys.hardware.identifiers.product_uuid); }
output += ','; output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.cpu_name)) { output += csvClean(nodeinfo.sys.hardware.identifiers.cpu_name); } if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.SpecVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.SpecVersion); }
output += ',,'; output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.bios_date)) { output += csvClean(nodeinfo.sys.hardware.linux.bios_date); } if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerId) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerId); }
output += ','; output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.bios_vendor)) { output += csvClean(nodeinfo.sys.hardware.linux.bios_vendor); } if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerVersion); }
output += ','; output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.bios_version)) { output += csvClean(nodeinfo.sys.hardware.linux.bios_version); } if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsActivated) { output += csvClean(nodeinfo.sys.hardware.tpm.IsActivated ? 'true' : 'false'); }
output += ','; output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.product_serial)) { output += csvClean(nodeinfo.sys.hardware.linux.product_serial); } if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsEnabled) { output += csvClean(nodeinfo.sys.hardware.tpm.IsEnabled ? 'true' : 'false'); }
else if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_serial)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_serial); } output += ',';
output += ','; if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsOwned) { output += csvClean(nodeinfo.sys.hardware.tpm.IsOwned ? 'true' : 'false'); }
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_mode)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_mode); } output += ',';
output += ','; if (nodeinfo.sys.hardware.windows.memory) {
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.board_name)) { output += csvClean(nodeinfo.sys.hardware.linux.board_name); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.board_vendor)) { output += csvClean(nodeinfo.sys.hardware.linux.board_vendor); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.board_version)) { output += csvClean(nodeinfo.sys.hardware.linux.board_version); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.product_uuid)) { output += csvClean(nodeinfo.sys.hardware.linux.product_uuid); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.SpecVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.SpecVersion); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerId) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerId); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerVersion); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsActivated) { output += csvClean(nodeinfo.sys.hardware.tpm.IsActivated ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsEnabled) { output += csvClean(nodeinfo.sys.hardware.tpm.IsEnabled ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsOwned) { output += csvClean(nodeinfo.sys.hardware.tpm.IsOwned ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.linux.memory) {
if (nodeinfo.sys.hardware.linux.memory.Memory_Device) {
var totalMemory = 0; var totalMemory = 0;
for (var j in nodeinfo.sys.hardware.linux.memory.Memory_Device) { for (var j in nodeinfo.sys.hardware.windows.memory) {
if (nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size) { if (nodeinfo.sys.hardware.windows.memory[j].Capacity) {
if (typeof nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size == 'number') { totalMemory += nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size; } if (typeof nodeinfo.sys.hardware.windows.memory[j].Capacity == 'number') { totalMemory += nodeinfo.sys.hardware.windows.memory[j].Capacity; }
if (typeof nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size == 'string') { totalMemory += parseInt(nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size); } if (typeof nodeinfo.sys.hardware.windows.memory[j].Capacity == 'string') { totalMemory += parseInt(nodeinfo.sys.hardware.windows.memory[j].Capacity); }
} }
} }
output += csvClean('' + (totalMemory * Math.pow(1024, 3))); output += csvClean('' + totalMemory);
} }
} } else if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.mobile)) {
} else { // Mobile
output += ',,,,,,,,,,,,,,,,,,'; output += ',';
} output += ',';
output += ',';
// Agent information output += ',';
if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.agentvers)) { output += ',';
output += ','; if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.bootloader)) { output += csvClean(nodeinfo.sys.hardware.mobile.bootloader); }
if (nodeinfo.sys.hardware.agentvers.openssl) { output += csvClean(nodeinfo.sys.hardware.agentvers.openssl); } output += ',';
output += ','; output += ',';
if (nodeinfo.sys.hardware.agentvers.commitDate) { output += csvClean(nodeinfo.sys.hardware.agentvers.commitDate); } output += ',';
output += ','; if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.model)) { output += csvClean(nodeinfo.sys.hardware.mobile.model); }
if (nodeinfo.sys.hardware.agentvers.commitHash) { output += csvClean(nodeinfo.sys.hardware.agentvers.commitHash); } output += ',';
output += ','; if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.brand)) { output += csvClean(nodeinfo.sys.hardware.mobile.brand); }
if (nodeinfo.sys.hardware.agentvers.compileTime) { output += csvClean(nodeinfo.sys.hardware.agentvers.compileTime); } output += ',';
} else { output += ',';
output += ',,,,'; if (nodeinfo.sys.hardware.mobile && (nodeinfo.sys.hardware.mobile.id)) { output += csvClean(nodeinfo.sys.hardware.mobile.id); }
} output += ',';
output += ',';
// Network interfaces output += ',';
if ((nodeinfo.net) && (nodeinfo.net.netif2)) { output += ',';
output += ','; output += ',';
output += Object.keys(nodeinfo.net.netif2).length; // Interface count output += ',';
var macs = [], addresses = []; output += ',';
for (var j in nodeinfo.net.netif2) { } else if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.linux)) {
if (Array.isArray(nodeinfo.net.netif2[j])) { // Linux
for (var k = 0; k < nodeinfo.net.netif2[j].length; k++) { output += ',';
if (typeof nodeinfo.net.netif2[j][k].mac == 'string') { macs.push(nodeinfo.net.netif2[j][k].mac); } if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.cpu_name)) { output += csvClean(nodeinfo.sys.hardware.identifiers.cpu_name); }
if (typeof nodeinfo.net.netif2[j][k].address == 'string') { addresses.push(nodeinfo.net.netif2[j][k].address); } output += ',,';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.bios_date)) { output += csvClean(nodeinfo.sys.hardware.linux.bios_date); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.bios_vendor)) { output += csvClean(nodeinfo.sys.hardware.linux.bios_vendor); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.bios_version)) { output += csvClean(nodeinfo.sys.hardware.linux.bios_version); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.product_serial)) { output += csvClean(nodeinfo.sys.hardware.linux.product_serial); }
else if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_serial)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_serial); }
output += ',';
if (nodeinfo.sys.hardware.identifiers && (nodeinfo.sys.hardware.identifiers.bios_mode)) { output += csvClean(nodeinfo.sys.hardware.identifiers.bios_mode); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.board_name)) { output += csvClean(nodeinfo.sys.hardware.linux.board_name); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.board_vendor)) { output += csvClean(nodeinfo.sys.hardware.linux.board_vendor); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.board_version)) { output += csvClean(nodeinfo.sys.hardware.linux.board_version); }
output += ',';
if (nodeinfo.sys.hardware.linux && (nodeinfo.sys.hardware.linux.product_uuid)) { output += csvClean(nodeinfo.sys.hardware.linux.product_uuid); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.SpecVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.SpecVersion); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerId) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerId); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.ManufacturerVersion) { output += csvClean(nodeinfo.sys.hardware.tpm.ManufacturerVersion); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsActivated) { output += csvClean(nodeinfo.sys.hardware.tpm.IsActivated ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsEnabled) { output += csvClean(nodeinfo.sys.hardware.tpm.IsEnabled ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.tpm && nodeinfo.sys.hardware.tpm.IsOwned) { output += csvClean(nodeinfo.sys.hardware.tpm.IsOwned ? 'true' : 'false'); }
output += ',';
if (nodeinfo.sys.hardware.linux.memory) {
if (nodeinfo.sys.hardware.linux.memory.Memory_Device) {
var totalMemory = 0;
for (var j in nodeinfo.sys.hardware.linux.memory.Memory_Device) {
if (nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size) {
if (typeof nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size == 'number') { totalMemory += nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size; }
if (typeof nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size == 'string') { totalMemory += parseInt(nodeinfo.sys.hardware.linux.memory.Memory_Device[j].Size); }
}
}
output += csvClean('' + (totalMemory * Math.pow(1024, 3)));
} }
} }
} else {
output += ',,,,,,,,,,,,,,,,,,';
} }
output += ',';
output += csvClean(macs.join(' ')); // MACS
output += ',';
output += csvClean(addresses.join(' ')); // Addresses
} else {
output += ',,,';
}
// Last connection information // Agent information
if (nodeinfo.lastConnect) { if ((nodeinfo.sys) && (nodeinfo.sys.hardware) && (nodeinfo.sys.hardware.agentvers)) {
output += ','; output += ',';
if (nodeinfo.lastConnect.time) { if (nodeinfo.sys.hardware.agentvers.openssl) { output += csvClean(nodeinfo.sys.hardware.agentvers.openssl); }
// Last connection time output += ',';
if ((typeof command.l == 'string') && (typeof command.tz == 'string')) { if (nodeinfo.sys.hardware.agentvers.commitDate) { output += csvClean(nodeinfo.sys.hardware.agentvers.commitDate); }
output += csvClean(new Date(nodeinfo.lastConnect.time).toLocaleString(command.l, { timeZone: command.tz })) output += ',';
} else { if (nodeinfo.sys.hardware.agentvers.commitHash) { output += csvClean(nodeinfo.sys.hardware.agentvers.commitHash); }
output += nodeinfo.lastConnect.time; output += ',';
if (nodeinfo.sys.hardware.agentvers.compileTime) { output += csvClean(nodeinfo.sys.hardware.agentvers.compileTime); }
} else {
output += ',,,,';
}
// Network interfaces
if ((nodeinfo.net) && (nodeinfo.net.netif2)) {
output += ',';
output += Object.keys(nodeinfo.net.netif2).length; // Interface count
var macs = [], addresses = [];
for (var j in nodeinfo.net.netif2) {
if (Array.isArray(nodeinfo.net.netif2[j])) {
for (var k = 0; k < nodeinfo.net.netif2[j].length; k++) {
if (typeof nodeinfo.net.netif2[j][k].mac == 'string') { macs.push(nodeinfo.net.netif2[j][k].mac); }
if (typeof nodeinfo.net.netif2[j][k].address == 'string') { addresses.push(nodeinfo.net.netif2[j][k].address); }
}
}
} }
output += ',';
output += csvClean(macs.join(' ')); // MACS
output += ',';
output += csvClean(addresses.join(' ')); // Addresses
} else {
output += ',,,';
} }
output += ',';
if (typeof nodeinfo.lastConnect.addr == 'string') { output += csvClean(nodeinfo.lastConnect.addr); } // Last connection address and port // Last connection information
} else { if (nodeinfo.lastConnect) {
output += ',,'; output += ',';
if (nodeinfo.lastConnect.time) {
// Last connection time
if ((typeof command.l == 'string') && (typeof command.tz == 'string')) {
output += csvClean(new Date(nodeinfo.lastConnect.time).toLocaleString(command.l, { timeZone: command.tz }))
} else {
output += nodeinfo.lastConnect.time;
}
}
output += ',';
if (typeof nodeinfo.lastConnect.addr == 'string') { output += csvClean(nodeinfo.lastConnect.addr); } // Last connection address and port
} else {
output += ',,';
}
output += '\r\n';
} }
} catch (ex) { console.log(ex); }
} else {
// Create the JSON file
output += '\r\n'; // Add the device group name to each device
for (var i = 0; i < results.length; i++) {
const nodeinfo = results[i];
if (nodeinfo.node) {
const mesh = parent.meshes[nodeinfo.node.meshid];
if (mesh) { results[i].node.groupname = mesh.name; }
}
} }
} catch (ex) { console.log(ex); }
} else {
// Create the JSON file
// Add the device group name to each device output = JSON.stringify(results, null, 2);
for (var i = 0; i < results.length; i++) {
const nodeinfo = results[i];
if (nodeinfo.node) {
const mesh = parent.meshes[nodeinfo.node.meshid];
if (mesh) { results[i].node.groupname = mesh.name; }
}
} }
try { ws.send(JSON.stringify({ action: 'getDeviceDetails', data: output, type: type })); } catch (ex) { }
output = JSON.stringify(results, null, 2); });
}
try { ws.send(JSON.stringify({ action: 'getDeviceDetails', data: output, type: type })); } catch (ex) { }
}); });
}); });
break; break;
} }
case 'endDesktopMultiplex': { case 'endDesktopMultiplex': {
@ -5542,7 +5613,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
'heapdump': [serverUserCommandHeapDump, ""], 'heapdump': [serverUserCommandHeapDump, ""],
'heapdump2': [serverUserCommandHeapDump2, ""], 'heapdump2': [serverUserCommandHeapDump2, ""],
'help': [serverUserCommandHelp, ""], 'help': [serverUserCommandHelp, ""],
'info': [serverUserCommandInfo, "Returns the most immidiatly useful information about this server, including MeshCentral and NodeJS versions. This is often information required to file a bug."], 'info': [serverUserCommandInfo, "Returns the most immidiatly useful information about this server, including MeshCentral and NodeJS versions. This is often information required to file a bug. Optionally use info h for human readable form."],
'le': [serverUserCommandLe, ""], 'le': [serverUserCommandLe, ""],
'lecheck': [serverUserCommandLeCheck, ""], 'lecheck': [serverUserCommandLeCheck, ""],
'leevents': [serverUserCommandLeEvents, ""], 'leevents': [serverUserCommandLeEvents, ""],
@ -6345,6 +6416,7 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
if (command.nodeid) { cookieContent.nodeid = command.nodeid; } if (command.nodeid) { cookieContent.nodeid = command.nodeid; }
if (command.tcpaddr) { cookieContent.tcpaddr = command.tcpaddr; } // Indicates the browser want the agent to TCP connect to a remote address if (command.tcpaddr) { cookieContent.tcpaddr = command.tcpaddr; } // Indicates the browser want the agent to TCP connect to a remote address
if (command.tcpport) { cookieContent.tcpport = command.tcpport; } // Indicates the browser want the agent to TCP connect to a remote port if (command.tcpport) { cookieContent.tcpport = command.tcpport; } // Indicates the browser want the agent to TCP connect to a remote port
if (command.tag == 'novnc') { cookieContent.p = 12; } // If tag is novnc we must encode a protocol for meshrelay logging
if (node.mtype == 3) { cookieContent.lc = 1; command.localRelay = true; } // Indicate this is for a local connection if (node.mtype == 3) { cookieContent.lc = 1; command.localRelay = true; } // Indicate this is for a local connection
command.cookie = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey); command.cookie = parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey);
command.trustedCert = parent.isTrustedCert(domain); command.trustedCert = parent.isTrustedCert(domain);
@ -7487,7 +7559,26 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
} }
function serverUserCommandInfo(cmdData) { function serverUserCommandInfo(cmdData) {
var info = {}; function convertSeconds (s, form) {
if (!['long', 'shortprecise'].includes(form)) {
form = 'shortprecise';
}
let t = {}, r = '';
t.d = Math.floor(s / (24 * 3600));
s %= 24 * 3600;
t.h= Math.floor(s / 3600);
s %= 3600;
t.m = Math.floor(s / 60);
t.s =(s%60).toFixed(0);
if ( form == 'long') {
r = t.d + ((t.d == 1) ? ' day, ' : ' days, ') + t.h + ((t.h == 1) ? ' hour, ' : ' hours, ') + t.m + ((t.m == 1) ? ' minute, ' : ' minutes, ') + t.s+ ((t.s == 1) ? ' second' : ' seconds');
} else if (form == 'shortprecise') {
r = String(t.d).padStart(2, '0') + ':' + String(t.h).padStart(2, '0') + ':' + String(t.m).padStart(2, '0') + ':' + String((s%60).toFixed(2)).padStart(5, '0') + 's';
}
return r;
}
var info = {}, arg = null, t = {}, r = '';
if ((cmdData.cmdargs['_'] != null) && (cmdData.cmdargs['_'][0] != null)) { arg = cmdData.cmdargs['_'][0].toLowerCase(); }
try { info.meshVersion = 'v' + parent.parent.currentVer; } catch (ex) { } try { info.meshVersion = 'v' + parent.parent.currentVer; } catch (ex) { }
try { info.nodeVersion = process.version; } catch (ex) { } try { info.nodeVersion = process.version; } catch (ex) { }
try { info.runMode = (["Hybrid (LAN + WAN) mode", "WAN mode", "LAN mode"][(args.lanonly ? 2 : (args.wanonly ? 1 : 0))]); } catch (ex) { } try { info.runMode = (["Hybrid (LAN + WAN) mode", "WAN mode", "LAN mode"][(args.lanonly ? 2 : (args.wanonly ? 1 : 0))]); } catch (ex) { }
@ -7499,9 +7590,24 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
try { info.platform = process.platform; } catch (ex) { } try { info.platform = process.platform; } catch (ex) { }
try { info.arch = process.arch; } catch (ex) { } try { info.arch = process.arch; } catch (ex) { }
try { info.pid = process.pid; } catch (ex) { } try { info.pid = process.pid; } catch (ex) { }
try { info.uptime = process.uptime(); } catch (ex) { } if (arg == 'h') {
try { info.cpuUsage = process.cpuUsage(); } catch (ex) { } try {
try { info.memoryUsage = process.memoryUsage(); } catch (ex) { } info.uptime = convertSeconds(process.uptime(), 'long');
info.cpuUsage = {
system: (convertSeconds(process.cpuUsage().system /1000000)),
user: (convertSeconds(process.cpuUsage().user /1000000))
}
info.memoryUsage = {};
for (const [key,value] of Object.entries(process.memoryUsage())){
info.memoryUsage[key] = ([value]/1048576).toFixed(2) + 'Mb';
}
} catch (ex) { }
}
else {
try { info.uptime = process.uptime(); } catch (ex) { }
try { info.cpuUsage = process.cpuUsage(); } catch (ex) { }
try { info.memoryUsage = process.memoryUsage(); } catch (ex) { }
}
try { info.warnings = parent.parent.getServerWarnings(); } catch (ex) { console.log(ex); } try { info.warnings = parent.parent.getServerWarnings(); } catch (ex) { console.log(ex); }
try { info.allDevGroupManagers = parent.parent.config.settings.managealldevicegroups; } catch (ex) { } try { info.allDevGroupManagers = parent.parent.config.settings.managealldevicegroups; } catch (ex) { }
try { if (process.traceDeprecation == true) { info.traceDeprecation = true; } } catch (ex) { } try { if (process.traceDeprecation == true) { info.traceDeprecation = true; } } catch (ex) { }
@ -7991,42 +8097,46 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
parent.common.unEscapeAllLinksFieldName(docs); parent.common.unEscapeAllLinksFieldName(docs);
var results = [], resultPendingCount = 0; var results = [], resultPendingCount = 0;
for (i in docs) { if (docs.length == 0) { // no results return blank array
// Check device links, if a link points to an unknown user, remove it. func(docs, type);
parent.cleanDevice(docs[i]); } else {
for (i in docs) {
// Check device links, if a link points to an unknown user, remove it.
parent.cleanDevice(docs[i]);
// Fetch the node from the database // Fetch the node from the database
resultPendingCount++; resultPendingCount++;
const getNodeFunc = function (node, rights, visible) { const getNodeFunc = function (node, rights, visible) {
if ((node != null) && (visible == true)) { if ((node != null) && (visible == true)) {
const getNodeSysInfoFunc = function (err, docs) { const getNodeSysInfoFunc = function (err, docs) {
const getNodeNetInfoFunc = function (err, docs) { const getNodeNetInfoFunc = function (err, docs) {
var netinfo = null; var netinfo = null;
if ((err == null) && (docs != null) && (docs.length == 1)) { netinfo = docs[0]; } if ((err == null) && (docs != null) && (docs.length == 1)) { netinfo = docs[0]; }
resultPendingCount--; resultPendingCount--;
getNodeNetInfoFunc.results.push({ node: parent.CloneSafeNode(getNodeNetInfoFunc.node), sys: getNodeNetInfoFunc.sysinfo, net: netinfo }); getNodeNetInfoFunc.results.push({ node: parent.CloneSafeNode(getNodeNetInfoFunc.node), sys: getNodeNetInfoFunc.sysinfo, net: netinfo });
if (resultPendingCount == 0) { func(getNodeFunc.results, type); } if (resultPendingCount == 0) { func(getNodeFunc.results, type); }
}
getNodeNetInfoFunc.results = getNodeSysInfoFunc.results;
getNodeNetInfoFunc.nodeid = getNodeSysInfoFunc.nodeid;
getNodeNetInfoFunc.node = getNodeSysInfoFunc.node;
if ((err == null) && (docs != null) && (docs.length == 1)) { getNodeNetInfoFunc.sysinfo = docs[0]; }
// Query the database for network information
db.Get('if' + getNodeSysInfoFunc.nodeid, getNodeNetInfoFunc);
} }
getNodeNetInfoFunc.results = getNodeSysInfoFunc.results; getNodeSysInfoFunc.results = getNodeFunc.results;
getNodeNetInfoFunc.nodeid = getNodeSysInfoFunc.nodeid; getNodeSysInfoFunc.nodeid = getNodeFunc.nodeid;
getNodeNetInfoFunc.node = getNodeSysInfoFunc.node; getNodeSysInfoFunc.node = node;
if ((err == null) && (docs != null) && (docs.length == 1)) { getNodeNetInfoFunc.sysinfo = docs[0]; }
// Query the database for network information // Query the database for system information
db.Get('if' + getNodeSysInfoFunc.nodeid, getNodeNetInfoFunc); db.Get('si' + getNodeFunc.nodeid, getNodeSysInfoFunc);
} } else { resultPendingCount--; }
getNodeSysInfoFunc.results = getNodeFunc.results; if (resultPendingCount == 0) { func(getNodeFunc.results.join('\r\n'), type); }
getNodeSysInfoFunc.nodeid = getNodeFunc.nodeid; }
getNodeSysInfoFunc.node = node; getNodeFunc.results = results;
getNodeFunc.nodeid = docs[i]._id;
// Query the database for system information parent.GetNodeWithRights(domain, user, docs[i]._id, getNodeFunc);
db.Get('si' + getNodeFunc.nodeid, getNodeSysInfoFunc);
} else { resultPendingCount--; }
if (resultPendingCount == 0) { func(getNodeFunc.results.join('\r\n'), type); }
} }
getNodeFunc.results = results;
getNodeFunc.nodeid = docs[i]._id;
parent.GetNodeWithRights(domain, user, docs[i]._id, getNodeFunc);
} }
}); });
} else { } else {
@ -8224,11 +8334,13 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
var email2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (domain.mailserver != null)); var email2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (domain.mailserver != null));
var sms2fa = ((parent.parent.smsserver != null) && ((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false))); var sms2fa = ((parent.parent.smsserver != null) && ((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false)));
var msg2fa = ((parent.parent.msgserver != null) && (parent.parent.msgserver.providers != 0) && ((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.msg2factor != false))); var msg2fa = ((parent.parent.msgserver != null) && (parent.parent.msgserver.providers != 0) && ((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.msg2factor != false)));
var duo2fa = ((typeof domain.passwordrequirements != 'object') || (typeof domain.passwordrequirements.duo2factor == 'object'));
var authFactorCount = 0; var authFactorCount = 0;
if (typeof user.otpsecret == 'string') { authFactorCount++; } // Authenticator time factor if (typeof user.otpsecret == 'string') { authFactorCount++; } // Authenticator time factor
if (email2fa && (user.otpekey != null)) { authFactorCount++; } // EMail factor if (email2fa && (user.otpekey != null)) { authFactorCount++; } // EMail factor
if (sms2fa && (user.phone != null)) { authFactorCount++; } // SMS factor if (sms2fa && (user.phone != null)) { authFactorCount++; } // SMS factor
if (msg2fa && (user.msghandle != null)) { authFactorCount++; } // Messaging factor if (msg2fa && (user.msghandle != null)) { authFactorCount++; } // Messaging factor
if (duo2fa && (user.otpduo != null)) { authFactorCount++; } // Duo authentication factor
if (user.otphkeys != null) { authFactorCount += user.otphkeys.length; } // FIDO hardware factor if (user.otphkeys != null) { authFactorCount += user.otphkeys.length; } // FIDO hardware factor
if ((authFactorCount > 0) && (user.otpkeys != null)) { authFactorCount++; } // Backup keys if ((authFactorCount > 0) && (user.otpkeys != null)) { authFactorCount++; } // Backup keys
return authFactorCount; return authFactorCount;

117
monitoring.js Normal file
View file

@ -0,0 +1,117 @@
/**
* @description MeshCentral monitoring module
* @author Simon Smith
* @license Apache-2.0
* @version v0.0.1
*/
"use strict";
module.exports.CreateMonitoring = function (parent, args) {
var obj = {};
obj.args = args;
obj.parent = parent;
obj.express = require('express');
obj.app = obj.express();
obj.prometheus = null;
if (args.compression !== false) { obj.app.use(require('compression')()); }
obj.app.disable('x-powered-by');
obj.counterMetrics = { // Counter Metrics always start at 0 and increase but never decrease
RelayErrors: { description: "Relay Errors" }, // parent.webserver.relaySessionErrorCount
UnknownGroup: { description: "Unknown Group" }, // meshDoesNotExistCount
InvalidPKCSsignature: { description: "Invalid PKCS signature" }, // invalidPkcsSignatureCount
InvalidRSAsignature: { description: "Invalid RSA signature" }, // invalidRsaSignatureCount
InvalidJSON: { description: "Invalid JSON" }, // invalidJsonCount
UnknownAction: { description: "Unknown Action" }, // unknownAgentActionCount
BadWebCertificate: { description: "Bad Web Certificate" }, // agentBadWebCertHashCount
BadSignature: { description: "Bad Signature" }, // (agentBadSignature1Count + agentBadSignature2Count)
MaxSessionsReached: { description: "Max Sessions Reached" }, // agentMaxSessionHoldCount
UnknownDeviceGroup: { description: "Unknown Device Group" }, // (invalidDomainMeshCount + invalidDomainMesh2Count)
InvalidDeviceGroupType: { description: "Invalid Device Group Type" }, // invalidMeshTypeCount
DuplicateAgent: { description: "Duplicate Agent" }, // duplicateAgentCount
blockedUsers: { description: "Blocked Users" }, // blockedUsers
blockedAgents: { description: "Blocked Agents" }, // blockedAgents
};
obj.gaugeMetrics = { // Gauge Metrics always start at 0 and can increase and decrease
ConnectedIntelAMT: { description: "Connected Intel AMT" }, // parent.mpsserver.ciraConnections[i].length
UserAccounts: { description: "User Accounts" }, // Object.keys(parent.webserver.users).length
DeviceGroups: { description: "Device Groups" }, // parent.webserver.meshes (ONLY WHERE deleted=null)
AgentSessions: { description: "Agent Sessions" }, // Object.keys(parent.webserver.wsagents).length
ConnectedUsers: { description: "Connected Users" }, // Object.keys(parent.webserver.wssessions).length
UsersSessions: { description: "Users Sessions" }, // Object.keys(parent.webserver.wssessions2).length
RelaySessions: { description: "Relay Sessions" }, // parent.webserver.relaySessionCount
RelayCount: { description: "Relay Count" } // Object.keys(parent.webserver.wsrelays).length30bb4fb74dfb758d36be52a7
}
obj.collectors = [];
if (parent.config.settings.prometheus != null) { // Create Prometheus Monitoring Endpoint
if ((typeof parent.config.settings.prometheus == 'number') && ((parent.config.settings.prometheus < 1) || (parent.config.settings.prometheus > 65535))) {
console.log('Promethus port number is invalid, Prometheus metrics endpoint has be disabled');
delete parent.config.settings.prometheus;
} else {
const port = ((typeof parent.config.settings.prometheus == 'number') ? parent.config.settings.prometheus : 9464);
obj.prometheus = require('prom-client');
const collectDefaultMetrics = obj.prometheus.collectDefaultMetrics;
collectDefaultMetrics();
for (const key in obj.gaugeMetrics) {
obj.gaugeMetrics[key].prometheus = new obj.prometheus.Gauge({ name: 'meshcentral_' + String(key).toLowerCase(), help: obj.gaugeMetrics[key].description });
}
for (const key in obj.counterMetrics) {
obj.counterMetrics[key].prometheus = new obj.prometheus.Counter({ name: 'meshcentral_' + String(key).toLowerCase(), help: obj.counterMetrics[key].description });
}
obj.app.get('/', function (req, res) { res.send('MeshCentral Prometheus server.'); });
obj.app.listen(port, function () {
console.log('MeshCentral Prometheus server running on port ' + port + '.');
obj.parent.updateServerState('prometheus-port', port);
});
obj.app.get('/metrics', async (req, res) => {
try {
// Count the number of device groups that are not deleted
var activeDeviceGroups = 0;
for (var i in parent.webserver.meshes) { if (parent.webserver.meshes[i].deleted == null) { activeDeviceGroups++; } } // This is not ideal for performance, we want to dome something better.
var gauges = {
UserAccounts: Object.keys(parent.webserver.users).length,
DeviceGroups: activeDeviceGroups,
AgentSessions: Object.keys(parent.webserver.wsagents).length,
ConnectedUsers: Object.keys(parent.webserver.wssessions).length,
UsersSessions: Object.keys(parent.webserver.wssessions2).length,
RelaySessions: parent.webserver.relaySessionCount,
RelayCount: Object.keys(parent.webserver.wsrelays).length,
ConnectedIntelAMT: 0
};
if (parent.mpsserver != null) {
for (var i in parent.mpsserver.ciraConnections) {
gauges.ConnectedIntelAMT += parent.mpsserver.ciraConnections[i].length;
}
}
for (const key in gauges) { obj.gaugeMetrics[key].prometheus.set(gauges[key]); }
// Take a look at agent errors
var agentstats = parent.webserver.getAgentStats();
const counters = {
RelayErrors: parent.webserver.relaySessionErrorCount,
UnknownGroup: agentstats.meshDoesNotExistCount,
InvalidPKCSsignature: agentstats.invalidPkcsSignatureCount,
InvalidRSAsignature: agentstats.invalidRsaSignatureCount,
InvalidJSON: agentstats.invalidJsonCount,
UnknownAction: agentstats.unknownAgentActionCount,
BadWebCertificate: agentstats.agentBadWebCertHashCount,
BadSignature: (agentstats.agentBadSignature1Count + agentstats.agentBadSignature2Count),
MaxSessionsReached: agentstats.agentMaxSessionHoldCount,
UnknownDeviceGroup: (agentstats.invalidDomainMeshCount + agentstats.invalidDomainMesh2Count),
InvalidDeviceGroupType: (agentstats.invalidMeshTypeCount + agentstats.invalidMeshType2Count),
DuplicateAgent: agentstats.duplicateAgentCount,
blockedUsers: parent.webserver.blockedUsers,
blockedAgents: parent.webserver.blockedAgents
};
for (const key in counters) { obj.counterMetrics[key].prometheus.reset(); obj.counterMetrics[key].prometheus.inc(counters[key]); }
res.set('Content-Type', obj.prometheus.register.contentType);
await Promise.all(obj.collectors.map((collector) => (collector(req, res))));
res.end(await obj.prometheus.register.metrics());
} catch (ex) {
console.log(ex);
res.status(500).end();
}
});
}
}
return obj;
}

1541
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{ {
"name": "meshcentral", "name": "meshcentral",
"version": "1.1.34", "version": "1.1.42",
"keywords": [ "keywords": [
"Remote Device Management", "Remote Device Management",
"Remote Device Monitoring", "Remote Device Monitoring",
@ -41,9 +41,9 @@
"archiver": "7.0.1", "archiver": "7.0.1",
"body-parser": "1.20.3", "body-parser": "1.20.3",
"cbor": "5.2.0", "cbor": "5.2.0",
"compression": "1.7.4", "compression": "1.7.5",
"cookie-session": "2.1.0", "cookie-session": "2.1.0",
"express": "4.21.1", "express": "4.21.2",
"express-handlebars": "7.1.3", "express-handlebars": "7.1.3",
"express-ws": "5.0.2", "express-ws": "5.0.2",
"ipcheck": "0.1.0", "ipcheck": "0.1.0",

View file

@ -139,7 +139,7 @@ module.exports.pluginHandler = function (parent) {
try { try {
obj.plugins[p][hookName](...args); obj.plugins[p][hookName](...args);
} catch (e) { } catch (e) {
console.log("Error ocurred while running plugin hook" + p + ':' + hookName + ' (' + e + ')'); console.log("Error occurred while running plugin hook " + p + ':' + hookName, e);
} }
} }
} }
@ -205,7 +205,7 @@ module.exports.pluginHandler = function (parent) {
panel[p].header = obj.plugins[p].on_device_header(); panel[p].header = obj.plugins[p].on_device_header();
panel[p].content = obj.plugins[p].on_device_page(); panel[p].content = obj.plugins[p].on_device_page();
} catch (e) { } catch (e) {
console.log("Error ocurred while getting plugin views " + p + ':' + ' (' + e + ')'); console.log("Error occurred while getting plugin views " + p + ':' + ' (' + e + ')');
} }
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View file

@ -180,6 +180,7 @@
self.prevClipboardText = null; self.prevClipboardText = null;
self.clipboardReadTimer = setInterval(function(){ self.clipboardReadTimer = setInterval(function(){
if(navigator.clipboard.readText != null){ if(navigator.clipboard.readText != null){
if (Mstsc.browser() == 'firefox') return; // this is needed because firefox pops up a PASTE option every second which is annoying
navigator.clipboard.readText() navigator.clipboard.readText()
.then(function(data){ .then(function(data){
if(data != self.prevClipboard){ if(data != self.prevClipboard){

File diff suppressed because one or more lines are too long

View file

@ -155,7 +155,6 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) {
if (Msg[1] == 1) { obj.ProcessCopyRectMsg(Msg[2]); } if (Msg[1] == 1) { obj.ProcessCopyRectMsg(Msg[2]); }
else if (Msg[1] == 2) { obj.Canvas.drawImage(Msg[2], obj.rotX(Msg[3], Msg[4]), obj.rotY(Msg[3], Msg[4])); delete Msg[2]; } else if (Msg[1] == 2) { obj.Canvas.drawImage(Msg[2], obj.rotX(Msg[3], Msg[4]), obj.rotY(Msg[3], Msg[4])); delete Msg[2]; }
obj.PendingOperations.splice(i, 1); obj.PendingOperations.splice(i, 1);
delete Msg;
obj.TilesDrawn++; obj.TilesDrawn++;
if ((obj.TilesDrawn == obj.tilesReceived) && (obj.KillDraw < obj.TilesDrawn)) { obj.KillDraw = obj.TilesDrawn = obj.tilesReceived = 0; } if ((obj.TilesDrawn == obj.tilesReceived) && (obj.KillDraw < obj.TilesDrawn)) { obj.KillDraw = obj.TilesDrawn = obj.tilesReceived = 0; }
return true; return true;
@ -221,12 +220,16 @@ var CreateAgentRemoteDesktop = function (canvasid, scrolldiv) {
if ((cmd == 3) || (cmd == 4) || (cmd == 7)) { X = (view[4] << 8) + view[5]; Y = (view[6] << 8) + view[7]; } if ((cmd == 3) || (cmd == 4) || (cmd == 7)) { X = (view[4] << 8) + view[5]; Y = (view[6] << 8) + view[7]; }
if (obj.debugmode > 2) { console.log('CMD', cmd, cmdsize, X, Y); } if (obj.debugmode > 2) { console.log('CMD', cmd, cmdsize, X, Y); }
// Fix for view being too large for String.fromCharCode.apply()
var chunkSize = 10000;
let result = '';
for (let i = 0; i < view.length; i += chunkSize) { result += String.fromCharCode.apply(null, view.slice(i, i + chunkSize)); }
// Record the command if needed // Record the command if needed
if (obj.recordedData != null) { if (obj.recordedData != null) {
if (cmdsize > 65000) { if (cmdsize > 65000) {
obj.recordedData.push(recordingEntry(2, 1, obj.shortToStr(27) + obj.shortToStr(8) + obj.intToStr(cmdsize) + obj.shortToStr(cmd) + obj.shortToStr(0) + obj.shortToStr(0) + obj.shortToStr(0) + String.fromCharCode.apply(null, view))); obj.recordedData.push(recordingEntry(2, 1, obj.shortToStr(27) + obj.shortToStr(8) + obj.intToStr(cmdsize) + obj.shortToStr(cmd) + obj.shortToStr(0) + obj.shortToStr(0) + obj.shortToStr(0) + result));
} else { } else {
obj.recordedData.push(recordingEntry(2, 1, String.fromCharCode.apply(null, view))); obj.recordedData.push(recordingEntry(2, 1, result));
} }
} }

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -17,6 +17,7 @@ function QV(x, y) { try { QS(x).display = (y ? '' : 'none'); } catch (x) { } }
function QA(x, y) { Q(x).innerHTML += y; } // "Q" append function QA(x, y) { Q(x).innerHTML += y; } // "Q" append
function QH(x, y) { Q(x).innerHTML = y; } // "Q" html function QH(x, y) { Q(x).innerHTML = y; } // "Q" html
function QC(x) { try { return Q(x).classList; } catch (x) { } } // "Q" class function QC(x) { try { return Q(x).classList; } catch (x) { } } // "Q" class
function QVH(x, y) { try { y ? Q(x).classList.remove('visually-hidden') : Q(x).classList.add('visually-hidden'); } catch (x) { } } // "Q" visibility
// Move cursor to end of input box // Move cursor to end of input box
function inputBoxFocus(x) { Q(x).focus(); var v = Q(x).value; Q(x).value = ''; Q(x).value = v; } function inputBoxFocus(x) { Q(x).focus(); var v = Q(x).value; Q(x).value = ''; Q(x).value = v; }

File diff suppressed because one or more lines are too long

View file

@ -1,29 +1,21 @@
document.addEventListener('DOMContentLoaded', function () { document.addEventListener("DOMContentLoaded", function () {
const themeStylesheet = document.getElementById("theme-stylesheet");
const themeSwitcher = document.getElementById('theme-switcher');
const themeStylesheet = document.getElementById('theme-stylesheet');
// Load saved theme from local storage // Load saved theme from local storage
const savedTheme = localStorage.getItem('theme'); const savedTheme = localStorage.getItem("theme");
if (savedTheme) { if (savedTheme) {
const safeTheme = encodeURIComponent(savedTheme); const safeTheme = ((savedTheme != 'default') ? encodeURIComponent(savedTheme) : encodeURIComponent('..'));
themeStylesheet.href = `styles/themes/${safeTheme}/bootstrap.min.css`; themeStylesheet.href = `styles/themes/${safeTheme}/bootstrap-min.css`;
themeSwitcher.value = savedTheme;
} }
// Change theme on selection
themeSwitcher.addEventListener('change', function () {
const selectedTheme = themeSwitcher.value;
const safeTheme = encodeURIComponent(selectedTheme);
themeStylesheet.href = `styles/themes/${safeTheme}/bootstrap.min.css`;
// Save selected theme to local storage
localStorage.setItem('theme', selectedTheme);
});
// Initialize Select2 on all select elements with the 'select2' class // Initialize Select2 on all select elements with the 'select2' class
$('.select2').select2({ $(".select2").select2({
theme: 'bootstrap-5', theme: "bootstrap-5",
width: $( this ).data( 'width' ) ? $( this ).data( 'width' ) : $( this ).hasClass( 'w-100' ) ? '100%' : 'style', width: $(this).data("width")
placeholder: $( this ).data( 'placeholder' ), ? $(this).data("width")
: $(this).hasClass("w-100")
? "100%"
: "style",
placeholder: $(this).data("placeholder"),
}); });
}); });

View file

@ -1 +1 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(window,function(){return r=[function(e,t,r){function n(){}Object.defineProperty(t,"__esModule",{value:!0}),n.prototype.activate=function(e){this._terminal=e},n.prototype.dispose=function(){},n.prototype.fit=function(){var e,t=this.proposeDimensions();t&&this._terminal&&(e=this._terminal._core,this._terminal.rows===t.rows&&this._terminal.cols===t.cols||(e._renderService.clear(),this._terminal.resize(t.cols,t.rows)))},n.prototype.proposeDimensions=function(){var e,t,r,n;if(this._terminal&&this._terminal.element&&this._terminal.element.parentElement)return e=this._terminal._core,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),n=Math.max(0,parseInt(n.getPropertyValue("width"))),t=window.getComputedStyle(this._terminal.element),r=r-(parseInt(t.getPropertyValue("padding-top"))+parseInt(t.getPropertyValue("padding-bottom"))),n=n-(parseInt(t.getPropertyValue("padding-right"))+parseInt(t.getPropertyValue("padding-left")))-e.viewport.scrollBarWidth,{cols:Math.max(2,Math.floor(n/e._renderService.dimensions.actualCellWidth)),rows:Math.max(1,Math.floor(r/e._renderService.dimensions.actualCellHeight))}},t.FitAddon=n}],n={},o.m=r,o.c=n,o.d=function(e,t,r){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(t,e){if(1&e&&(t=o(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(o.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)o.d(r,n,function(e){return t[e]}.bind(null,n));return r},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=0);function o(e){var t;return(n[e]||(t=n[e]={i:e,l:!1,exports:{}},r[e].call(t.exports,t,t.exports,o),t.l=!0,t)).exports}var r,n}) ((e,t)=>{"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()})(window,function(){return r=[function(e,t,r){function n(){}Object.defineProperty(t,"__esModule",{value:!0}),n.prototype.activate=function(e){this._terminal=e},n.prototype.dispose=function(){},n.prototype.fit=function(){var e,t=this.proposeDimensions();t&&this._terminal&&(e=this._terminal._core,this._terminal.rows===t.rows&&this._terminal.cols===t.cols||(e._renderService.clear(),this._terminal.resize(t.cols,t.rows)))},n.prototype.proposeDimensions=function(){var e,t,r,n;if(this._terminal&&this._terminal.element&&this._terminal.element.parentElement)return e=this._terminal._core,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue("height")),n=Math.max(0,parseInt(n.getPropertyValue("width"))),t=window.getComputedStyle(this._terminal.element),r=r-(parseInt(t.getPropertyValue("padding-top"))+parseInt(t.getPropertyValue("padding-bottom"))),n=n-(parseInt(t.getPropertyValue("padding-right"))+parseInt(t.getPropertyValue("padding-left")))-e.viewport.scrollBarWidth,{cols:Math.max(2,Math.floor(n/e._renderService.dimensions.actualCellWidth)),rows:Math.max(1,Math.floor(r/e._renderService.dimensions.actualCellHeight))}},t.FitAddon=n}],n={},o.m=r,o.c=n,o.d=function(e,t,r){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(t,e){if(1&e&&(t=o(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(o.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var n in t)o.d(r,n,function(e){return t[e]}.bind(null,n));return r},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=0);function o(e){var t;return(n[e]||(t=n[e]={i:e,l:!1,exports:{}},r[e].call(t.exports,t,t.exports,o),t.l=!0,t)).exports}var r,n})

File diff suppressed because one or more lines are too long

View file

@ -1 +1 @@
"undefined"==typeof ZLIB&&alert("ZLIB is not defined. SRC zlib.js before zlib-adler32.js"),function(){var b=65521,v=5552;ZLIB.adler32=function(r,e,o,t){if("string"==typeof e){var a,d=r,c=e,C=o,h=t,A=d>>>16&65535;if(d&=65535,1==h)d+=255&c.charCodeAt(C),b<=d&&(d-=b),b<=(A+=d)&&(A-=b);else{if(null===c)return 1;if(h<16){for(;h--;)A+=d+=255&c.charCodeAt(C++);return b<=d&&(d-=b),d|(A%=b)<<16}for(;v<=h;){for(h-=v,a=347;A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A+=d+=255&c.charCodeAt(C++))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)),--a;);d%=b,A%=b}if(h){for(;16<=h;)h-=16,A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A+=d+=255&c.charCodeAt(C++))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++));for(;h--;)A+=d+=255&c.charCodeAt(C++);d%=b,A%=b}}return d|A<<16}var f,n=r,i=e,u=o,l=t,s=n>>>16&65535;if(n&=65535,1==l)n+=i[u],b<=n&&(n-=b),b<=(s+=n)&&(s-=b);else{if(null===i)return 1;if(l<16){for(;l--;)s+=n+=i[u++];return b<=n&&(n-=b),n|(s%=b)<<16}for(;v<=l;){for(l-=v,f=347;s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s+=n+=i[u++])+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]),--f;);n%=b,s%=b}if(l){for(;16<=l;)l-=16,s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s+=n+=i[u++])+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]))+(n+=i[u++]);for(;l--;)s+=n+=i[u++];n%=b,s%=b}}return n|s<<16},ZLIB.adler32_combine=function(r,e,o){var t,a;return o<0?4294967295:(a=(o%=b)*(t=65535&r),b<=(t+=(65535&e)+b-1)&&(t-=b),b<=t&&(t-=b),b<<1<=(a=a%b+((r>>16&65535)+(e>>16&65535)+b-o))&&(a-=b<<1),b<=a&&(a-=b),t|a<<16)}}() "undefined"==typeof ZLIB&&alert("ZLIB is not defined. SRC zlib.js before zlib-adler32.js"),(()=>{var b=65521,v=5552;ZLIB.adler32=function(r,e,o,t){if("string"==typeof e){var a,d=r,c=e,C=o,h=t,A=d>>>16&65535;if(d&=65535,1==h)d+=255&c.charCodeAt(C),b<=d&&(d-=b),b<=(A+=d)&&(A-=b);else{if(null===c)return 1;if(h<16){for(;h--;)A+=d+=255&c.charCodeAt(C++);return b<=d&&(d-=b),d|(A%=b)<<16}for(;v<=h;){for(h-=v,a=347;A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A+=d+=255&c.charCodeAt(C++))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)),--a;);d%=b,A%=b}if(h){for(;16<=h;)h-=16,A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A=(A+=d+=255&c.charCodeAt(C++))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++)))+(d+=255&c.charCodeAt(C++));for(;h--;)A+=d+=255&c.charCodeAt(C++);d%=b,A%=b}}return d|A<<16}var f,n=r,i=e,l=o,u=t,s=n>>>16&65535;if(n&=65535,1==u)n+=i[l],b<=n&&(n-=b),b<=(s+=n)&&(s-=b);else{if(null===i)return 1;if(u<16){for(;u--;)s+=n+=i[l++];return b<=n&&(n-=b),n|(s%=b)<<16}for(;v<=u;){for(u-=v,f=347;s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s+=n+=i[l++])+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]),--f;);n%=b,s%=b}if(u){for(;16<=u;)u-=16,s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s=(s+=n+=i[l++])+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]))+(n+=i[l++]);for(;u--;)s+=n+=i[l++];n%=b,s%=b}}return n|s<<16},ZLIB.adler32_combine=function(r,e,o){var t,a;return o<0?4294967295:(a=(o%=b)*(t=65535&r),b<=(t+=(65535&e)+b-1)&&(t-=b),b<=t&&(t-=b),b<<1<=(a=a%b+((r>>16&65535)+(e>>16&65535)+b-o))&&(a-=b<<1),b<=a&&(a-=b),t|a<<16)}})()

View file

@ -1 +1 @@
"undefined"==typeof ZLIB&&alert("ZLIB is not defined. SRC zlib.js before zlib-crc32.js"),function(){var C=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];ZLIB.crc32=function(r,e,o,n){if("string"==typeof e){var t=r,f=e,c=o,a=n;if(null==f)return 0;for(t^=4294967295;8<=a;)t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,a-=8;if(a)for(;t=C[255&(t^f.charCodeAt(c++))]^t>>>8,--a;);return 4294967295^t}var i=r,u=e,d=o,A=n;if(null==u)return 0;for(i^=4294967295;8<=A;)i=C[255&(i^u[d++])]^i>>>8,i=C[255&(i^u[d++])]^i>>>8,i=C[255&(i^u[d++])]^i>>>8,i=C[255&(i^u[d++])]^i>>>8,i=C[255&(i^u[d++])]^i>>>8,i=C[255&(i^u[d++])]^i>>>8,i=C[255&(i^u[d++])]^i>>>8,i=C[255&(i^u[d++])]^i>>>8,A-=8;if(A)for(;i=C[255&(i^u[d++])]^i>>>8,--A;);return 4294967295^i};function a(r,e){for(var o=0,n=0;e;)1&e&&(n^=r[o]),e>>=1,o++;return n}function i(r,e){for(var o=0;o<32;o++)r[o]=a(e,e[o])}ZLIB.crc32_combine=function(r,e,o){var n,t,f,c;if(!(o<=0)){for(f=new Array(32),(c=new Array(32))[0]=3988292384,n=t=1;n<32;n++)c[n]=t,t<<=1;for(i(f,c),i(c,f);i(f,c),1&o&&(r=a(f,r)),0!=(o>>=1)&&(i(c,f),1&o&&(r=a(c,r)),0!=(o>>=1)););r^=e}return r}}() "undefined"==typeof ZLIB&&alert("ZLIB is not defined. SRC zlib.js before zlib-crc32.js"),(()=>{var C=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];function a(r,e){for(var o=0,n=0;e;)1&e&&(n^=r[o]),e>>=1,o++;return n}function i(r,e){for(var o=0;o<32;o++)r[o]=a(e,e[o])}ZLIB.crc32=function(r,e,o,n){if("string"==typeof e){var t=r,f=e,c=o,a=n;if(null==f)return 0;for(t^=4294967295;8<=a;)t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,t=C[255&(t^f.charCodeAt(c++))]^t>>>8,a-=8;if(a)for(;t=C[255&(t^f.charCodeAt(c++))]^t>>>8,--a;);return 4294967295^t}var i=r,d=e,u=o,A=n;if(null==d)return 0;for(i^=4294967295;8<=A;)i=C[255&(i^d[u++])]^i>>>8,i=C[255&(i^d[u++])]^i>>>8,i=C[255&(i^d[u++])]^i>>>8,i=C[255&(i^d[u++])]^i>>>8,i=C[255&(i^d[u++])]^i>>>8,i=C[255&(i^d[u++])]^i>>>8,i=C[255&(i^d[u++])]^i>>>8,i=C[255&(i^d[u++])]^i>>>8,A-=8;if(A)for(;i=C[255&(i^d[u++])]^i>>>8,--A;);return 4294967295^i},ZLIB.crc32_combine=function(r,e,o){var n,t,f,c;if(!(o<=0)){for(f=new Array(32),(c=new Array(32))[0]=3988292384,n=t=1;n<32;n++)c[n]=t,t<<=1;for(i(f,c),i(c,f);i(f,c),1&o&&(r=a(f,r)),0!=(o>>=1)&&(i(c,f),1&o&&(r=a(c,r)),0!=(o>>=1)););r^=e}return r}})()

File diff suppressed because one or more lines are too long

View file

@ -168,7 +168,6 @@ body {
height: 66px; height: 66px;
color: #c8c8c8; color: #c8c8c8;
padding-left: 14px; padding-left: 14px;
padding-top: 7px;
font-size: 46px; font-size: 46px;
font-family: Arial,Helvetica,sans-serif; font-family: Arial,Helvetica,sans-serif;
font-weight: bold; font-weight: bold;
@ -180,7 +179,7 @@ body {
height: 66px; height: 66px;
color: #c8c8c8; color: #c8c8c8;
padding-left: 5px; padding-left: 5px;
padding-top: 14px; padding-top: 12px;
font-size: 14px; font-size: 14px;
font-family: Arial,Helvetica,sans-serif; font-family: Arial,Helvetica,sans-serif;
font-weight: bold; font-weight: bold;
@ -248,7 +247,6 @@ body {
} }
.nonenglish .topbar_td { .nonenglish .topbar_td {
width: 10px;
height: 24px; height: 24px;
cursor: pointer; cursor: pointer;
padding-left:16px; padding-left:16px;
@ -268,6 +266,16 @@ body {
right: 3px; right: 3px;
} }
.textnewui {
color: white;
font-weight: bold;
padding-top: 5px;
cursor: pointer;
position: absolute;
right: 0;
margin-right: 10px;
}
.LogoffLinkColor { .LogoffLinkColor {
color:white; color:white;
} }
@ -295,8 +303,8 @@ body {
#MainSubMenuSpan, #MeshSubMenuSpan, #EventsSubMenuSpan, #UserSubMenuSpan, #UsersSubMenuSpan, #ServerSubMenuSpan, #MainMenuSpan, #MainSubMenu, #MeshSubMenu, #UserSubMenu, #ServerSubMenu, #UserDummyMenu, #PluginSubMenu { #MainSubMenuSpan, #MeshSubMenuSpan, #EventsSubMenuSpan, #UserSubMenuSpan, #UsersSubMenuSpan, #ServerSubMenuSpan, #MainMenuSpan, #MainSubMenu, #MeshSubMenu, #UserSubMenu, #ServerSubMenu, #UserDummyMenu, #PluginSubMenu {
width: 100%; width: 100%;
height: 24px; height: 24px;
color: var(--sub-menu-color); color: var(--bs-secondary-color);
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
} }
.menu_stack #UserDummyMenu { .menu_stack #UserDummyMenu {
@ -695,6 +703,10 @@ body {
text-align: center; text-align: center;
} }
.DeviceCheckbox {
margin-top: 2px !important;
}
.deviceBarCheckbox { .deviceBarCheckbox {
width:22px; width:22px;
float:left; float:left;
@ -730,25 +742,21 @@ body {
#devListToolbarSpan { #devListToolbarSpan {
width: 100%; width: 100%;
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
color: var(--bs-secondary-color);
vertical-align: middle; vertical-align: middle;
border-spacing: 0; border-spacing: 0;
} }
.night #devListToolbarSpan { #SearchInput, #KvmSearchInput {
color: black;
background-color: #d3d9d6;
}
#SearchInput {
width: 120px; width: 120px;
} }
#SearchInput.search { #SearchInput.search, #KvmSearchInput.search {
background-color: #FDFFBE; background-color: #FDFFBE;
} }
.night #SearchInput.search { .night #SearchInput.search, .night #KvmSearchInput.search {
background-color: grey; background-color: grey;
} }
@ -819,15 +827,15 @@ NoMeshesPanel img {
.deviceNotifySmallDot { .deviceNotifySmallDot {
position:absolute; position:absolute;
right:10px; right:10px;
top:0px; top:4px;
height:10px; height:10px;
} }
.deviceNotifySmallDotSub { .deviceNotifySmallDotSub {
text-align:center; text-align:center;
color:#FFF; color:#FFF;
height:10px; height:14px;
width:10px; width:14px;
padding:2px; padding:2px;
background-color:#00F; background-color:#00F;
border-radius:10px; border-radius:10px;
@ -1078,11 +1086,6 @@ NoMeshesPanel img {
.pTable { .pTable {
width: 100%; width: 100%;
height: 24px;
background: var(--sub-menu-bg) !important;
margin-bottom: 4px;
vertical-align: middle;
border-spacing: 0;
} }
#p50groups { #p50groups {
@ -1126,24 +1129,15 @@ NoMeshesPanel img {
#p5filehead { #p5filehead {
width: 100%; width: 100%;
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
text-align: left; padding: 4px 0px;
padding: 4px;
}
.night #p5filehead {
background: var(--sub-menu-bg);
} }
#p5filesubhead { #p5filesubhead {
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
height: 28px; height: 28px;
} }
.night #p5filesubhead {
background-color: #222;
}
#p5rightOfButtons { #p5rightOfButtons {
float: right; float: right;
margin-top: 3px; margin-top: 3px;
@ -1744,14 +1738,14 @@ nav .lbbuttonsel2 {
.style3 { .style3 {
text-align: center; text-align: center;
color: white; color: white;
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
font-weight: bold; font-weight: bold;
} }
.style3x { .style3x {
text-align: center; text-align: center;
color: var(--sub-menu-color); color: var(--bs-secondary-color);
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
font-weight: bold; font-weight: bold;
} }
@ -1832,34 +1826,21 @@ nav .lbbuttonsel2 {
.style14 { .style14 {
height: 100%; height: 100%;
text-align: left; text-align: left;
/* background-color: #D3D9D6; */ background: var(--bs-secondary-bg);
background: var(--sub-menu-bg);
} }
.night .style14 { .night .style14 {
background-color: #333;
color: #CCC; color: #CCC;
} }
.auto-style1 { .auto-style1 {
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
text-align: right;
}
#pTable .auto-style1 {
height: 100%;
float: right;
} }
.night .auto-style1 { .night .auto-style1 {
background: var(--sub-menu-bg);
color: #CCC; color: #CCC;
} }
.night #pTable {
color: black;
}
.icon2 { .icon2 {
float: left; float: left;
margin: 7px; margin: 7px;
@ -2102,7 +2083,11 @@ nav .lbbuttonsel2 {
#d2devNotes, #d2devNotes,
#d2devEvent, #d2devEvent,
#d2runcmd, #d2runcmd,
#d2devMessage { #d2devMessage,
#d2smsText,
#d2emailSubject,
#d2emailText,
#broadcastMessage {
background-color: #FFF9D3; background-color: #FFF9D3;
} }
@ -2112,7 +2097,11 @@ nav .lbbuttonsel2 {
.night #d2devNotes, .night #d2devNotes,
.night #d2devEvent, .night #d2devEvent,
.night #d2runcmd, .night #d2runcmd,
.night #d2devMessage { .night #d2devMessage,
.night #d2smsText,
.night #d2emailSubject,
.night #d2emailText,
.night #broadcastMessage {
background-color: black; background-color: black;
} }
@ -2689,10 +2678,6 @@ nav .lbbuttonsel2 {
-ms-grid-row: 4; -ms-grid-row: 4;
} }
#DeskClip, #DeskControlSpan, #specialkeylist {
padding-left: 6px;
}
.serverStateTableCell { .serverStateTableCell {
width: 300px; width: 300px;
height: 24px; height: 24px;
@ -2750,23 +2735,16 @@ nav .lbbuttonsel2 {
#p13toolbar .areaHead2 { #p13toolbar .areaHead2 {
width: 100%; width: 100%;
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
text-align: left; padding: 4px 0px;
padding: 4px;
} }
.night #p13toolbar .areaHead2 {
background: var(--sub-menu-bg);
}
#p13toolbar .areaHead3 { #p13toolbar .areaHead3 {
background: var(--sub-menu-bg); background: var(--bs-secondary-bg);
height: 28px; height: 28px;
} }
.night #p13toolbar .areaHead3 {
background-color: #333;
}
#p13filetable { #p13filetable {
width: 100%; width: 100%;
@ -2816,11 +2794,6 @@ nav .lbbuttonsel2 {
color: black; color: black;
} }
#p15statetext {
padding: 4px;
height: 15px;
}
#p15agentConsole { #p15agentConsole {
background: black; background: black;
margin: 0; margin: 0;
@ -2837,11 +2810,6 @@ nav .lbbuttonsel2 {
max-height: calc(100vh - 305px); max-height: calc(100vh - 305px);
} }
#p15coreName {
padding: 4px;
display: inline-block;
}
#p15agentConsoleText { #p15agentConsoleText {
margin: 0; margin: 0;
padding: 0; padding: 0;
@ -2923,7 +2891,7 @@ nav .lbbuttonsel2 {
width: 28px; width: 28px;
} }
.viewSelector3 { .viewSelector3, .uiSelector7 {
margin-left: 2px; margin-left: 2px;
margin-top: 2px; margin-top: 2px;
background: url(../images/views.png) -56px 0px; background: url(../images/views.png) -56px 0px;
@ -3023,6 +2991,13 @@ nav .lbbuttonsel2 {
background-color: #AAA; background-color: #AAA;
} }
.uiSelector_end {
width: 32px;
height: 32px;
float: left;
margin: 3px;
}
.uiSelectorSel { .uiSelectorSel {
background-color: #BBB; background-color: #BBB;
opacity: 0.8; opacity: 0.8;

View file

@ -263,6 +263,16 @@ body {
right: 3px; right: 3px;
} }
.textnewui {
color: white;
font-weight: bold;
padding-top: 5px;
cursor: pointer;
position: absolute;
right: 0;
margin-right: 10px;
}
.LogoffLinkColor { .LogoffLinkColor {
color:white; color:white;
} }
@ -2896,7 +2906,7 @@ a {
width: 28px; width: 28px;
} }
.viewSelector3 { .viewSelector3, .uiSelector7 {
margin-left: 2px; margin-left: 2px;
margin-top: 2px; margin-top: 2px;
background: url(../images/views.png) -56px 0px; background: url(../images/views.png) -56px 0px;
@ -2996,6 +3006,13 @@ a {
background-color: #AAA; background-color: #AAA;
} }
.uiSelector_end {
width: 32px;
height: 32px;
float: left;
margin: 3px;
}
.uiSelectorSel { .uiSelectorSel {
background-color: #BBB; background-color: #BBB;
opacity: 0.8; opacity: 0.8;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -186,6 +186,7 @@
"domains": { "domains": {
"": { "": {
"_siteStyle": 2, "_siteStyle": 2,
"_showModernUIToggle": true,
"title": "MyServer", "title": "MyServer",
"title2": "Servername", "title2": "Servername",
"_titlePicture": "title-sample.png", "_titlePicture": "title-sample.png",
@ -322,7 +323,8 @@
"skip2factor": "127.0.0.1,192.168.2.0/24", "skip2factor": "127.0.0.1,192.168.2.0/24",
"oldPasswordBan": 5, "oldPasswordBan": 5,
"banCommonPasswords": false, "banCommonPasswords": false,
"twoFactorTimeout": 300 "twoFactorTimeout": 300,
"duo2factor": true
}, },
"_twoFactorCookieDurationDays": 30, "_twoFactorCookieDurationDays": 30,
"_agentInviteCodes": true, "_agentInviteCodes": true,
@ -341,6 +343,7 @@
"files": "{0} requesting remote files access. Grant access?", "files": "{0} requesting remote files access. Grant access?",
"consentTimeout": 30, "consentTimeout": 30,
"autoAcceptOnTimeout": false, "autoAcceptOnTimeout": false,
"autoAcceptIfNoUser": false,
"oldStyle": true "oldStyle": true
}, },
"_notificationMessages": { "_notificationMessages": {
@ -383,6 +386,8 @@
"_agentBlockedIP": "127.0.0.1,::1", "_agentBlockedIP": "127.0.0.1,::1",
"___userSessionIdleTimeout__": "Number of user idle minutes before auto-disconnect", "___userSessionIdleTimeout__": "Number of user idle minutes before auto-disconnect",
"_userSessionIdleTimeout": 30, "_userSessionIdleTimeout": 30,
"___logoutOnIdleSessionTimeout": "Determines whether MeshCentral should logout after the session idle timeout elapsed or should just disconnect remote desktop, terminal and files.",
"_logoutOnIdleSessionTimeout": false,
"userConsentFlags": { "userConsentFlags": {
"desktopnotify": true, "desktopnotify": true,
"terminalnotify": true, "terminalnotify": true,
@ -454,6 +459,11 @@
"_redirects": { "_redirects": {
"meshcommander": "https://www.meshcommander.com/" "meshcommander": "https://www.meshcommander.com/"
}, },
"_duo2factor": {
"integrationkey": "mykey",
"secretkey": "mysecret",
"apihostname": "api-xxxxxxxxxxx.duosecurity.com"
},
"_yubikey": { "_yubikey": {
"id": "0000", "id": "0000",
"secret": "xxxxxxxxxxxxxxxxxxxxx", "secret": "xxxxxxxxxxxxxxxxxxxxx",

View file

@ -22,6 +22,7 @@ var meshCentralSourceFiles = [
"../views/agentinvite.handlebars", "../views/agentinvite.handlebars",
"../views/invite.handlebars", "../views/invite.handlebars",
"../views/default.handlebars", "../views/default.handlebars",
"../views/default3.handlebars",
"../views/default-mobile.handlebars", "../views/default-mobile.handlebars",
"../views/download.handlebars", "../views/download.handlebars",
"../views/download2.handlebars", "../views/download2.handlebars",
@ -38,6 +39,7 @@ var meshCentralSourceFiles = [
"../views/messenger.handlebars", "../views/messenger.handlebars",
"../views/player.handlebars", "../views/player.handlebars",
"../views/sharing.handlebars", "../views/sharing.handlebars",
"../views/sharing-mobile.handlebars",
"../views/mstsc.handlebars", "../views/mstsc.handlebars",
"../views/ssh.handlebars", "../views/ssh.handlebars",
"../emails/account-check.html", "../emails/account-check.html",
@ -63,6 +65,7 @@ var minifyMeshCentralSourceFiles = [
"../views/agentinvite.handlebars", "../views/agentinvite.handlebars",
"../views/invite.handlebars", "../views/invite.handlebars",
"../views/default.handlebars", "../views/default.handlebars",
"../views/default3.handlebars",
"../views/default-mobile.handlebars", "../views/default-mobile.handlebars",
"../views/download.handlebars", "../views/download.handlebars",
"../views/download2.handlebars", "../views/download2.handlebars",
@ -451,7 +454,8 @@ function startEx(argv) {
removeScriptTypeAttributes: true, removeScriptTypeAttributes: true,
removeTagWhitespace: true, removeTagWhitespace: true,
preserveLineBreaks: false, preserveLineBreaks: false,
useShortDoctype: true useShortDoctype: true,
log: function(a) { if (typeof a !== 'string') { console.log(a); } } // Log errors from UglifyJS to console output
}); });
} catch (ex) { } catch (ex) {
console.log(ex); console.log(ex);
@ -782,10 +786,12 @@ function getStringsHtml(name, node) {
// Check if the "value" attribute exists and needs to be translated // Check if the "value" attribute exists and needs to be translated
var subnodeignore = false; var subnodeignore = false;
var subnodevalueignore = false;
if ((subnode.attributes != null) && (subnode.attributes.length > 0)) { if ((subnode.attributes != null) && (subnode.attributes.length > 0)) {
var subnodevalue = null, subnodeplaceholder = null, subnodetitle = null; var subnodevalue = null, subnodeplaceholder = null, subnodetitle = null;
for (var j in subnode.attributes) { for (var j in subnode.attributes) {
if ((subnode.attributes[j].name == 'notrans') && (subnode.attributes[j].value == '1')) { subnodeignore = true; } if ((subnode.attributes[j].name == 'notrans') && (subnode.attributes[j].value == '1')) { subnodeignore = true; }
if ((subnode.attributes[j].name == 'notransval') && (subnode.attributes[j].value == '1')) { subnodevalueignore = true; }
if ((subnode.attributes[j].name == 'type') && (subnode.attributes[j].value == 'hidden')) { subnodeignore = true; } if ((subnode.attributes[j].name == 'type') && (subnode.attributes[j].value == 'hidden')) { subnodeignore = true; }
if (subnode.attributes[j].name == 'value') { subnodevalue = subnode.attributes[j].value; } if (subnode.attributes[j].name == 'value') { subnodevalue = subnode.attributes[j].value; }
if (subnode.attributes[j].name == 'placeholder') { subnodeplaceholder = subnode.attributes[j].value; } if (subnode.attributes[j].name == 'placeholder') { subnodeplaceholder = subnode.attributes[j].value; }
@ -794,7 +800,7 @@ function getStringsHtml(name, node) {
if ((subnodevalue != null) && isNumber(subnodevalue) == true) { subnodevalue = null; } if ((subnodevalue != null) && isNumber(subnodevalue) == true) { subnodevalue = null; }
if ((subnodeplaceholder != null) && isNumber(subnodeplaceholder) == true) { subnodeplaceholder = null; } if ((subnodeplaceholder != null) && isNumber(subnodeplaceholder) == true) { subnodeplaceholder = null; }
if ((subnodetitle != null) && isNumber(subnodetitle) == true) { subnodetitle = null; } if ((subnodetitle != null) && isNumber(subnodetitle) == true) { subnodetitle = null; }
if ((subnodeignore == false) && (subnodevalue != null)) { if ((subnodeignore == false) && (subnodevalueignore == false) && (subnodevalue != null)) {
// Add a new string to the list (value) // Add a new string to the list (value)
if (sourceStrings[subnodevalue] == null) { sourceStrings[subnodevalue] = { en: subnodevalue, xloc: [name] }; } else { if (sourceStrings[subnodevalue].xloc == null) { sourceStrings[subnodevalue].xloc = []; } sourceStrings[subnodevalue].xloc.push(name); } if (sourceStrings[subnodevalue] == null) { sourceStrings[subnodevalue] = { en: subnodevalue, xloc: [name] }; } else { if (sourceStrings[subnodevalue].xloc == null) { sourceStrings[subnodevalue].xloc = []; } sourceStrings[subnodevalue].xloc.push(name); }
} }

File diff suppressed because it is too large Load diff

View file

@ -1304,6 +1304,7 @@
delete urlargs.viewmode; delete urlargs.viewmode;
delete urlargs.gotonode; delete urlargs.gotonode;
delete urlargs.gotodevicename; delete urlargs.gotodevicename;
delete urlargs.gotodeviceip;
delete urlargs.gotomesh; delete urlargs.gotomesh;
delete urlargs.panel; delete urlargs.panel;
@ -1324,7 +1325,7 @@
var logoutControls = JSON.parse(decodeURIComponent('{{{logoutControls}}}')); var logoutControls = JSON.parse(decodeURIComponent('{{{logoutControls}}}'));
var authCookieRenewTimer = null; var authCookieRenewTimer = null;
var webRelayPort = parseInt('{{{webRelayPort}}}'); var webRelayPort = parseInt('{{{webRelayPort}}}');
var hidePowerTimeline = {{{hidePowerTimeline}}}; var hidePowerTimeline = '{{{hidePowerTimeline}}}';
var webRelayDns = '{{{webRelayDns}}}'; var webRelayDns = '{{{webRelayDns}}}';
var meshserver = null; var meshserver = null;
var xdr = null; var xdr = null;
@ -1521,7 +1522,26 @@
} }
function setSessionActivity() { sessionActivity = Date.now(); } function setSessionActivity() { sessionActivity = Date.now(); }
function checkIdleSessionTimeout() { var delta = (Date.now() - sessionActivity); if (delta > serverinfo.timeout) { window.location.href = 'logout'; } } function checkIdleSessionTimeout() {
var delta = (Date.now() - sessionActivity);
if (delta > serverinfo.timeout) {
if (desktop != null) { // Disconnect remote desktop
desktop.Stop();
desktopNode = desktop = null;
}
if (terminal != null) { // Disconnect terminal
terminal.Stop();
terminal = null;
}
if (files != null) { // Disconnect files
files.Stop();
files = null;
}
if (serverinfo.logoutonidlesessiontimeout) {
window.location.href = 'logout';
}
}
}
function onMessage(server, message) { function onMessage(server, message) {
switch (message.action) { switch (message.action) {
@ -1743,7 +1763,7 @@
var secret = message.secret; var secret = message.secret;
if (secret.length == 52) { secret = secret.split(/(.............)/).filter(Boolean).join(' '); } if (secret.length == 52) { secret = secret.split(/(.............)/).filter(Boolean).join(' '); }
else if (secret.length == 32) { secret = secret.split(/(....)/).filter(Boolean).join(' '); secret = secret.substring(0, 20) + '<br/>' + secret.substring(20) } else if (secret.length == 32) { secret = secret.split(/(....)/).filter(Boolean).join(' '); secret = secret.substring(0, 20) + '<br/>' + secret.substring(20) }
QH('d2optinfo', format("Install <a href=\"https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2\" rel=\"noreferrer noopener\" target=_blank>Google Authenticator</a> or a compatible application, use <a href=\"{0}\" rel=\"noreferrer noopener\" target=_blank> this link</a> or enter the secret below. Then, enter the current 6 digit token to activate 2-Step login.", message.url) + '<br /><br /><div style=width:100%;text-align:center><tt id=d2optsecret secret="' + message.secret + '" style=font-size:15px>' + secret + '</tt><br /><br />Token: <input type=text autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]*" onkeypress=\"return (event.keyCode == 8) || (event.charCode >= 48 && event.charCode <= 57)\" onkeyup=account_addOtpCheck(event) onkeydown=account_addOtpCheck() maxlength=6 id=d2otpauthinput type=text></div>'); QH('d2optinfo', format("Install" + ' <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2" rel="noreferrer noopener" target=_blank>' + "Google Authenticator" + '</a> ' + "or a compatible application, use <a href=\"{0}\" rel=\"noreferrer noopener\" target=_blank> this link</a> or enter the secret below. Then, enter the current 6 digit token to activate 2-Step login.", message.url) + '<br /><br /><div style=width:100%;text-align:center><tt id=d2optsecret secret="' + message.secret + '" style=font-size:15px>' + secret + '</tt><br /><br />Token: <input type=text autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]*" onkeypress=\"return (event.keyCode == 8) || (event.charCode >= 48 && event.charCode <= 57)\" onkeyup=account_addOtpCheck(event) onkeydown=account_addOtpCheck() maxlength=6 id=d2otpauthinput type=text></div>');
QV('idx_dlgOkButton', true); QV('idx_dlgOkButton', true);
QE('idx_dlgOkButton', false); QE('idx_dlgOkButton', false);
Q('d2otpauthinput').focus(); Q('d2otpauthinput').focus();
@ -1753,12 +1773,12 @@
} }
case 'otpauth-setup': { case 'otpauth-setup': {
if (xxdialogMode) return; if (xxdialogMode) return;
setDialogMode(2, "Authenticator App", 1, null, message.success ? "<b style=color:green>2-step login activation successful</b>. You will now need a valid token to login again." : "<b style=color:red>2-step login activation failed</b>. Clear the secret from the application and try again. You only have a few minutes to enter the proper code."); setDialogMode(2, "Authenticator App", 1, null, message.success ? ('<b style=color:green>' + "Authenticator app activation successful." + '</b> ' + "You will now need a valid token to login again.") : ('<b style=color:red>' + "2-step login activation failed." + '</b> ' + "Clear the secret from the application and try again. You only have a few minutes to enter the proper code."));
break; break;
} }
case 'otpauth-clear': { case 'otpauth-clear': {
if (xxdialogMode) return; if (xxdialogMode) return;
setDialogMode(2, "Authenticator App", 1, null, message.success ? "<b style=color:green>2-step login activation removed</b>. You can reactivate this feature at any time." : "<b style=color:red>2-step login activation removal failed</b>. Try again."); setDialogMode(2, "Authenticator App", 1, null, message.success ? ('<b>' + "Authenticator application removed." + '</b> ' + "You can reactivate this feature at any time.") : ('<b style=color:red>' + "2-step login activation removal failed." + '</b> ' + "Try again."));
break; break;
} }
case 'otpauth-getpasswords': { case 'otpauth-getpasswords': {
@ -2025,6 +2045,8 @@
// Change the node // Change the node
node.name = message.event.node.name; node.name = message.event.node.name;
node.rname = message.event.node.rname; node.rname = message.event.node.rname;
node.lusers = message.event.node.lusers;
node.users = message.event.node.users;
node.host = message.event.node.host; node.host = message.event.node.host;
node.desc = message.event.node.desc; node.desc = message.event.node.desc;
node.publicip = message.event.node.publicip; node.publicip = message.event.node.publicip;
@ -2229,6 +2251,10 @@
var foundNode = null; var foundNode = null;
if (nodes != null) { for (var i in nodes) { if (nodes[i].name == args.gotodevicename) { foundNode = nodes[i]._id; } } } if (nodes != null) { for (var i in nodes) { if (nodes[i].name == args.gotodevicename) { foundNode = nodes[i]._id; } } }
if (foundNode) { gotoDevice(foundNode, xviewmode); go(xviewmode); } if (foundNode) { gotoDevice(foundNode, xviewmode); go(xviewmode); }
} else if (args.gotodeviceip != null) {
var foundNode = null;
if (nodes != null) { for (var i in nodes) { if (nodes[i].ip == args.gotodeviceip) { foundNode = nodes[i]._id; } } }
if (foundNode) { gotoDevice(foundNode, xviewmode); go(xviewmode); }
} else if (args.gotomesh != null) { } else if (args.gotomesh != null) {
if (meshes['mesh/' + domain + '/' + args.gotomesh] == null) return; // This device group is not loaded yet if (meshes['mesh/' + domain + '/' + args.gotomesh] == null) return; // This device group is not loaded yet
gotoMesh('mesh/' + domain + '/' + args.gotomesh); gotoMesh('mesh/' + domain + '/' + args.gotomesh);
@ -4255,7 +4281,7 @@
// Draw device power bars. The bars are 766px wide. // Draw device power bars. The bars are 766px wide.
function drawDeviceTimeline() { function drawDeviceTimeline() {
if (currentNode.mtype == 3 || hidePowerTimeline) { QH('p10html2', '<br />'); return; } if (currentNode.mtype == 3 || hidePowerTimeline === 'true') { QH('p10html2', '<br />'); return; }
var timeline = null, now = Date.now(); var timeline = null, now = Date.now();
if (currentNode._id == powerTimelineNode) { timeline = powerTimeline; } if (currentNode._id == powerTimelineNode) { timeline = powerTimeline; }
@ -6180,6 +6206,7 @@
// Operating System // Operating System
var x = ''; var x = '';
if (node.rname) { x += addDetailItem("Name", EscapeHtml(node.rname), s); } if (node.rname) { x += addDetailItem("Name", EscapeHtml(node.rname), s); }
if (hardware.windows && hardware.windows.osinfo && hardware.windows.osinfo.Description) { x += addDetailItem("Description", EscapeHtml(hardware.windows.osinfo.Description), s); }
if (node.osdesc) { x += addDetailItem("Version", EscapeHtml(node.osdesc), s); } if (node.osdesc) { x += addDetailItem("Version", EscapeHtml(node.osdesc), s); }
if (hardware.windows && hardware.windows.osinfo) { if (hardware.windows && hardware.windows.osinfo) {
var m = hardware.windows.osinfo; var m = hardware.windows.osinfo;
@ -6238,11 +6265,11 @@
} }
// Defender for Windows Server // Defender for Windows Server
if(node.defender && !node.wsc) { if(node.defender) {
var y = []; var y = [];
if (node.defender.RealTimeProtection != null) { if (node.defender.RealTimeProtection == true) { y.push("RealTimeProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("RealTimeProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } } if (node.defender.RealTimeProtection != null) { if (node.defender.RealTimeProtection == true) { y.push("RealTimeProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("RealTimeProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } }
if (node.defender.TamperProtected != null) { if (node.defender.TamperProtected == true) { y.push("TamperProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("TamperProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } } if (node.defender.TamperProtected != null) { if (node.defender.TamperProtected == true) { y.push("TamperProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("TamperProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } }
x += addDetailItem("Windows Defender", y.join(', ')); if (y.length > 0) x += addDetailItem("Windows Defender", y.join(', '));
} }
// Antivirus // Antivirus
@ -6261,7 +6288,12 @@
} }
// Active Users // Active Users
if (node.users && (node.users.length > 0)) { x += addDetailItem(((node.users.length > 1)?"Active Users":"Active User"), EscapeHtml(node.users.join(', '))); } if (node.users && node.users.length > 0) {
var u = node.users.map(function(user) {
return addKeyLinkConditional(EscapeHtml(user), "Locked", (node.lusers && node.lusers.indexOf(user) >= 0));
}).join(', ');
x += addDetailItem((node.users.length > 1 ? "Active Users" : "Active User"), u);
}
if (x != '') { sections.push({ name: "Operating System", html: x, img: 'software' }); } if (x != '') { sections.push({ name: "Operating System", html: x, img: 'software' }); }
@ -6350,7 +6382,7 @@
} }
if (hardware.network && hardware.network.dns) { if (hardware.network && hardware.network.dns) {
x += '<tr><td><div class=style10 style=border-radius:5px;padding:8px>'; x += '<tr><td><div class=style10 style=border-radius:5px;padding:8px>';
x += addDetailItem("<b>DNS Servers</b>", hardware.network.dns.join(", ")); x += addDetailItem('<b>' + "DNS Servers" + '</b>', hardware.network.dns.join(", "));
x += '</div></td></tr>'; x += '</div></td></tr>';
} }
x += '</table>'; x += '</table>';
@ -6787,7 +6819,19 @@
if (e.shiftKey == true) { meshserver.send({ action: 'uploadagentcore', nodeid: consoleNode._id, type: 'default' }); } // Upload default core if (e.shiftKey == true) { meshserver.send({ action: 'uploadagentcore', nodeid: consoleNode._id, type: 'default' }); } // Upload default core
else if (e.altKey == true) { meshserver.send({ action: 'uploadagentcore', nodeid: consoleNode._id, type: 'clear' }); } // Clear the core else if (e.altKey == true) { meshserver.send({ action: 'uploadagentcore', nodeid: consoleNode._id, type: 'clear' }); } // Clear the core
else if (e.ctrlKey == true) { p15uploadCore2(); } // Upload the core from a file else if (e.ctrlKey == true) { p15uploadCore2(); } // Upload the core from a file
else { setDialogMode(2, "Perform Agent Action", 3, p15uploadCoreEx, addHtmlValue("Action", '<select id=d3coreMode style=width:230px><option value=1>' + "Upload default server core" + '</option><option value=2>' + "Clear the core" + '</option><option value=6>' + "Upload recovery core" + '</option><option value=7>' + "Upload tiny core" + '</option><option value=3>' + "Upload a core file" + '</option><option value=4>' + "Soft disconnect agent" + '</option><option value=5>' + "Hard disconnect agent" + '</option><option value=8>' + "Restart agent service" + '</select>')); } else {
var htmlValue = '<select id=d3coreMode style=width:230px>' +
'<option value=1>' + "Upload default server core" + '</option>' +
'<option value=2>' + "Clear the core" + '</option>' +
'<option value=3>' + "Upload a core file" + '</option>' +
'<option value=4>' + "Soft disconnect agent" + '</option>' +
'<option value=5>' + "Hard disconnect agent" + '</option>' +
'<option value=6>' + "Upload recovery core" + '</option>' +
'<option value=7>' + "Upload tiny core" + '</option>' +
'<option value=8>' + "Restart agent service" + '</option>' +
'<option value=9>' + "Force agent update" + '</option></select>';
setDialogMode(2, "Perform Agent Action", 3, p15uploadCoreEx, addHtmlValue("Action", htmlValue));
}
} }
function p15uploadCoreEx() { function p15uploadCoreEx() {
@ -6815,6 +6859,9 @@
} else if (Q('d3coreMode').value == 8) { } else if (Q('d3coreMode').value == 8) {
// Restart MeshAgent service // Restart MeshAgent service
meshserver.send({ action: 'msg', type: 'console', nodeid: consoleNode._id, value:'service restart' }); meshserver.send({ action: 'msg', type: 'console', nodeid: consoleNode._id, value:'service restart' });
} else if (Q('d3coreMode').value == 9) {
// Update mesh agent
meshserver.send({ action: 'updateAgents', nodeids: [consoleNode._id] });
} }
} }
@ -7573,7 +7620,7 @@
function addLink(x, f) { return '<a style=cursor:pointer;text-decoration:none onclick=\'' + f + '\'>&diams; ' + x + '</a>'; } function addLink(x, f) { return '<a style=cursor:pointer;text-decoration:none onclick=\'' + f + '\'>&diams; ' + x + '</a>'; }
function addLinkConditional(x, f, c) { if (c) return addLink(x, f); return x; } function addLinkConditional(x, f, c) { if (c) return addLink(x, f); return x; }
function addKeyLink(x, f) { return '<span tabindex=0 style=cursor:pointer;text-decoration:none onclick=' + f + ' onkeypress="if (event.key==\'Enter\') { ' + f + ' } ">' + x + ' <img class=hoverButton src=images/key16.png></span>'; } function addKeyLink(x, f) { return '<span tabindex=0 style=cursor:pointer;text-decoration:none onclick=' + f + ' onkeypress="if (event.key==\'Enter\') { ' + f + ' } ">' + x + ' <img class=hoverButton src=images/key16.png></span>'; }
function addKeyLinkConditional(x, f, c) { if (c) return addKeyLink(x, f); return x; } function addKeyLinkConditional(x, t, c) { if (c) return '<span title=\'' + t + '\'>' + x + ' <img class=hoverButton src=images/key16.png></span>'; return x }
function passwordcheck(p) { var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()]).{8,}/; return re.test(p); } function passwordcheck(p) { var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()]).{8,}/; return re.test(p); }
function getFileSizeStr(size) { if (typeof size != 'number') { size = 0; } if (size == 1) return "1 byte"; return format('{0} bytes', size); } function getFileSizeStr(size) { if (typeof size != 'number') { size = 0; } if (size == 1) return "1 byte"; return format('{0} bytes', size); }
function joinPaths() { var x = []; for (var i in arguments) { var w = arguments[i]; if ((w != null) && (w != '')) { while (w.endsWith('/') || w.endsWith('\\')) { w = w.substring(0, w.length - 1); } while (w.startsWith('/') || w.startsWith('\\')) { w = w.substring(1); } x.push(w); } } return x.join('/'); } function joinPaths() { var x = []; for (var i in arguments) { var w = arguments[i]; if ((w != null) && (w != '')) { while (w.endsWith('/') || w.endsWith('\\')) { w = w.substring(0, w.length - 1); } while (w.startsWith('/') || w.startsWith('\\')) { w = w.substring(1); } x.push(w); } } return x.join('/'); }

View file

@ -164,6 +164,9 @@
<div id=notificationCount onclick="clickNotificationIcon()" class="unselectable" style="display: none;" title="Click to view current notifications">0</div> <div id=notificationCount onclick="clickNotificationIcon()" class="unselectable" style="display: none;" title="Click to view current notifications">0</div>
</div> </div>
<p id="logoutControl"><span id=logoutControlSpan class="logoncontrolspan"></span><span id=idleTimeoutNotify style="color:yellow"></span></p> <p id="logoutControl"><span id=logoutControlSpan class="logoncontrolspan"></span><span id=idleTimeoutNotify style="color:yellow"></span></p>
<div class=textnewui id=textnewui onmouseup=toggleBootstrapUIMode() onkeypress="if (event.key=='Enter') { toggleBootstrapUIMode(); }">
<b>Try the new MeshCentral UI</b>
</div>
</div> </div>
<div id="page_leftbar"> <div id="page_leftbar">
<div style="height:16px"></div> <div style="height:16px"></div>
@ -199,11 +202,13 @@
<div tabindex=0 id=uiViewButton1 class=uiSelector onclick=userInterfaceSelectMenu(1) title="Left bar interface" onkeypress="if (event.key == 'Enter') userInterfaceSelectMenu(1)"><div class="uiSelector1"></div></div> <div tabindex=0 id=uiViewButton1 class=uiSelector onclick=userInterfaceSelectMenu(1) title="Left bar interface" onkeypress="if (event.key == 'Enter') userInterfaceSelectMenu(1)"><div class="uiSelector1"></div></div>
<div tabindex=0 id=uiViewButton2 class=uiSelector onclick=userInterfaceSelectMenu(2) title="Top bar interface" onkeypress="if (event.key == 'Enter') userInterfaceSelectMenu(2)"><div class="uiSelector2"></div></div> <div tabindex=0 id=uiViewButton2 class=uiSelector onclick=userInterfaceSelectMenu(2) title="Top bar interface" onkeypress="if (event.key == 'Enter') userInterfaceSelectMenu(2)"><div class="uiSelector2"></div></div>
<div tabindex=0 id=uiViewButton3 class=uiSelector onclick=userInterfaceSelectMenu(3) title="Fixed width interface" onkeypress="if (event.key == 'Enter') userInterfaceSelectMenu(3)"><div class="uiSelector3"></div></div> <div tabindex=0 id=uiViewButton3 class=uiSelector onclick=userInterfaceSelectMenu(3) title="Fixed width interface" onkeypress="if (event.key == 'Enter') userInterfaceSelectMenu(3)"><div class="uiSelector3"></div></div>
<div tabindex=0 id=uiViewButton7 class=uiSelector onclick=toggleBootstrapUIMode() title="Toggle Modern UI" onkeypress="if (event.key == 'Enter') toggleBootstrapUIMode()"><div class="uiSelector7"></div></div>
</td> </td>
<td> <td>
<div tabindex=0 id=uiViewButton6 class=uiSelector onclick="showNotes(false)" title="Personal Notes" onkeypress="if (event.key == 'Enter') showNotes(false)"><div class="uiSelector6"></div></div> <div tabindex=0 id=uiViewButton6 class=uiSelector onclick="showNotes(false)" title="Personal Notes" onkeypress="if (event.key == 'Enter') showNotes(false)"><div class="uiSelector6"></div></div>
<div tabindex=0 id=uiViewButton4 class=uiSelector onclick=toggleNightMode() title="Toggle night mode" onkeypress="if (event.key == 'Enter') toggleNightMode()"><div class="uiSelector4"></div></div> <div tabindex=0 id=uiViewButton4 class=uiSelector onclick=toggleNightMode() title="Toggle night mode" onkeypress="if (event.key == 'Enter') toggleNightMode()"><div class="uiSelector4"></div></div>
<div tabindex=0 id=uiViewButton5 class=uiSelector onclick=toggleFooterBarMode() title="Toggle footer bar" onkeypress="if (event.key == 'Enter') toggleFooterBarMode()"><div class="uiSelector5"></div></div> <div tabindex=0 id=uiViewButton5 class=uiSelector onclick=toggleFooterBarMode() title="Toggle footer bar" onkeypress="if (event.key == 'Enter') toggleFooterBarMode()"><div class="uiSelector5"></div></div>
<div class=uiSelector_end>&nbsp;</div>
</td> </td>
</tr> </tr>
</table> </table>
@ -430,6 +435,7 @@
<div id="managePhoneNumber1"><div class="p2AccountActions"><span id="authPhoneNumberCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_managePhone()">Manage phone number</a><br /></span></div> <div id="managePhoneNumber1"><div class="p2AccountActions"><span id="authPhoneNumberCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_managePhone()">Manage phone number</a><br /></span></div>
<div id="manageEmail2FA"><div class="p2AccountActions"><span id="authEmailSetupCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageAuthEmail()">Manage email authentication</a><br /></span></div> <div id="manageEmail2FA"><div class="p2AccountActions"><span id="authEmailSetupCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageAuthEmail()">Manage email authentication</a><br /></span></div>
<div id="manageAuthApp"><div class="p2AccountActions"><span id="authAppSetupCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageAuthApp()">Manage authenticator app</a><br /></span></div> <div id="manageAuthApp"><div class="p2AccountActions"><span id="authAppSetupCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageAuthApp()">Manage authenticator app</a><br /></span></div>
<div id="manageDuoApp"><div class="p2AccountActions"><span id="authDuoSetupCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageAuthDuo()">Manage Duo authentication</a><br /></span></div>
<div id="manageHardwareOtp"><div class="p2AccountActions"><span id="authKeySetupCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageHardwareOtp(0)">Manage security keys</a><br /></span></div> <div id="manageHardwareOtp"><div class="p2AccountActions"><span id="authKeySetupCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageHardwareOtp(0)">Manage security keys</a><br /></span></div>
<div id="managePushAuthDev"><div class="p2AccountActions"><span id="authPushAuthDevCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_managePushAuthDev()">Manage push authentication</a><br /></span></div> <div id="managePushAuthDev"><div class="p2AccountActions"><span id="authPushAuthDevCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_managePushAuthDev()">Manage push authentication</a><br /></span></div>
<div id="manageMessaging1"><div class="p2AccountActions"><span id="authMessagingCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageMessaging()">Manage messaging</a><br /></span></div> <div id="manageMessaging1"><div class="p2AccountActions"><span id="authMessagingCheck"><strong>&#x2713;</strong></span></div><span><a href=# onclick="return account_manageMessaging()">Manage messaging</a><br /></span></div>
@ -475,23 +481,23 @@
<td class="auto-style1"> <td class="auto-style1">
Filter Filter
<select id=p3filterevents onchange=refreshEvents()> <select id=p3filterevents onchange=refreshEvents()>
<option value="">All Logs</option> <option notransval=1 value="">All Logs</option>
<option value=agentlog>Agent Logs</option> <option notransval=1 value=agentlog>Agent Logs</option>
<option value=relaylog>Relay Logs</option> <option notransval=1 value=relaylog>Relay Logs</option>
<option value=manual>Manual Logs</option> <option notransval=1 value=manual>Manual Logs</option>
<option value=runcommands>Run Command Logs</option> <option notransval=1 value=runcommands>Run Command Logs</option>
<option value=batchupload>Batch Upload Logs</option> <option notransval=1 value=batchupload>Batch Upload Logs</option>
<option value=changenode>Change Node Logs</option> <option notransval=1 value=changenode>Change Node Logs</option>
<option value=removenode>Remove Node Logs</option> <option notransval=1 value=removenode>Remove Node Logs</option>
</select> </select>
Show Show
<select id=p3limitdropdown onchange=refreshEvents()> <select id=p3limitdropdown onchange=refreshEvents()>
<option value=60>Last 60</option> <option notransval=1 value=60>Last 60</option>
<option value=120>Last 120</option> <option notransval=1 value=120>Last 120</option>
<option value=250>Last 250</option> <option notransval=1 value=250>Last 250</option>
<option value=500>Last 500</option> <option notransval=1 value=500>Last 500</option>
<option value=1000>Last 1000</option> <option notransval=1 value=1000>Last 1000</option>
<option value="">No limit</option> <option notransval=1 value="">No limit</option>
</select>&nbsp; </select>&nbsp;
<a href=# onclick=p3showDownloadEventsDialog(2)><img src=images/link4.png height=10 width=10 title="Download Events" style=cursor:pointer></a>&nbsp; <a href=# onclick=p3showDownloadEventsDialog(2)><img src=images/link4.png height=10 width=10 title="Download Events" style=cursor:pointer></a>&nbsp;
</td> </td>
@ -992,22 +998,22 @@
<td class="auto-style1"> <td class="auto-style1">
Filter Filter
<select id=p16filterevents onchange=refreshDeviceEvents()> <select id=p16filterevents onchange=refreshDeviceEvents()>
<option value="">All Logs</option> <option notransval=1 value="">All Logs</option>
<option value=agentlog>Agent Logs</option> <option notransval=1 value=agentlog>Agent Logs</option>
<option value=relaylog>Relay Logs</option> <option notransval=1 value=relaylog>Relay Logs</option>
<option value=manual>Manual Logs</option> <option notransval=1 value=manual>Manual Logs</option>
<option value=runcommands>Run Command Logs</option> <option notransval=1 value=runcommands>Run Command Logs</option>
<option value=batchupload>Batch Upload Logs</option> <option notransval=1 value=batchupload>Batch Upload Logs</option>
<option value=changenode>Change Node Logs</option> <option notransval=1 value=changenode>Change Node Logs</option>
<option value=removenode>Remove Node Logs</option> <option notransval=1 value=removenode>Remove Node Logs</option>
</select> </select>
Show Show
<select id=p16limitdropdown onchange=refreshDeviceEvents()> <select id=p16limitdropdown onchange=refreshDeviceEvents()>
<option value=60>Last 60</option> <option notransval=1 value=60>Last 60</option>
<option value=120>Last 120</option> <option notransval=1 value=120>Last 120</option>
<option value=250>Last 250</option> <option notransval=1 value=250>Last 250</option>
<option value=500>Last 500</option> <option notransval=1 value=500>Last 500</option>
<option value=1000>Last 1000</option> <option notransval=1 value=1000>Last 1000</option>
</select> </select>
<a href=# onclick=p3showDownloadEventsDialog(1)><img src=images/link4.png height=10 width=10 title="Download Events" style=cursor:pointer></a>&nbsp; <a href=# onclick=p3showDownloadEventsDialog(1)><img src=images/link4.png height=10 width=10 title="Download Events" style=cursor:pointer></a>&nbsp;
</td> </td>
@ -1132,23 +1138,23 @@
<td class="auto-style1"> <td class="auto-style1">
Filter Filter
<select id=p31filterevents onchange=refreshUsersEvents()> <select id=p31filterevents onchange=refreshUsersEvents()>
<option value="">All Logs</option> <option notransval=1 value="">All Logs</option>
<option value=agentlog>Agent Logs</option> <option notransval=1 value=agentlog>Agent Logs</option>
<option value=relaylog>Relay Logs</option> <option notransval=1 value=relaylog>Relay Logs</option>
<option value=manual>Manual Logs</option> <option notransval=1 value=manual>Manual Logs</option>
<option value=runcommands>Run Command Logs</option> <option notransval=1 value=runcommands>Run Command Logs</option>
<option value=batchupload>Batch Upload Logs</option> <option notransval=1 value=batchupload>Batch Upload Logs</option>
<option value=changenode>Change Node Logs</option> <option notransval=1 value=changenode>Change Node Logs</option>
<option value=removenode>Remove Node Logs</option> <option notransval=1 value=removenode>Remove Node Logs</option>
</select> </select>
Show Show
<select id=p31limitdropdown onchange=refreshUsersEvents()> <select id=p31limitdropdown onchange=refreshUsersEvents()>
<option value=60>Last 60</option> <option notransval=1 value=60>Last 60</option>
<option value=120>Last 120</option> <option notransval=1 value=120>Last 120</option>
<option value=250>Last 250</option> <option notransval=1 value=250>Last 250</option>
<option value=500>Last 500</option> <option notransval=1 value=500>Last 500</option>
<option value=1000>Last 1000</option> <option notransval=1 value=1000>Last 1000</option>
<option value="">No limit</option> <option notransval=1 value="">No limit</option>
</select> </select>
<a href=# onclick=p3showDownloadEventsDialog(3)><img src=images/link4.png height=10 width=10 title="Download Events" style=cursor:pointer></a>&nbsp; <a href=# onclick=p3showDownloadEventsDialog(3)><img src=images/link4.png height=10 width=10 title="Download Events" style=cursor:pointer></a>&nbsp;
</td> </td>
@ -1452,16 +1458,16 @@
<div style="margin-top:8px"> <div style="margin-top:8px">
<div>Display Size</div> <div>Display Size</div>
<select id="d7rdpsize"> <select id="d7rdpsize">
<option value="canvas">Canvas Size</option> <option notransval=1 value="canvas">Canvas Size</option>
<option value="browser">Browser Size</option> <option notransval=1 value="browser">Browser Size</option>
<option value="screen">Screen Size</option> <option notransval=1 value="screen">Screen Size</option>
<option value="640x480">640x480</option> <option notransval=1 value="640x480">640x480</option>
<option value="1024x768">1024x768</option> <option notransval=1 value="1024x768">1024x768</option>
<option value="1280x800">1280x800</option> <option notransval=1 value="1280x800">1280x800</option>
<option value="1440x900">1440x900</option> <option notransval=1 value="1440x900">1440x900</option>
<option value="1600x900">1600x900</option> <option notransval=1 value="1600x900">1600x900</option>
<option value="1680x1050">1680x1050</option> <option notransval=1 value="1680x1050">1680x1050</option>
<option value="1920x1080">1920x1080</option> <option notransval=1 value="1920x1080">1920x1080</option>
</select> </select>
</div> </div>
<div> <div>
@ -1473,7 +1479,7 @@
<label style="display:block"><input type="checkbox" id="d7rdp4" />Disable Theming</label> <label style="display:block"><input type="checkbox" id="d7rdp4" />Disable Theming</label>
<label style="display:block"><input type="checkbox" id="d7rdp6" />Disable Cursor Shadow</label> <label style="display:block"><input type="checkbox" id="d7rdp6" />Disable Cursor Shadow</label>
<label style="display:block"><input type="checkbox" id="d7rdp7" />Disable Cursor Settings</label> <label style="display:block"><input type="checkbox" id="d7rdp7" />Disable Cursor Settings</label>
<label style="display:block"><input type="checkbox" id="d7rdp8" />Enable Font Smooting</label> <label style="display:block"><input type="checkbox" id="d7rdp8" />Enable Font Smoothing</label>
<label style="display:block"><input type="checkbox" id="d7rdp9" />Enable Desktop Composision</label> <label style="display:block"><input type="checkbox" id="d7rdp9" />Enable Desktop Composision</label>
<label style="display:block"><input type="checkbox" id="d7rdpclip" />Automatic Clipboard</label> <label style="display:block"><input type="checkbox" id="d7rdpclip" />Automatic Clipboard</label>
<label style="display:block"><input type="checkbox" id="d7rdpsmb" />Swap Mouse Buttons</label> <label style="display:block"><input type="checkbox" id="d7rdpsmb" />Swap Mouse Buttons</label>
@ -1547,8 +1553,8 @@
var sessionTime = parseInt('{{{sessiontime}}}'); var sessionTime = parseInt('{{{sessiontime}}}');
var webRelayPort = parseInt('{{{webRelayPort}}}'); var webRelayPort = parseInt('{{{webRelayPort}}}');
var webRelayDns = '{{{webRelayDns}}}'; var webRelayDns = '{{{webRelayDns}}}';
var hidePowerTimeline = {{{hidePowerTimeline}}}; var hidePowerTimeline = '{{{hidePowerTimeline}}}';
var showNotesPanel = {{{showNotesPanel}}}; var showNotesPanel = '{{{showNotesPanel}}}';
var sessionRefreshTimer = null; var sessionRefreshTimer = null;
var domain = '{{{domain}}}'; var domain = '{{{domain}}}';
var domainUrl = '{{{domainurl}}}'; var domainUrl = '{{{domainurl}}}';
@ -1641,6 +1647,7 @@
delete urlargs.viewmode; delete urlargs.viewmode;
delete urlargs.gotonode; delete urlargs.gotonode;
delete urlargs.gotodevicename; delete urlargs.gotodevicename;
delete urlargs.gotodeviceip;
delete urlargs.gotomesh; delete urlargs.gotomesh;
delete urlargs.gotouser; delete urlargs.gotouser;
delete urlargs.gotougrp; delete urlargs.gotougrp;
@ -1721,6 +1728,9 @@
}); });
} }
// Show the modern ui switcher
QV('textnewui', ((features2 & 0x40000000) == 0) ? false : true);
// Connect to the mesh server // Connect to the mesh server
meshserver = MeshServerCreateControl(domainUrl); meshserver = MeshServerCreateControl(domainUrl);
meshserver.onStateChanged = onStateChanged; meshserver.onStateChanged = onStateChanged;
@ -2181,10 +2191,29 @@
QV('body', true); QV('body', true);
} }
function saveUserInterfaceMode() {
var nUiViewMode = 2;
if (Q('ui1').checked) { nUiViewMode = 3; }
if (getstore('uiViewMode', 2) != nUiViewMode) {
putstore('uiViewMode', nUiViewMode);
reload();
}
}
function toggleBootstrapUIMode() {
if (xxdialogMode) return;
var uiViewMode = getstore('uiViewMode', 2);
var x = '<input type=radio id=ui0 name=uiradio value=2 ' + ((uiViewMode == 2)?'checked':'') + '><label for=ui0>' + "Classic" + '</label><br>';
x += '<input type=radio id=ui1 name=uiradio value=3 ' + ((uiViewMode == 3)?'checked':'') + '><label for=ui1>' + "Modern" + '</label><br>';
setDialogMode(2, "User Interface", 3, saveUserInterfaceMode, x);
QV('uiMenu', false);
}
function getNodeFromId(id) { if (nodes != null) { for (var i in nodes) { if (nodes[i]._id == id) return nodes[i]; } } return null; } function getNodeFromId(id) { if (nodes != null) { for (var i in nodes) { if (nodes[i]._id == id) return nodes[i]; } } return null; }
function reload() { function reload() {
var x = window.location.href; var x = window.location.href;
if (x.endsWith('/#')) { x = x.substring(0, x.length - 2); } if (x.endsWith('/#')) { x = x.substring(0, x.length - 2); }
if (x.endsWith('#')) { x = x.substring(0, x.length - 1); }
window.location.href = x; window.location.href = x;
} }
@ -2357,8 +2386,10 @@
QV('authPhoneNumberCheck', (userinfo.phone != null)); QV('authPhoneNumberCheck', (userinfo.phone != null));
QV('authMessagingCheck', (userinfo.msghandle != null)); QV('authMessagingCheck', (userinfo.msghandle != null));
QV('authEmailSetupCheck', (userinfo.otpekey == 1) && (userinfo.email != null) && (userinfo.emailVerified == true)); QV('authEmailSetupCheck', (userinfo.otpekey == 1) && (userinfo.email != null) && (userinfo.emailVerified == true));
QV('authDuoSetupCheck', (userinfo.otpduo == 1) && ((features2 & 0x20000000) != 0));
QV('authAppSetupCheck', userinfo.otpsecret == 1); QV('authAppSetupCheck', userinfo.otpsecret == 1);
QV('manageAuthApp', (serverinfo.lock2factor != true) && ((userinfo.otpsecret == 1) || ((features2 & 0x00020000) == 0))); QV('manageAuthApp', (serverinfo.lock2factor != true) && ((userinfo.otpsecret == 1) || ((features2 & 0x00020000) == 0)));
QV('manageDuoApp', (serverinfo.lock2factor != true) && ((features2 & 0x20000000) != 0));
QV('authKeySetupCheck', userinfo.otphkeys > 0); QV('authKeySetupCheck', userinfo.otphkeys > 0);
QV('authPushAuthDevCheck', (userinfo.otpdev > 0) && ((features2 & 0x40) != 0)); QV('authPushAuthDevCheck', (userinfo.otpdev > 0) && ((features2 & 0x40) != 0));
QV('authCodesSetupCheck', userinfo.otpkeys > 0); QV('authCodesSetupCheck', userinfo.otpkeys > 0);
@ -2416,15 +2447,28 @@
files.Stop(); files.Stop();
files = null; files = null;
} }
window.location.href = 'logout'; if (serverinfo.logoutonidlesessiontimeout) {
window.location.href = 'logout';
}
} else { } else {
var ds = Math.round((serverinfo.timeout - delta) / 1000); var ds = Math.round((serverinfo.timeout - delta) / 1000);
var sessionInProgress = desktop != null || terminal != null || files != null;
var show = serverinfo.logoutonidlesessiontimeout || sessionInProgress;
var isLogout = serverinfo.logoutonidlesessiontimeout;
var theText = ''; // Initialize theText
if (ds <= 60) { if (ds <= 60) {
QH('idleTimeoutNotify', '<br />' + format((ds == 1)?"1 second until disconnect":"{0} seconds until disconnect", ds)); theText = isLogout
? (ds == 1 ? "1 second until logout" : "{0} seconds until logout")
: (ds == 1 ? "1 second until disconnect" : "{0} seconds until disconnect");
} else { } else {
ds = Math.round(ds / 60); ds = Math.round(ds / 60);
if (ds <= 5) { QH('idleTimeoutNotify', '<br />' + format((ds == 1)?"1 minute until disconnect":"{0} minutes until disconnect", ds)); } if (ds <= 5) {
theText = isLogout
? (ds == 1 ? "1 minute until logout" : "{0} minutes until logout")
: (ds == 1 ? "1 minute until disconnect" : "{0} minutes until disconnect");
}
} }
QH('idleTimeoutNotify', show && theText ? '<br />' + format(theText, ds) : '');
} }
} }
@ -2484,7 +2528,7 @@
24: "Unable to load agent logo file: {0}.", 24: "Unable to load agent logo file: {0}.",
25: "This NodeJS version does not support OpenID.", 25: "This NodeJS version does not support OpenID.",
26: "This NodeJS version does not support Discord.js.", 26: "This NodeJS version does not support Discord.js.",
27: "Firebase is not supported on this version of NodeJS." 27: "Firebase now requires a service account JSON file, Firebase disabled."
}; };
var x = ''; var x = '';
for (var i in message.warnings) { for (var i in message.warnings) {
@ -2833,11 +2877,11 @@
if (net.name) { x += addHtmlValue2("Name", '<b>' + EscapeHtml(net.name) + '</b>'); } if (net.name) { x += addHtmlValue2("Name", '<b>' + EscapeHtml(net.name) + '</b>'); }
if (net.desc) { x += addHtmlValue2("Description", EscapeHtml(net.desc).replace('(R)', '&reg;').replace('(r)', '&reg;')); } if (net.desc) { x += addHtmlValue2("Description", EscapeHtml(net.desc).replace('(R)', '&reg;').replace('(r)', '&reg;')); }
if (net.dnssuffix) { x += addHtmlValue2("DNS suffix", EscapeHtml(net.dnssuffix) + ' <img src="images/link4.png" title="' + "Copy name to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.dnssuffix) + '") width=10 height=10>'); } if (net.dnssuffix) { x += addHtmlValue2("DNS suffix", EscapeHtml(net.dnssuffix) + ' <img src="images/link4.png" title="' + "Copy name to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.dnssuffix) + '") width=10 height=10>'); }
if (net.mac) { x += addHtmlValue2("MAC address", '<a href="https://dnslytics.com/mac-address-lookup/' + net.mac.substring(0, 6) + '" rel="noreferrer noopener" target="MeshMACLoopup">' + EscapeHtml(net.mac.toLowerCase()) + '</a> <img src="images/link4.png" title="' + "Copy MAC address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.mac.toLowerCase()) + '") width=10 height=10>'); } if (net.mac) { x += addHtmlValue2("MAC address", '<a href="https://maclookup.app/search/result?mac=' + net.mac.substring(0, 6) + '" rel="noreferrer noopener" target="MeshMACLoopup">' + EscapeHtml(net.mac.toLowerCase()) + '</a> <img src="images/link4.png" title="' + "Copy MAC address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.mac.toLowerCase()) + '") width=10 height=10>'); }
if (net.v4addr) { x += addHtmlValue2("IPv4 address", EscapeHtml(net.v4addr) + ' <img src="images/link4.png" title="' + "Copy address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.v4addr) + '") width=10 height=10>'); } if (net.v4addr) { x += addHtmlValue2("IPv4 address", EscapeHtml(net.v4addr) + ' <img src="images/link4.png" title="' + "Copy address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.v4addr) + '") width=10 height=10>'); }
if (net.v4mask) { x += addHtmlValue2("IPv4 mask", EscapeHtml(net.v4mask) + ' <img src="images/link4.png" title="' + "Copy address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.v4mask) + '") width=10 height=10>'); } if (net.v4mask) { x += addHtmlValue2("IPv4 mask", EscapeHtml(net.v4mask) + ' <img src="images/link4.png" title="' + "Copy address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.v4mask) + '") width=10 height=10>'); }
if (net.v4gateway) { x += addHtmlValue2("IPv4 gateway", EscapeHtml(net.v4gateway) + ' <img src="images/link4.png" title="' + "Copy address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.v4gateway) + '") width=10 height=10>'); } if (net.v4gateway) { x += addHtmlValue2("IPv4 gateway", EscapeHtml(net.v4gateway) + ' <img src="images/link4.png" title="' + "Copy address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.v4gateway) + '") width=10 height=10>'); }
if (net.gatewaymac) { x += addHtmlValue2("Gateway MAC", '<a href="https://dnslytics.com/mac-address-lookup/' + net.gatewaymac.substring(0, 6) + '" rel="noreferrer noopener" target="MeshMACLoopup">' + EscapeHtml(net.gatewaymac.toLowerCase()) + '</a> <img src="images/link4.png" title="' + "Copy MAC address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.gatewaymac.toLowerCase()) + '") width=10 height=10>'); } if (net.gatewaymac) { x += addHtmlValue2("Gateway MAC", '<a href="https://maclookup.app/search/result?mac=' + net.gatewaymac.substring(0, 6) + '" rel="noreferrer noopener" target="MeshMACLoopup">' + EscapeHtml(net.gatewaymac.toLowerCase()) + '</a> <img src="images/link4.png" title="' + "Copy MAC address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net.gatewaymac.toLowerCase()) + '") width=10 height=10>'); }
} }
} else if (message.netif2 != null) { } else if (message.netif2 != null) {
// New style // New style
@ -2846,7 +2890,7 @@
if ((Array.isArray(net) == false) || (net.length < 1) || (net[0] == null) || ((typeof net[0].mac == 'string') && (net[0].mac.startsWith('00:00:00:00')))) continue; if ((Array.isArray(net) == false) || (net.length < 1) || (net[0] == null) || ((typeof net[0].mac == 'string') && (net[0].mac.startsWith('00:00:00:00')))) continue;
x += '<hr />' x += '<hr />'
x += addHtmlValue2("Name", '<b>' + EscapeHtml(i) + '</b>'); x += addHtmlValue2("Name", '<b>' + EscapeHtml(i) + '</b>');
if (typeof net[0].mac == 'string') { x += addHtmlValue2("MAC address", '<a href="https://dnslytics.com/mac-address-lookup/' + net[0].mac.split(':').join('').substring(0, 6) + '" rel="noreferrer noopener" target="MeshMACLoopup">' + EscapeHtml(net[0].mac.toLowerCase()) + '</a> <img src="images/link4.png" title="' + "Copy MAC address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net[0].mac.toLowerCase()) + '") width=10 height=10>'); } if (typeof net[0].mac == 'string') { x += addHtmlValue2("MAC address", '<a href="https://maclookup.app/search/result?mac=' + net[0].mac.split(':').join('').substring(0, 6) + '" rel="noreferrer noopener" target="MeshMACLoopup">' + EscapeHtml(net[0].mac.toLowerCase()) + '</a> <img src="images/link4.png" title="' + "Copy MAC address to clipboard" + '" style="cursor:pointer" onclick=copyTextToClip2("' + encodeURIComponentEx(net[0].mac.toLowerCase()) + '") width=10 height=10>'); }
if (net[0].fqdn) { x += addHtmlValue2("FQDN", net[0].fqdn); } if (net[0].fqdn) { x += addHtmlValue2("FQDN", net[0].fqdn); }
for (var j = 0; j < net.length; j++) { for (var j = 0; j < net.length; j++) {
var netif = net[j]; var netif = net[j];
@ -2994,7 +3038,7 @@
} }
}else{ }else{
Q('notesPanelArea').innerHTML = (message.notes && marked && DOMPurify) ? DOMPurify.sanitize(marked.parse(decodeURIComponent(message.notes), { breaks: true }), { USE_PROFILES: { html: true } }) : ''; Q('notesPanelArea').innerHTML = (message.notes && marked && DOMPurify) ? DOMPurify.sanitize(marked.parse(decodeURIComponent(message.notes), { breaks: true }), { USE_PROFILES: { html: true } }) : '';
if (showNotesPanel && message.notes) { QV('notesPanel',true); }else{ QV('notesPanel', false); } if ((showNotesPanel === 'true') && message.notes) { QV('notesPanel',true); }else{ QV('notesPanel', false); }
} }
break; break;
} }
@ -3007,7 +3051,7 @@
var secret = message.secret; var secret = message.secret;
if (secret.length == 52) { secret = secret.split(/(.............)/).filter(Boolean).join(' '); } if (secret.length == 52) { secret = secret.split(/(.............)/).filter(Boolean).join(' '); }
else if (secret.length == 32) { secret = secret.split(/(....)/).filter(Boolean).join(' '); secret = secret.substring(0, 20) + '<br/>' + secret.substring(20) } else if (secret.length == 32) { secret = secret.split(/(....)/).filter(Boolean).join(' '); secret = secret.substring(0, 20) + '<br/>' + secret.substring(20) }
QH('d2optinfo', '<table style=width:380px><tr><td style=vertical-align:top>' + format("Install <a href=\"https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2\" rel=\"noreferrer noopener\" target=_blank>Google Authenticator</a> or a compatible application and scan the barcode, use <a href=\"{0}\" rel=\"noreferrer noopener\" target=_blank>this link</a> or enter the secret. Then, enter the current 6 digit token below to activate 2-Step login.", message.url) + '<br /><br />' + 'Secret <img src=images/link4.png height=10 width=10 title="' + "Copy Secret to clipboard" + '" style=cursor:pointer onclick=d2CopySecretToClip()>' + '<br /><tt id=d2optsecret secret="' + message.secret + '" style=font-size:12px>' + secret + '</tt><br /><br /></td><td style=width:1px;vertical-align:top><a href="' + message.url + '" rel="noreferrer noopener" target=_blank><div id="qrcode"></div></a></td><tr><td colspan=2 style="text-align:center;border-top:1px solid black"><br />' + "Enter the token here for 2-step login:" + ' <input type=text autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]*" onkeypress="return (event.keyCode == 8) || (event.charCode >= 48 && event.charCode <= 57)" onkeyup=account_addOtpCheck(event) onkeydown=account_addOtpCheck() maxlength=6 id=d2otpauthinput type=text></td></table>'); QH('d2optinfo', '<table style=width:380px><tr><td style=vertical-align:top>' + format("Install" + ' <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2" rel="noreferrer noopener" target=_blank>' + "Google Authenticator" + '</a> ' + "or a compatible application and scan the barcode, use <a href=\"{0}\" rel=\"noreferrer noopener\" target=_blank>this link</a> or enter the secret. Then, enter the current 6 digit token below to activate 2-Step login.", message.url) + '<br /><br />' + 'Secret <img src=images/link4.png height=10 width=10 title="' + "Copy Secret to clipboard" + '" style=cursor:pointer onclick=d2CopySecretToClip()>' + '<br /><tt id=d2optsecret secret="' + message.secret + '" style=font-size:12px>' + secret + '</tt><br /><br /></td><td style=width:1px;vertical-align:top><a href="' + message.url + '" rel="noreferrer noopener" target=_blank><div id="qrcode"></div></a></td><tr><td colspan=2 style="text-align:center;border-top:1px solid black"><br />' + "Enter the token here for 2-step login:" + ' <input type=text autocomplete="one-time-code" inputmode="numeric" pattern="[0-9]*" onkeypress="return (event.keyCode == 8) || (event.charCode >= 48 && event.charCode <= 57)" onkeyup=account_addOtpCheck(event) onkeydown=account_addOtpCheck() maxlength=6 id=d2otpauthinput type=text></td></table>');
new QRCode(Q('qrcode'), { text: message.url, width: 128, height: 128, colorDark: '#000000', colorLight: '#EEE', correctLevel: QRCode.CorrectLevel.H }); new QRCode(Q('qrcode'), { text: message.url, width: 128, height: 128, colorDark: '#000000', colorLight: '#EEE', correctLevel: QRCode.CorrectLevel.H });
QV('idx_dlgOkButton', true); QV('idx_dlgOkButton', true);
QE('idx_dlgOkButton', false); QE('idx_dlgOkButton', false);
@ -3062,7 +3106,7 @@
if (xxdialogMode && (xxdialogTag != 'otpauth-hardware-manage')) return; if (xxdialogMode && (xxdialogTag != 'otpauth-hardware-manage')) return;
var start = '<div style="border-radius:6px;border:2px solid #CCC;background-color:#BBB;width:100%;box-sizing:border-box;margin-bottom:6px"><div style="margin:3px;font-family:Arial, Helvetica, sans-serif;font-size:16px;font-weight:bold"><table style=width:100%;text-align:left>'; var start = '<div style="border-radius:6px;border:2px solid #CCC;background-color:#BBB;width:100%;box-sizing:border-box;margin-bottom:6px"><div style="margin:3px;font-family:Arial, Helvetica, sans-serif;font-size:16px;font-weight:bold"><table style=width:100%;text-align:left>';
var end = '</table></div></div>'; var end = '</table></div></div>';
var x = "<a href=\"https://www.yubico.com/\" rel=\"noreferrer noopener\" target=\"_blank\">Hardware keys</a> are used as secondary login authentication."; var x = '<a href="https://www.yubico.com/" rel="noreferrer noopener" target="_blank">' + "Hardware keys" + '</a> ' + "are used as secondary login authentication.";
x += '<div style="max-height:150px;overflow-y:auto;overflow-x:hidden;margin-top:6px;margin-bottom:6px">'; x += '<div style="max-height:150px;overflow-y:auto;overflow-x:hidden;margin-top:6px;margin-bottom:6px">';
if (message.keys && message.keys.length > 0) { if (message.keys && message.keys.length > 0) {
for (var i in message.keys) { for (var i in message.keys) {
@ -3175,9 +3219,11 @@
if (currentNode && (message.event.nodeid == currentNode._id) && (currentDeviceEvents != null)) { if (currentNode && (message.event.nodeid == currentNode._id) && (currentDeviceEvents != null)) {
// If this event has a nodeid and we are looking at this node, update the log in real time. // If this event has a nodeid and we are looking at this node, update the log in real time.
if ((message.event.action == p16filterevents.value) || (p16filterevents.value == "")) { if ((message.event.action == p16filterevents.value) || (p16filterevents.value == "")) {
currentDeviceEvents.unshift(message.event); if(currentDeviceEvents != null) {
var eventLimit = parseInt(p16limitdropdown.value); currentDeviceEvents.unshift(message.event);
while (currentDeviceEvents.length > eventLimit) { currentDeviceEvents.pop(); } // Remove element(s) at the end var eventLimit = parseInt(p16limitdropdown.value);
while (currentDeviceEvents.length > eventLimit) { currentDeviceEvents.pop(); } // Remove element(s) at the end
}
mainUpdate(1024); mainUpdate(1024);
} }
} }
@ -3185,18 +3231,22 @@
if (currentUser && (message.event.userid == currentUser._id)) { if (currentUser && (message.event.userid == currentUser._id)) {
// If this event has a userid and we are looking at this user, update the log in real time. // If this event has a userid and we are looking at this user, update the log in real time.
if ((message.event.action == p31filterevents.value) || (p31filterevents.value == "")) { if ((message.event.action == p31filterevents.value) || (p31filterevents.value == "")) {
currentUserEvents.unshift(message.event); if(currentUserEvents != null) {
var eventLimit = parseInt(p31limitdropdown.value); currentUserEvents.unshift(message.event);
while (currentUserEvents.length > eventLimit) { currentUserEvents.pop(); } // Remove element(s) at the end var eventLimit = parseInt(p31limitdropdown.value);
while (currentUserEvents.length > eventLimit) { currentUserEvents.pop(); } // Remove element(s) at the end
}
mainUpdate(2048); mainUpdate(2048);
} }
} }
// Add this event to the main events log. // Add this event to the main events log.
if ((message.event.action == p3filterevents.value) || (p3filterevents.value == "")) { if ((message.event.action == p3filterevents.value) || (p3filterevents.value == "")) {
events.unshift(message.event); if(events != null) {
var eventLimit = parseInt(p3limitdropdown.value); events.unshift(message.event);
while (events.length > eventLimit) { events.pop(); } // Remove element(s) at the end var eventLimit = parseInt(p3limitdropdown.value);
while (events.length > eventLimit) { events.pop(); } // Remove element(s) at the end
}
mainUpdate(32); mainUpdate(32);
} }
} }
@ -3492,6 +3542,7 @@
// Change the node // Change the node
node.name = message.event.node.name; node.name = message.event.node.name;
node.rname = message.event.node.rname; node.rname = message.event.node.rname;
node.lusers = message.event.node.lusers;
node.users = message.event.node.users; node.users = message.event.node.users;
node.host = message.event.node.host; node.host = message.event.node.host;
node.desc = message.event.node.desc; node.desc = message.event.node.desc;
@ -4008,6 +4059,10 @@
var foundNode = null; var foundNode = null;
if (nodes != null) { for (var i in nodes) { if (nodes[i].name == args.gotodevicename) { foundNode = nodes[i]._id; } } } if (nodes != null) { for (var i in nodes) { if (nodes[i].name == args.gotodevicename) { foundNode = nodes[i]._id; } } }
if (foundNode) { gotoDevice(foundNode, xviewmode); goBackStack.push(1); } if (foundNode) { gotoDevice(foundNode, xviewmode); goBackStack.push(1); }
} else if (args.gotodeviceip != null) {
var foundNode = null;
if (nodes != null) { for (var i in nodes) { if (nodes[i].ip == args.gotodeviceip) { foundNode = nodes[i]._id; } } }
if (foundNode) { gotoDevice(foundNode, xviewmode); goBackStack.push(1); }
} else if (args.gotomesh != null) { } else if (args.gotomesh != null) {
if (meshes['mesh/' + domain + '/' + args.gotomesh] == null) return; // This device group is not loaded yet if (meshes['mesh/' + domain + '/' + args.gotomesh] == null) return; // This device group is not loaded yet
gotoMesh('mesh/' + domain + '/' + args.gotomesh); gotoMesh('mesh/' + domain + '/' + args.gotomesh);
@ -4888,13 +4943,13 @@
r += '<span style=line-height:20px>' + groupingTags + '</span>'; r += '<span style=line-height:20px>' + groupingTags + '</span>';
} }
if (deviceViewSettings.devsCols.indexOf('windowsav') >= 0) { // Windows AV if (deviceViewSettings.devsCols.indexOf('windowsav') >= 0) { // Windows AV
r += '<td style=text-align:center>' + ((node.wsc && node.wsc.antiVirus != null) ? (node.wsc.antiVirus == 'OK' ? "<span style=color:green>OK</span>" : "<span style=color:red>BAD</span>") : ""); r += '<td style=text-align:center>' + ((node.wsc && node.wsc.antiVirus != null) ? (node.wsc.antiVirus == 'OK' ? '<span style=color:green>' + "OK" + '</span>' : '<span style=color:red>' + "BAD" + '</span>') : "");
} }
if (deviceViewSettings.devsCols.indexOf('windowsupdate') >= 0) {// Windows Update if (deviceViewSettings.devsCols.indexOf('windowsupdate') >= 0) {// Windows Update
r += '<td style=text-align:center>' + ((node.wsc && node.wsc.autoUpdate != null) ? (node.wsc.autoUpdate == 'OK' ? "<span style=color:green>OK</span>" : "<span style=color:red>BAD</span>") : ""); r += '<td style=text-align:center>' + ((node.wsc && node.wsc.autoUpdate != null) ? (node.wsc.autoUpdate == 'OK' ? '<span style=color:green>' + "OK" + '</span>' : '<span style=color:red>' + "BAD" + '</span>') : "");
} }
if (deviceViewSettings.devsCols.indexOf('windowsfirewall') >= 0) { // Windows Firewall if (deviceViewSettings.devsCols.indexOf('windowsfirewall') >= 0) { // Windows Firewall
r += '<td style=text-align:center>' + ((node.wsc && node.wsc.firewall != null) ? (node.wsc.firewall == 'OK' ? "<span style=color:green>OK</span>" : "<span style=color:red>BAD</span>") : ""); r += '<td style=text-align:center>' + ((node.wsc && node.wsc.firewall != null) ? (node.wsc.firewall == 'OK' ? '<span style=color:green>' + "OK" + '</span>' : '<span style=color:red>' + "BAD" + '</span>') : "");
} }
if (deviceViewSettings.devsCols.indexOf('lastbootuptime') >= 0) { // Last Boot Up Time if (deviceViewSettings.devsCols.indexOf('lastbootuptime') >= 0) { // Last Boot Up Time
r += '<td style=text-align:center;font-size:x-small>' + ((node.lastbootuptime != null) ? printDateTime(new Date(node.lastbootuptime)) : ""); r += '<td style=text-align:center;font-size:x-small>' + ((node.lastbootuptime != null) ? printDateTime(new Date(node.lastbootuptime)) : "");
@ -5385,7 +5440,7 @@
x += addHtmlValue("New Password*", '<input id=dp1password1 type=password style=width:230px autocomplete=off maxlength=32 onchange=validateAmtAcmSetupEx() onkeyup=validateAmtAcmSetupEx() />'); x += addHtmlValue("New Password*", '<input id=dp1password1 type=password style=width:230px autocomplete=off maxlength=32 onchange=validateAmtAcmSetupEx() onkeyup=validateAmtAcmSetupEx() />');
x += addHtmlValue("New Password*", '<input id=dp1password2 type=password style=width:230px autocomplete=off maxlength=32 onchange=validateAmtAcmSetupEx() onkeyup=validateAmtAcmSetupEx() />'); x += addHtmlValue("New Password*", '<input id=dp1password2 type=password style=width:230px autocomplete=off maxlength=32 onchange=validateAmtAcmSetupEx() onkeyup=validateAmtAcmSetupEx() />');
if ((features2 & 0x00000020) && (currentMesh.mtype == 1) && (serverinfo.amtProvServerMeshId == currentMesh._id)) { x += '<label><input id=dp1lanprov type=checkbox /> ' + "Use for bare-metal LAN activation." + '</label>'; } // Intel AMT LAN provisioning server is active. if ((features2 & 0x00000020) && (currentMesh.mtype == 1) && (serverinfo.amtProvServerMeshId == currentMesh._id)) { x += '<label><input id=dp1lanprov type=checkbox /> ' + "Use for bare-metal LAN activation." + '</label>'; } // Intel AMT LAN provisioning server is active.
x += '<div><span id=dp10passNotify style="font-size:10px"> ' + "* 8 characters, 1 upper, 1 lower, 1 numeric, 1 non-alpha numeric." + '</span></div>'; x += '<div><span id=dp10passNotify style="font-size:10px"> ' + "* 8-16 characters, 1 upper, 1 lower, 1 numeric, 1 non-alpha numeric." + '</span></div>';
setDialogMode(2, "Intel&reg; AMT ACM", 3, showAmtAcmSetupEx, x); setDialogMode(2, "Intel&reg; AMT ACM", 3, showAmtAcmSetupEx, x);
Q('dp1password0').focus(); Q('dp1password0').focus();
validateAmtAcmSetupEx(); validateAmtAcmSetupEx();
@ -5604,10 +5659,10 @@
// QR code agent install // QR code agent install
x += '<div id=agins_qrcode style=display:none;min-height:180px><a id=agins_qrimage_a rel=\"noreferrer noopener\" target=_blank><div id=agins_qrimage style=float:right;margin-left:10px;width:180px;height:180px;cursor:pointer></div></a><div>' + format("To add a mobile device to group \"{0}\", download the MeshAgent application and scan this QR code.", EscapeHtml(mesh.name)) + '</div>'; x += '<div id=agins_qrcode style=display:none;min-height:180px><a id=agins_qrimage_a rel=\"noreferrer noopener\" target=_blank><div id=agins_qrimage style=float:right;margin-left:10px;width:180px;height:180px;cursor:pointer></div></a><div>' + format("To add a mobile device to group \"{0}\", download the MeshAgent application and scan this QR code.", EscapeHtml(mesh.name)) + '</div>';
x += "<table style=width:180px>"; x += '<table style=width:180px>';
x += "<tr><td style=text-align:center><a rel=\"noreferrer noopener\" target=_blank href=\"https://play.google.com/store/apps/details?id=com.meshcentral.agent2\"><img style=cursor:pointer src=\"images/google-play-140.png\" width=140 srcset=\"images/google-play-280.png 2x\" /></a></td></tr>"; x += '<tr><td style=text-align:center><a title="' + "Google Play Store" + '"rel="noreferrer noopener" target=_blank href="https://play.google.com/store/apps/details?id=com.meshcentral.agent2"><img style=cursor:pointer src="images/google-play-140.png" width=140 srcset="images/google-play-280.png 2x" /></a></td></tr>';
x += "<tr><td style=text-align:center><a rel=\"noreferrer noopener\" target=_blank href=\"https://www.amazon.co.uk/gp/product/B097Z4Q7SK/\"><img style=cursor:pointer src=\"images/amazon-appstore-140.png\" width=140 srcset=\"images/amazon-appstore-280.png 2x\" /></a></td></tr>"; x += '<tr><td style=text-align:center><a title="' + "Amazon App Store" + '" rel="noreferrer noopener" target=_blank href="https://www.amazon.co.uk/gp/product/B097Z4Q7SK/"><img style=cursor:pointer src="images/amazon-appstore-140.png" width=140 srcset="images/amazon-appstore-280.png 2x" /></a></td></tr>';
x += "</table>"; x += '</table>';
x += addHtmlValue("Android APK", '<a onclick=downloadFile("meshagents?id=14' + (urlargs.key?('&key=' + urlargs.key):'') + '",null,true) title="' + "APK version of the MeshAgent" + '">' + "APK" + '</a> <img src=images/link4.png height=10 width=10 title="' + "Copy URL to clipboard" + '" style=cursor:pointer onclick=copyAgentUrl("meshagents?id=14&meshid=' + meshid.split('/')[2] + (urlargs.key?('&key=' + urlargs.key):'') + '")>'); x += addHtmlValue("Android APK", '<a onclick=downloadFile("meshagents?id=14' + (urlargs.key?('&key=' + urlargs.key):'') + '",null,true) title="' + "APK version of the MeshAgent" + '">' + "APK" + '</a> <img src=images/link4.png height=10 width=10 title="' + "Copy URL to clipboard" + '" style=cursor:pointer onclick=copyAgentUrl("meshagents?id=14&meshid=' + meshid.split('/')[2] + (urlargs.key?('&key=' + urlargs.key):'') + '")>');
x += '</div>' x += '</div>'
@ -5932,7 +5987,7 @@
setDialogMode(2, "Edit Device Tags", 3, d2groupActionFunctionTagsExec, x); setDialogMode(2, "Edit Device Tags", 3, d2groupActionFunctionTagsExec, x);
} else if (op == 108) { } else if (op == 108) {
// Device notification // Device notification
var x = "<div style=margin-bottom:4px>Perform batch device notification</div>"; var x = '<div style=margin-bottom:4px>'+ "Perform batch device notification" + '</div>';
x += '<select id=d2deviceop style=width:100%;margin-bottom:4px><option value=2>' + "Toast Notification" + '</option><option value=1>' + "Message Box" + '</option><option value=3>' + "Alert Box" + '</option></select>'; x += '<select id=d2deviceop style=width:100%;margin-bottom:4px><option value=2>' + "Toast Notification" + '</option><option value=1>' + "Message Box" + '</option><option value=3>' + "Alert Box" + '</option></select>';
x += '<input id=dp2notifyTitle maxlength=256 placeholder="' + "Title" + '" style=width:100%;box-sizing:border-box;margin-bottom:4px />'; x += '<input id=dp2notifyTitle maxlength=256 placeholder="' + "Title" + '" style=width:100%;box-sizing:border-box;margin-bottom:4px />';
x += '<textarea id=d2notifyMsg style=background-color:#fcf3cf;width:100%;height:140px;resize:none;overflow-y:scroll;box-sizing:border-box;margin-bottom:4px></textarea>'; x += '<textarea id=d2notifyMsg style=background-color:#fcf3cf;width:100%;height:140px;resize:none;overflow-y:scroll;box-sizing:border-box;margin-bottom:4px></textarea>';
@ -6046,7 +6101,7 @@
meshserver.send({ action: 'getDeviceDetails', nodeids: chkNodeIds, tz: tz, tf: new Date().getTimezoneOffset(), l: getLang(), type: 'csv' }); // With details meshserver.send({ action: 'getDeviceDetails', nodeids: chkNodeIds, tz: tz, tf: new Date().getTimezoneOffset(), l: getLang(), type: 'csv' }); // With details
} else { } else {
// Without details // Without details
var csv = "id,name,rname,host,icon,ip,osdesc,state,groupname,conn,pwr,av,update,firewall,bitlocker,avdetails,tags" + '\r\n', r = []; var csv = "id,name,rname,host,icon,ip,osdesc,state,groupname,conn,pwr,av,update,firewall,bitlocker,avdetails,tags,lastbootuptime" + '\r\n', r = [];
for (var i in chkNodeIds) { for (var i in chkNodeIds) {
var n = getNodeFromId(chkNodeIds[i]); var n = getNodeFromId(chkNodeIds[i]);
csv += '"' + n._id.split(',').join('') + '","' + n.name.split(',').join('') + '","' + (n.rname?(n.rname.split(',').join('')):'') + '","' + (n.host?(n.host.split(',').join('')):'') + '","' + n.icon + '","' + (n.ip?n.ip:'') + '","' + (n.osdesc?(n.osdesc.split(',').join('')):'') + '","' + n.state + '","' + meshes[n.meshid].name.split(',').join('') + '","' + (n.conn?n.conn:'') + '","' + (n.pwr?n.pwr:'') + '"'; csv += '"' + n._id.split(',').join('') + '","' + n.name.split(',').join('') + '","' + (n.rname?(n.rname.split(',').join('')):'') + '","' + (n.host?(n.host.split(',').join('')):'') + '","' + n.icon + '","' + (n.ip?n.ip:'') + '","' + (n.osdesc?(n.osdesc.split(',').join('')):'') + '","' + n.state + '","' + meshes[n.meshid].name.split(',').join('') + '","' + (n.conn?n.conn:'') + '","' + (n.pwr?n.pwr:'') + '"';
@ -6072,6 +6127,7 @@
else { else {
csv += ','; csv += ',';
} }
if (typeof n.lastbootuptime == 'number') { csv += ',"' + n.lastbootuptime + '"'; }
csv += '\r\n'; csv += '\r\n';
} }
saveAs(stringToUtf8Blob(csv), "devicelist.csv"); saveAs(stringToUtf8Blob(csv), "devicelist.csv");
@ -7583,7 +7639,7 @@
} }
// Defender for Windows Server // Defender for Windows Server
if(node.defender && !node.wsc) { if(node.defender) {
var y = []; var y = [];
if (node.defender.RealTimeProtection != null) { if (node.defender.RealTimeProtection == true) { y.push("RealTimeProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("RealTimeProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } } if (node.defender.RealTimeProtection != null) { if (node.defender.RealTimeProtection == true) { y.push("RealTimeProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("RealTimeProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } }
if (node.defender.TamperProtected != null) { if (node.defender.TamperProtected == true) { y.push("TamperProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("TamperProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } } if (node.defender.TamperProtected != null) { if (node.defender.TamperProtected == true) { y.push("TamperProtection" + ' - <span style=color:green>' + "On" + '</span>'); } else { y.push("TamperProtection" + ' - <span style=color:red>' + "Off" + '</span>'); } }
@ -7606,7 +7662,12 @@
} }
// Active Users // Active Users
if (node.users && (node.users.length > 0)) { x += addDeviceAttribute(((node.users.length > 1)?"Active Users":"Active User"), EscapeHtml(node.users.join(', '))); } if (node.users && node.users.length > 0) {
var u = node.users.map(function(user) {
return addKeyLinkConditional(EscapeHtml(user), "Locked", (node.lusers && node.lusers.indexOf(user) >= 0));
}).join(', ');
x += addDeviceAttribute((node.users.length > 1 ? "Active Users" : "Active User"), u);
}
// Display device user consent // Display device user consent
if ((node.agent != null) && (node.agent.id != 14) && (node.mtype != 3)) { if ((node.agent != null) && (node.agent.id != 14) && (node.mtype != 3)) {
@ -8193,7 +8254,7 @@
if (noteid == null) { noteid = encodeURIComponentEx('p'+userinfo._id); } if (noteid == null) { noteid = encodeURIComponentEx('p'+userinfo._id); }
var x = '<textarea id=d2devNotes ro=' + readonly + ' noteid=' + noteid + ' readonly style=background-color:#fcf3cf;width:100%;height:200px;resize:none;overflow-y:scroll></textarea>'; var x = '<textarea id=d2devNotes ro=' + readonly + ' noteid=' + noteid + ' readonly style=background-color:#fcf3cf;width:100%;height:200px;resize:none;overflow-y:scroll></textarea>';
if (noteid.startsWith('node%2F%2F')) { x += ' <span style=font-size:10px>' + "Device group notes can be viewed and changed by other device group administrators." + '</span>'; } if (noteid.startsWith('node%2F%2F')) { x += ' <span style=font-size:10px>' + "Device group notes can be viewed and changed by other device group administrators." + '</span>'; }
if (showNotesPanel) { x += ' <span style=font-size:10px><a target=_blank href=\'https://www.markdownguide.org/cheat-sheet/\'>' + "Markdown syntax supported" + '</a></span>'; } if (showNotesPanel === 'true') { x += ' <span style=font-size:10px><a target=_blank href=\'https://www.markdownguide.org/cheat-sheet/\'>' + "Markdown syntax supported" + '</a></span>'; }
setDialogMode(2, "Notes", 3, showNotesEx, x, noteid); setDialogMode(2, "Notes", 3, showNotesEx, x, noteid);
meshserver.send({ action: 'getNotes', id: decodeURIComponent(noteid) }); meshserver.send({ action: 'getNotes', id: decodeURIComponent(noteid) });
} }
@ -8201,7 +8262,7 @@
function showNotesEx(buttons, tag) { function showNotesEx(buttons, tag) {
Q('notesPanelArea').innerHTML = (marked && DOMPurify) ? DOMPurify.sanitize(marked.parse(Q('d2devNotes').value, { breaks: true }), { USE_PROFILES: { html: true } }) : Q('d2devNotes').value; Q('notesPanelArea').innerHTML = (marked && DOMPurify) ? DOMPurify.sanitize(marked.parse(Q('d2devNotes').value, { breaks: true }), { USE_PROFILES: { html: true } }) : Q('d2devNotes').value;
meshserver.send({ action: 'setNotes', id: decodeURIComponent(tag), notes: encodeURIComponentEx(Q('d2devNotes').value) }); meshserver.send({ action: 'setNotes', id: decodeURIComponent(tag), notes: encodeURIComponentEx(Q('d2devNotes').value) });
if (showNotesPanel && Q('d2devNotes').value != '') { QV('notesPanel',true); }else{ QV('notesPanel', false); } if ((showNotesPanel === 'true') && Q('d2devNotes').value != '') { QV('notesPanel',true); }else{ QV('notesPanel', false); }
} }
function openIpKvmRemoteControl(nodeid) { function openIpKvmRemoteControl(nodeid) {
@ -8622,7 +8683,7 @@
// Draw device power bars. The bars are 766px wide. // Draw device power bars. The bars are 766px wide.
function drawDeviceTimeline() { function drawDeviceTimeline() {
if ((currentNode == null) || (xxcurrentView < 10) || (xxcurrentView > 19) || (currentNode.mtype == 3) || (hidePowerTimeline)) return; if ((currentNode == null) || (xxcurrentView < 10) || (xxcurrentView > 19) || (currentNode.mtype == 3) || (hidePowerTimeline === 'true')) return;
var timeline = null, now = Date.now(); var timeline = null, now = Date.now();
if (currentNode._id == powerTimelineNode) { timeline = powerTimeline; } if (currentNode._id == powerTimelineNode) { timeline = powerTimeline; }
@ -9593,6 +9654,7 @@
QH('DeskLatency', latencyStr); QH('DeskLatency', latencyStr);
// Auto-clipboard // Auto-clipboard
if ((((desktop.contype != 4) && (desktopsettings.autoclipboard === true)) || ((desktop.contype == 4) && (desktopsettings.rdpautoclipboard === true))) && (navigator.clipboard != null) && (navigator.clipboard.readText != null)) { if ((((desktop.contype != 4) && (desktopsettings.autoclipboard === true)) || ((desktop.contype == 4) && (desktopsettings.rdpautoclipboard === true))) && (navigator.clipboard != null) && (navigator.clipboard.readText != null)) {
if (Mstsc.browser() == 'firefox') return; // this is needed because firefox pops up a PASTE option every second which is annoying
try { try {
navigator.clipboard.readText().then(function(text) { navigator.clipboard.readText().then(function(text) {
if (desktop == null) return; if (desktop == null) return;
@ -10526,7 +10588,7 @@
function dmousedown(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) { if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mousedown(e); desktop.m.sendKeepAlive(); } else { desktop.m.mousedown(e); } } dblClickDetect(e); } function dmousedown(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) { if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mousedown(e); desktop.m.sendKeepAlive(); } else { desktop.m.mousedown(e); } } dblClickDetect(e); }
function dmouseup(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mouseup(e); desktop.m.sendKeepAlive(); } else { desktop.m.mouseup(e); } } function dmouseup(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mouseup(e); desktop.m.sendKeepAlive(); } else { desktop.m.mouseup(e); } }
function dmousemove(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) { if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mousemove(e); desktop.m.sendKeepAlive(); } else { desktop.m.mousemove(e); } } } function dmousemove(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) { Q('Desk').style.cursor = ''; if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mousemove(e); desktop.m.sendKeepAlive(); } else { desktop.m.mousemove(e); } } else if (!xxdialogMode && desktop != null && !Q('DeskControl').checked) { Q('Desk').style.cursor = 'not-allowed'; } }
function dmousewheel(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) { if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mousewheel(e); desktop.m.sendKeepAlive(); } else { if (desktop.m.mousewheel) { desktop.m.mousewheel(e); } } haltEvent(e); return true; } return false; } function dmousewheel(e) { setSessionActivity(); e.addx = Q('DeskParent').scrollLeft; e.addy = Q('DeskParent').scrollTop; if (!xxdialogMode && desktop != null && Q('DeskControl').checked) { if ((webRtcDesktop != null) && (webRtcDesktop.softdesktop != null)) { webRtcDesktop.softdesktop.m.mousewheel(e); desktop.m.sendKeepAlive(); } else { if (desktop.m.mousewheel) { desktop.m.mousewheel(e); } } haltEvent(e); return true; } return false; }
function drotate(x) { if (!xxdialogMode && desktop != null) { desktop.m.setRotation(desktop.m.rotation + x); deskAdjust(); deskAdjust(); } } function drotate(x) { if (!xxdialogMode && desktop != null) { desktop.m.setRotation(desktop.m.rotation + x); deskAdjust(); deskAdjust(); } }
function stopProcess(id, name) { setDialogMode(2, "Process Control", 3, stopProcessEx, format("Stop process #{0} \"{1}\"?", id, name), id); return false; } function stopProcess(id, name) { setDialogMode(2, "Process Control", 3, stopProcessEx, format("Stop process #{0} \"{1}\"?", id, name), id); return false; }
@ -11305,7 +11367,7 @@
} }
function p13openfilefolder() { function p13openfilefolder() {
setDialogMode(2, "Open File/Folder", 3, p13openfilefolderEx, "Are you sure you want to open this file/folder on the remote devices desktop ?"); setDialogMode(2, "Open File/Folder", 3, p13openfilefolderEx, "Are you sure you want to open this file/folder on the remote devices desktop?");
} }
function p13openfilefolderEx() { function p13openfilefolderEx() {
var openfilefolder = "", checkboxes = document.getElementsByName('fd'); var openfilefolder = "", checkboxes = document.getElementsByName('fd');
@ -12055,6 +12117,7 @@
// Operating System // Operating System
var x = ''; var x = '';
if (node.rname) { x += addDetailItem("Name", EscapeHtml(node.rname), s); } if (node.rname) { x += addDetailItem("Name", EscapeHtml(node.rname), s); }
if (hardware.windows && hardware.windows.osinfo && hardware.windows.osinfo.Description) { x += addDetailItem("Description", EscapeHtml(hardware.windows.osinfo.Description), s); }
if (node.osdesc) { x += addDetailItem("Version", EscapeHtml(node.osdesc), s); } if (node.osdesc) { x += addDetailItem("Version", EscapeHtml(node.osdesc), s); }
if (hardware.windows && hardware.windows.osinfo) { if (hardware.windows && hardware.windows.osinfo) {
var m = hardware.windows.osinfo; var m = hardware.windows.osinfo;
@ -12219,7 +12282,7 @@
} }
if (hardware.network && hardware.network.dns) { if (hardware.network && hardware.network.dns) {
x += '<tr><td><div class=style10 style=border-radius:5px;padding:8px>'; x += '<tr><td><div class=style10 style=border-radius:5px;padding:8px>';
x += addDetailItem("<b>DNS Servers</b>", hardware.network.dns.join(", ")); x += addDetailItem('<b>' + "DNS Servers" + '</b>', hardware.network.dns.join(", "));
x += '</div></td></tr>'; x += '</div></td></tr>';
} }
x += '</table>'; x += '</table>';
@ -12681,7 +12744,19 @@
if (e.shiftKey == true) { meshserver.send({ action: 'uploadagentcore', nodeids: [ consoleNode._id ], type: 'default' }); } // Upload default core if (e.shiftKey == true) { meshserver.send({ action: 'uploadagentcore', nodeids: [ consoleNode._id ], type: 'default' }); } // Upload default core
else if (e.altKey == true) { meshserver.send({ action: 'uploadagentcore', nodeids: [ consoleNode._id ], type: 'clear' }); } // Clear the core else if (e.altKey == true) { meshserver.send({ action: 'uploadagentcore', nodeids: [ consoleNode._id ], type: 'clear' }); } // Clear the core
else if (e.ctrlKey == true) { p15uploadCore2(); } // Upload the core from a file else if (e.ctrlKey == true) { p15uploadCore2(); } // Upload the core from a file
else { setDialogMode(2, "Perform Agent Action", 3, p15uploadCoreEx, addHtmlValue("Action", '<select id=d3coreMode style=width:230px><option value=1>' + "Upload default server core" + '</option><option value=2>' + "Clear the core" + '</option><option value=6>' + "Upload recovery core" + '</option><option value=7>' + "Upload tiny core" + '</option><option value=3>' + "Upload a core file" + '</option><option value=4>' + "Soft disconnect agent" + '</option><option value=5>' + "Hard disconnect agent" + '</option><option value=8>' + "Restart agent service" + '</select>')); } else {
var htmlValue = '<select id=d3coreMode style=width:230px>' +
'<option value=1>' + "Upload default server core" + '</option>' +
'<option value=2>' + "Clear the core" + '</option>' +
'<option value=3>' + "Upload a core file" + '</option>' +
'<option value=4>' + "Soft disconnect agent" + '</option>' +
'<option value=5>' + "Hard disconnect agent" + '</option>' +
'<option value=6>' + "Upload recovery core" + '</option>' +
'<option value=7>' + "Upload tiny core" + '</option>' +
'<option value=8>' + "Restart agent service" + '</option>' +
'<option value=9>' + "Force agent update" + '</option></select>';
setDialogMode(2, "Perform Agent Action", 3, p15uploadCoreEx, addHtmlValue("Action", htmlValue));
}
} }
function p15uploadCoreEx() { function p15uploadCoreEx() {
@ -12709,6 +12784,9 @@
} else if (Q('d3coreMode').value == 8) { } else if (Q('d3coreMode').value == 8) {
// Restart MeshAgent service // Restart MeshAgent service
meshserver.send({ action: 'msg', type: 'console', nodeid: consoleNode._id, value:'service restart' }); meshserver.send({ action: 'msg', type: 'console', nodeid: consoleNode._id, value:'service restart' });
} else if (Q('d3coreMode').value == 9) {
// Update mesh agent
meshserver.send({ action: 'updateAgents', nodeids: [ consoleNode._id ] });
} }
} }
@ -12879,6 +12957,25 @@
}, "When enabled, on each login, you will be given the option to receive a login token to you email account for added security." + '<br /><br /><label><input id=email2facheck type=checkbox ' + (emailU2Fenabled?'checked':'') + '/>' + "Enable email two-factor authentication." + '</label>'); }, "When enabled, on each login, you will be given the option to receive a login token to you email account for added security." + '<br /><br /><label><input id=email2facheck type=checkbox ' + (emailU2Fenabled?'checked':'') + '/>' + "Enable email two-factor authentication." + '</label>');
} }
function account_manageAuthDuo() {
if (xxdialogMode || ((features2 & 0x20000000) == 0)) return;
var duoU2Fenabled = ((userinfo.otpduo == 1));
if (duoU2Fenabled == false) {
setDialogMode(2, "Duo Authentication", 3, function () {
window.location.href = '/add-duo?rurl=' + encodeURIComponentEx(window.location.href) + ((urlargs.key)?('&key=' + urlargs.key):'');
}, "Confirm enabling of Duo 2FA login security. Once enabled you will be given the option to use Duo at login for added security. Click ok to go thru the steps to enable Duo." + '<p style="text-align: center"><img src="images/duo-2fa-250.png"></p>');
} else {
setDialogMode(2, "Duo Authentication", 3, function () {
meshserver.send({ action: 'otpduo', enabled: false });
}, '<p><label><input id=duo2facheck type=checkbox onclick=account_manageAuthDuoConfirm() />' + "Confirm disabling 2FA Duo login security." + '</label></p>' + '<p style="text-align: center"><img src="images/duo-2fa-250-disable.png"></p>');
QE('idx_dlgOkButton', false);
}
}
function account_manageAuthDuoConfirm() {
QE('idx_dlgOkButton', Q('duo2facheck').checked);
}
function account_manageAuthApp() { function account_manageAuthApp() {
if (xxdialogMode || ((features & 4096) == 0)) return; if (xxdialogMode || ((features & 4096) == 0)) return;
if (userinfo.otpsecret == 1) { account_removeOtp(); } else { account_addOtp(); } if (userinfo.otpsecret == 1) { account_removeOtp(); } else { account_addOtp(); }
@ -13376,7 +13473,7 @@
function server_showRestoreDlg() { function server_showRestoreDlg() {
if (xxdialogMode) return false; if (xxdialogMode) return false;
var x = "Restore the server using a backup, <span style=color:red>this will delete the existing server data</span>. Only do this if you know what you are doing." + '<br /><br />'; var x = "Restore the server using a backup," + ' <span style=color:red>' + "this will delete the existing server data." + '</span> ' + "Only do this if you know what you are doing." + '<br /><br />';
x += '<form action="/restoreserver.ashx' + ((urlargs.key)?('?key=' + urlargs.key):'') + '" enctype="multipart/form-data" method="post"><div>'; x += '<form action="/restoreserver.ashx' + ((urlargs.key)?('?key=' + urlargs.key):'') + '" enctype="multipart/form-data" method="post"><div>';
x += '<input type=hidden name=auth value=' + authCookie + '>'; x += '<input type=hidden name=auth value=' + authCookie + '>';
x += '<input id=account_dlgFileInput type=file name=datafile style=width:100% accept=".zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" onchange=account_validateServerRestore()><br /><br />'; x += '<input id=account_dlgFileInput type=file name=datafile style=width:100% accept=".zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" onchange=account_validateServerRestore()><br /><br />';
@ -13808,7 +13905,7 @@
x += addHtmlValue("Unknown password", '<select id=dp20amtbadpass style=width:230px><option value=0>' + "Do nothing" + '</option><option value=1>' + "If in CCM, reactivate Intel&reg; AMT" + '</option></select>'); x += addHtmlValue("Unknown password", '<select id=dp20amtbadpass style=width:230px><option value=0>' + "Do nothing" + '</option><option value=1>' + "If in CCM, reactivate Intel&reg; AMT" + '</option></select>');
x += '</div>'; x += '</div>';
if ((features & 0x400) == 0) { x += addHtmlValue('<span title="' + "Client Initiated Remote Access" + '">' + "CIRA setup" + '</span>', '<select id=dp20amtcira style=width:230px><option value=0>' + "Do nothing" + '</option><option value=1>' + "Don't connect to server" + '</option><option value=2>' + "Connect to server" + '</option></select>'); } if ((features & 0x400) == 0) { x += addHtmlValue('<span title="' + "Client Initiated Remote Access" + '">' + "CIRA setup" + '</span>', '<select id=dp20amtcira style=width:230px><option value=0>' + "Do nothing" + '</option><option value=1>' + "Don't connect to server" + '</option><option value=2>' + "Connect to server" + '</option></select>'); }
x += '<span id=dp10passNotify style="font-size:10px"> ' + "* 8 characters, 1 upper, 1 lower, 1 numeric, 1 non-alpha numeric." + '</span>'; x += '<span id=dp10passNotify style="font-size:10px"> ' + "* 8-16 characters, 1 upper, 1 lower, 1 numeric, 1 non-alpha numeric." + '</span>';
if ((currentMesh.mtype == 2) && (ptype == 2)) { x += '<span style="font-size:10px"> ' + "This policy will not impact devices with Intel&reg; AMT in ACM mode." + '</span>'; } if ((currentMesh.mtype == 2) && (ptype == 2)) { x += '<span style="font-size:10px"> ' + "This policy will not impact devices with Intel&reg; AMT in ACM mode." + '</span>'; }
} }
if (ptype == 0) { x = '<table style=padding-top:4px><tr><td><img style=padding-right:8px src=images/rcheckbox60.png width=60 height=60><td>' + "When this policy is selected, Intel&reg; AMT is not managed by this server. Intel AMT can still be used by manually activating and configuring it." + '</table>'; } if (ptype == 0) { x = '<table style=padding-top:4px><tr><td><img style=padding-right:8px src=images/rcheckbox60.png width=60 height=60><td>' + "When this policy is selected, Intel&reg; AMT is not managed by this server. Intel AMT can still be used by manually activating and configuring it." + '</table>'; }
@ -15240,7 +15337,9 @@
156: "Verified messaging account of user {0}", 156: "Verified messaging account of user {0}",
157: "Removed messaging account of user {0}", 157: "Removed messaging account of user {0}",
158: "Displaying alert box, title=\"{0}\", message=\"{1}\"", 158: "Displaying alert box, title=\"{0}\", message=\"{1}\"",
159: "Device Powered On" 159: "Device Powered On",
160: "Enabled Duo two-factor authentication",
161: "Disabled Duo two-factor authentication"
}; };
var eventsShortMessageId = { var eventsShortMessageId = {
@ -15532,7 +15631,7 @@
if (userdomain != '') { username += ', <span style=color:#26F>' + userdomain + '</span>'; } if (userdomain != '') { username += ', <span style=color:#26F>' + userdomain + '</span>'; }
} }
if ((user.otpsecret > 0) || (user.otphkeys > 0) || ((user.otpekey == 1) && (features & 0x00800000)) || ((user.phone != null) && (features & 0x04000000))) { username += ' <img src="images/key12.png" height=12 width=11 title="' + "2nd factor authentication enabled" + '" style="margin-top:2px" />'; } if ((user.otpsecret > 0) || (user.otphkeys > 0) || ((user.otpekey == 1) && (features & 0x00800000)) || (user.otpduo == 1) || ((user.phone != null) && (features & 0x04000000))) { username += ' <img src="images/key12.png" height=12 width=11 title="' + "2nd factor authentication enabled" + '" style="margin-top:2px" />'; }
if (user.phone != null) { username += ' <img src="images/phone12.png" height=12 width=7 title="' + "Verified phone number" + '" style="margin-top:2px" />'; } if (user.phone != null) { username += ' <img src="images/phone12.png" height=12 width=7 title="' + "Verified phone number" + '" style="margin-top:2px" />'; }
if ((user.siteadmin != null) && ((user.siteadmin & 32) != 0) && (user.siteadmin != 0xFFFFFFFF)) { username += ' <img src="images/padlock12.png" height=12 width=8 title="' + "Account is locked" + '" style="margin-top:2px" />'; } if ((user.siteadmin != null) && ((user.siteadmin & 32) != 0) && (user.siteadmin != 0xFFFFFFFF)) { username += ' <img src="images/padlock12.png" height=12 width=8 title="' + "Account is locked" + '" style="margin-top:2px" />'; }
if ((user.msghandle != null) && (features2 & 0x02000000)) { username += ' <img src="images/messaging12.png" height=12 width=12 title="' + "Verified messaging account" + '" style="margin-top:2px" />'; } if ((user.msghandle != null) && (features2 & 0x02000000)) { username += ' <img src="images/messaging12.png" height=12 width=12 title="' + "Verified messaging account" + '" style="margin-top:2px" />'; }
@ -15834,7 +15933,7 @@
} }
function p4downloadUserInfoCSV() { function p4downloadUserInfoCSV() {
var csv = "id, name, email, creation, lastlogin, groups, authfactors, siteadmin, useradmin, locked" + '\r\n'; var csv = "id,name,email,creation,lastlogin,groups,authfactors,siteadmin,useradmin,locked" + '\r\n';
for (var i in users) { for (var i in users) {
var multiFactor = false, factors = []; var multiFactor = false, factors = [];
if ((users[i].otpsecret > 0) || (users[i].otphkeys > 0)) { if ((users[i].otpsecret > 0) || (users[i].otphkeys > 0)) {
@ -16715,12 +16814,13 @@
} }
var multiFactor = 0; var multiFactor = 0;
if ((user.otpsecret > 0) || (user.otphkeys > 0) || (user.otpekey > 0)) { if ((user.otpsecret > 0) || (user.otphkeys > 0) || (user.otpekey > 0) || (user.otpduo > 0)) {
multiFactor = 1; multiFactor = 1;
var factors = []; var factors = [];
if (user.otpsecret > 0) { factors.push("Authentication App"); } if (user.otpsecret > 0) { factors.push("Authentication App"); }
if (user.otphkeys > 0) { factors.push("Security Key"); } if (user.otphkeys > 0) { factors.push("Security Key"); }
if (user.otpekey > 0) { factors.push("Email"); } if (user.otpekey > 0) { factors.push("Email"); }
if (user.otpduo > 0) { factors.push("Duo"); }
if (user.otpkeys > 0) { factors.push("Backup Codes"); } if (user.otpkeys > 0) { factors.push("Backup Codes"); }
if (user.otpdev > 0) { factors.push("Device Push"); } if (user.otpdev > 0) { factors.push("Device Push"); }
if ((user.phone != null) && (features & 0x04000000)) { factors.push("SMS"); } if ((user.phone != null) && (features & 0x04000000)) { factors.push("SMS"); }
@ -19127,7 +19227,7 @@
function addLink(x, f) { return '<span tabindex=0 style=cursor:pointer;text-decoration:none onclick=\'' + f + '\' onkeypress="if (event.key==\'Enter\') {' + f + '} ">' + x + ' <img class=hoverButton src=images/link5.png></span>'; } function addLink(x, f) { return '<span tabindex=0 style=cursor:pointer;text-decoration:none onclick=\'' + f + '\' onkeypress="if (event.key==\'Enter\') {' + f + '} ">' + x + ' <img class=hoverButton src=images/link5.png></span>'; }
function addLinkConditional(x, f, c) { if (c) return addLink(x, f); return x; } function addLinkConditional(x, f, c) { if (c) return addLink(x, f); return x; }
function addKeyLink(x, f) { return '<span tabindex=0 style=cursor:pointer;text-decoration:none onclick=' + f + ' onkeypress="if (event.key==\'Enter\') { ' + f + ' } ">' + x + ' <img class=hoverButton src=images/key16.png></span>'; } function addKeyLink(x, f) { return '<span tabindex=0 style=cursor:pointer;text-decoration:none onclick=' + f + ' onkeypress="if (event.key==\'Enter\') { ' + f + ' } ">' + x + ' <img class=hoverButton src=images/key16.png></span>'; }
function addKeyLinkConditional(x, f, c) { if (c) return addKeyLink(x, f); return x; } function addKeyLinkConditional(x, t, c) { if (c) return '<span title=\'' + t + '\'>' + x + ' <img class=hoverButton src=images/key16.png></span>'; return x }
function haltEvent(e) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); return false; } function haltEvent(e) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); return false; }
function addOption(q, t, i) { var option = document.createElement('option'); option.text = t; option.value = i; Q(q).add(option); } function addOption(q, t, i) { var option = document.createElement('option'); option.text = t; option.value = i; Q(q).add(option); }
function passwordcheck(p) { return (p.length > 7) && (/\d/.test(p)) && (/[a-z]/.test(p)) && (/[A-Z]/.test(p)) && (/\W/.test(p)); } function passwordcheck(p) { return (p.length > 7) && (/\d/.test(p)) && (/[a-z]/.test(p)) && (/[A-Z]/.test(p)) && (/\W/.test(p)); }

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more