-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathindex.js
More file actions
264 lines (229 loc) · 8.64 KB
/
index.js
File metadata and controls
264 lines (229 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/* eslint-disable consistent-return */
const common = require('./common');
const updater = require('./updater');
const hooks = require('./hooks');
const commands = require('./commands');
const actions = require('./actions');
const triggers = require('./triggers');
const reports = require('./reports');
const providers = require('./providers');
const {
correctPreyConf, getDataDb, readWithoutVerification,
} = require('./utils/prey-configuration/preyconf');
const { saveToDbKey } = require('../utils/configutil');
const storage = require('./utils/storage');
const { restore } = require('./utils/storage/restore');
const setup = require('./control-panel/setup');
const skippedPermissions = require('../utils/skippedPermissions');
const logo = require('./utils/logo');
const controlPanel = require('./control-panel');
const {
// eslint-disable-next-line camelcase
system, logger, program, exceptions, os_name, os_release,
} = common;
const config = require('../utils/configfile');
const fetchEnvVar = require('../utils/fetch-env-var');
const watchList = ['connection', 'hostname', 'location', 'network', 'power', 'status', 'wifi-on'];
let running = false;
let startedAt = null;
let runningAs = null;
const isRunning = () => running;
const runFromCommandLine = () => {
if (!program.debug) logger.pause();
hooks.on('data', console.log);
hooks.on('error', console.log);
hooks.on('report', console.log);
const parsed = commands.parse(program.run);
if (!parsed) { return console.log('Invalid command.'); }
commands.perform(parsed[1]);
};
const isNetworkError = (err) => {
const codes = ['ENETDOWN', 'ENETUNREACH', 'EADDRINFO', 'ENOTFOUND'];
return codes.indexOf(err.code) !== -1;
};
const connectionDown = () => {
if (!config.getData('auto_connect')) { return false; }
logger.notice('Lost connection. Trying to connect...');
};
const handleError = (err, source) => {
logger.error(err, source);
// no connection
if (isNetworkError(err)) connectionDown();
else if (config.getData('send_crash_reports')) exceptions.send(err);
};
const shutdown = () => {
running = false;
commands.stop_watching();
updater.stop_checking();
logger.debug('Stopping actions.');
actions.stop_all();
logger.debug('Unloading hooks.');
hooks.unload();
logger.debug('Canceling reports.');
reports.cancel_all();
logger.debug('Unwatching triggers.');
triggers.unwatch();
logger.debug('Cleaning up temporary files.');
providers.remove_files();
};
const reload = () => {
logger.warn('Reloading!');
config.load();
};
const writeHeader = () => {
function write(str, color) {
logger.write(logger.paint(str, color));
}
write(`\n${logo}`, 'grey');
const title = `\n PREY ${common.version} spreads its wings!`;
write(title, 'light_red');
write(` Current time: ${startedAt.toString()}`, 'bold');
// eslint-disable-next-line camelcase
write(` Running with PID ${process.pid} as ${runningAs} over Node.js ${process.version} on a ${process.arch}, ${os_name} system (${os_release}) \n`);
logger.debug(JSON.stringify(fetchEnvVar('all')));
};
const boot = () => {
hooks.on('error', handleError);
controlPanel.load(() => {
commands.run_stored();
commands.start_watching();
if (config.getData('auto_update')) updater.check_every(3 * 60 * 60 * 1000);
logger.info('Initialized.');
triggers.watch(watchList);
});
};
const hasDeviceKeyApiKey = (cb) => {
try {
const apiKey = config.getData('control-panel.api_key');
const deviceKey = config.getData('control-panel.device_key');
if (apiKey && apiKey !== '' && (deviceKey === undefined || deviceKey === null || deviceKey === '')) {
setup.start(common, () => {
cb();
});
} else cb();
} catch (exception) {
logger.info(`Error in hasDeviceKeyApiKey: ${exception}`);
cb();
}
};
const getDataFromShouldPreyCFile = (cb) => {
getDataDb('shouldPreyCFile', (errorGetData, dataFromDb) => {
if (errorGetData) return cb(errorGetData, null);
if (dataFromDb && dataFromDb.length > 0) {
return cb(null, dataFromDb[0].value);
}
return cb(null, null);
});
};
const reactToDataFromShouldPreyCFile = (errGetShouldInside, dataShouldInside) => {
if (errGetShouldInside) return;
if (dataShouldInside && dataShouldInside.localeCompare('true') !== 0) {
storage.do('update', {
type: 'keys', id: 'shouldPreyCFile', columns: 'value', values: 'true',
}, (errUpdate) => {
if (errUpdate) logger.error(`Error while updating inside preyConfReconf: ${errUpdate}`);
});
} else if (!dataShouldInside) {
storage.do('set', { type: 'keys', id: 'shouldPreyCFile', data: { value: 'true' } }, (errSetting) => {
if (errSetting) logger.error(`Error while setting preyConfReconf: ${errSetting}`);
});
}
};
const actionForDataWithoutVerification = (errReadWithoutVerification, data) => {
if (errReadWithoutVerification) return;
if (data['control-panel.device_key'] && data['control-panel.api_key']) {
config.setData('control-panel.api_key', data['control-panel.api_key'], () => {
config.setData('control-panel.device_key', data['control-panel.device_key'], () => {
getDataFromShouldPreyCFile(reactToDataFromShouldPreyCFile);
});
});
}
};
const correctDataTimedOut = () => correctPreyConf(config.all(), () => {});
const preyConfReconf = () => {
getDataFromShouldPreyCFile((_err, shouldPreyCFile) => {
if (shouldPreyCFile && shouldPreyCFile.localeCompare('true') === 0) {
setTimeout(correctDataTimedOut, 1000 * 60 * 5);
setInterval(correctDataTimedOut, 1000 * 60 * 30);
} else {
getDataDb('preyconf', (_errorGetData, dataFromDb) => {
if (dataFromDb && dataFromDb.length > 0) {
const preyConfData = JSON.parse(dataFromDb[0].value);
if (preyConfData['control-panel.device_key'] && preyConfData['control-panel.api_key']) {
return getDataFromShouldPreyCFile(reactToDataFromShouldPreyCFile);
}
setInterval(() => {
getDataFromShouldPreyCFile((errGetShould, dataShould) => {
getDataDb('preyconf', (errorGetData, dataFromDbInside) => {
if (errorGetData) return;
if (dataFromDbInside && dataFromDbInside.length > 0) {
const preyConfDataInside = JSON.parse(dataFromDbInside[0].value);
if ((!dataShould || dataShould.localeCompare('false') === 0)
&& preyConfDataInside['control-panel.device_key'] && preyConfDataInside['control-panel.api_key']) {
return getDataFromShouldPreyCFile(reactToDataFromShouldPreyCFile);
}
}
});
if (errGetShould) return;
if (dataShould && dataShould.localeCompare('true') === 0) {
return;
}
readWithoutVerification(actionForDataWithoutVerification);
});
}, 1000 * 30);
}
});
}
});
};
const run = () => {
if (running) return;
running = true;
if (program.run) { return runFromCommandLine(); }
config.load(() => {
skippedPermissions.load(() => {
try {
storage.do('query', { type: 'keys', column: 'id', data: 'settingDeviceKey' }, (err, stored) => {
// eslint-disable-next-line no-useless-return
if (err) return;
if (stored && stored.length > 0) {
const settingDeviceKeyValue = JSON.parse(stored[0].value);
if ((Date.now() - settingDeviceKeyValue.dateTime) > 90000) {
storage.do('del', { type: 'keys', id: 'settingDeviceKey' }, () => {
});
}
}
});
} catch (e) {
logger.warn(`Error deleting settingDeviceKey: ${e.message}`);
}
common.writeFileLoggerRestart((Math.floor(new Date().getTime() / 1000)).toString());
common.countLinesLoggerRestarts();
process.title = 'prx'; // stealth camouflage FTW!
// env.RUNNING_USER is user by the updater to check if it was called by the agent
process.env.RUNNING_USER = system.get_running_user();
runningAs = system.get_running_user();
startedAt = new Date();
writeHeader();
if (config.getData('auto_update') === false) return boot();
preyConfReconf();
try {
hasDeviceKeyApiKey(() => {
updater.check_for_update((err) => {
restore((msg) => {
saveToDbKey('fenixReady', 'true', () => {});
if (typeof msg === 'string') logger.info(msg);
if (err) return boot();
});
});
});
} catch (exception) {
boot();
}
});
});
};
exports.run = run;
exports.reload = reload;
exports.running = isRunning;
exports.shutdown = shutdown;