-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
284 lines (255 loc) · 11.5 KB
/
cli.js
File metadata and controls
284 lines (255 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#!/usr/bin/env node
import { fileURLToPath, pathToFileURL } from 'url';
const __filename = fileURLToPath(import.meta.url);
import path from 'path';
const __dirname = path.dirname(__filename);
import fs from 'fs';
import { execSync } from 'child_process';
import readline from 'readline';
import crypto from 'crypto';
import { argon2id } from 'hash-wasm';
const isPackaged = !fs.existsSync(path.join(__dirname, 'services', 'databaseService.js'));
let databaseService;
let userDataPath;
if (isPackaged) {
userDataPath = path.join(path.dirname(process.execPath), 'aegis-data');
} else {
userDataPath = path.join(__dirname, 'aegis-data');
}
const dbPath = path.join(userDataPath, 'vault.db');
const metaPath = path.join(userDataPath, 'vault_meta.json');
const hbPath = path.join(userDataPath, '.aegis_hb');
// --- NATIVE SECURITY LOADING ---
let nativeSecurity = null;
try {
const require = (await import('module')).createRequire(import.meta.url);
const addonPaths = [
path.join(__dirname, 'build', 'Release', 'aegis_security.node'),
path.join(path.dirname(process.execPath), 'resources', 'app.asar.unpacked', 'build', 'Release', 'aegis_security.node'),
path.join(__dirname, '..', 'app.asar.unpacked', 'build', 'Release', 'aegis_security.node')
];
for (const p of addonPaths) {
if (fs.existsSync(p)) {
nativeSecurity = require(p);
break;
}
}
} catch (e) {
console.warn('⚠️ Uyarı: Native güvenlik modülü yüklenemedi, donanım kilidi yazılımsal sürümde çalışacak.');
}
function getHardwareBoundSecret(deviceId) {
if (nativeSecurity && fs.existsSync(hbPath)) {
try {
const encrypted = fs.readFileSync(hbPath);
const decrypted = nativeSecurity.unprotectData(encrypted);
if (decrypted) return decrypted;
} catch (e) { }
}
// Software Fallback
return crypto.createHash('sha256').update(deviceId + 'AEGIS-HB-SALT').digest();
}
function getDeviceId() {
try {
let serial = "";
if (process.platform === 'win32') {
serial = execSync('wmic baseboard get serialnumber').toString() +
execSync('wmic cpu get processorid').toString();
} else {
serial = os.hostname() + os.arch() + os.totalmem();
}
return crypto.createHash('sha256').update(serial.replace(/\s/g, '')).digest('hex').toUpperCase().substring(0, 24);
} catch (e) {
return "AEGIS-GENERIC-ID";
}
}
// --- SECURE IO: GUI & TERMINAL ---
async function secureAsk(query) {
return new Promise((resolve) => {
if (process.platform === 'win32') {
try {
const prompt = query.replace('🔑 ', '').replace(':', '');
const cmd = `powershell -Command "$ErrorActionPreference = 'Stop'; [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null; $p = [Microsoft.VisualBasic.Interaction]::InputBox('${prompt}', 'Aegis Vault CLI'); if($p) { $bytes = [System.Text.Encoding]::UTF8.GetBytes($p); [Convert]::ToBase64String($bytes) } else { '' }"`;
const resultB64 = execSync(cmd, { encoding: 'utf8', windowsHide: true }).trim();
if (resultB64) {
resolve(Buffer.from(resultB64, 'base64').toString('utf8'));
return;
}
} catch (e) { }
}
process.stdout.write(query);
const rl = readline.createInterface({ input: process.stdin });
rl.on('line', (l) => { rl.close(); resolve(l); });
});
}
function decryptData(ciphertext, key, iv, tag) {
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
let decrypted = decipher.update(ciphertext, 'binary', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// --- TOTP IMPLEMENTATION FOR 2FA ---
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
function base32Decode(base32) {
base32 = base32.toUpperCase().replace(/=+$/, '');
let bits = 0, value = 0, index = 0;
const output = Buffer.alloc(Math.floor((base32.length * 5) / 8));
for (let i = 0; i < base32.length; i++) {
const charValue = BASE32_ALPHABET.indexOf(base32[i]);
if (charValue === -1) continue;
value = (value << 5) | charValue;
bits += 5;
if (bits >= 8) {
output[index++] = (value >>> (bits - 8)) & 255;
bits -= 8;
}
}
return output;
}
function generateTOTP(key, counter) {
const counterBuffer = Buffer.alloc(8);
counterBuffer.writeUInt32BE(0, 0);
counterBuffer.writeUInt32BE(counter, 4);
const hmac = crypto.createHmac('sha1', key).update(counterBuffer).digest();
const offset = hmac[hmac.length - 1] & 0xf;
const binary = ((hmac[offset] & 0x7f) << 24) | ((hmac[offset + 1] & 0xff) << 16) | ((hmac[offset + 2] & 0xff) << 8) | (hmac[offset + 3] & 0xff);
return (binary % 1000000).toString().padStart(6, '0');
}
async function verifyTOTP(secret, token) {
const key = base32Decode(secret);
const counter = Math.floor(Date.now() / 30000);
for (let i = -1; i <= 1; i++) {
if (generateTOTP(key, counter + i) === token) return true;
}
return false;
}
async function main() {
console.log('\n🛡️ Aegis Vault CLI (v2.0.1 - Hardened)');
console.log('-------------------------------------');
if (!fs.existsSync(dbPath)) {
console.error('❌ Hata: Database dosyası bulunamadı!');
process.exit(1);
}
const args = process.argv.slice(2);
// Komut belirleme - "list get id" veya "get id" formatını destekle
let command = args[0] || 'list';
let subArgs = args.slice(1);
// "list get <id>" formatını düzelt -> "get <id>" olarak işle
if (command === 'list' && args[1] === 'get') {
command = 'get';
subArgs = args.slice(2);
}
// Yardım komutu
if (command === 'help' || command === '-h' || command === '--help') {
console.log('\n📖 Kullanım:');
console.log(' cli.bat list - Tüm kayıtları listele');
console.log(' cli.bat get <id> - Belirli bir kaydın ayrıntılarını göster');
console.log(' cli.bat get <id> --reveal - Şifreyi açık metin olarak göster');
console.log(' cli.bat help - Bu yardım mesajını göster');
console.log('\nÖrnek:');
console.log(" cli.bat get a1b2c3d4 - ID'si a1b2c3d4 ile başlayan kaydı göster");
console.log(" cli.bat get a1b2c3d4 --reveal");
process.exit(0);
}
try {
const dbServicePath = isPackaged
? path.join(path.dirname(process.execPath), 'resources', 'app.asar', 'services', 'databaseService.js')
: path.join(__dirname, 'services', 'databaseService.js');
const finalPath = fs.existsSync(dbServicePath) ? dbServicePath : path.join(__dirname, 'services', 'databaseService.js');
const dbModule = await import(pathToFileURL(finalPath).href);
databaseService = dbModule.databaseService;
} catch (e) {
console.error('❌ Hata: Database servisi yüklenemedi.');
process.exit(1);
}
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
const rawPassword = await secureAsk('🔑 Master Şifrenizi Girin: ');
if (!rawPassword) {
console.error('❌ Hata: Şifre girilmedi.');
process.exit(1);
}
console.log('🔓 Kasa açılıyor...');
try {
const hash = await argon2id({
password: rawPassword,
salt: Buffer.from(meta.salt, 'base64'),
iterations: meta.iterations || 20,
memorySize: 65536,
parallelism: 4,
hashLength: 32,
outputType: 'binary',
});
const masterKeyBuffer = Buffer.from(hash);
const deviceId = getDeviceId();
const hwSecret = getHardwareBoundSecret(deviceId);
const combinedKey = crypto.createHmac('sha256', hwSecret).update(masterKeyBuffer).digest('hex');
databaseService.init(userDataPath, combinedKey);
databaseService.db.prepare('SELECT count(*) FROM config').get();
// --- 2FA KONTROLÜ ---
const twoFaConfigJson = databaseService.getConfig('aegis_2fa_config');
if (twoFaConfigJson) {
console.log('🛡️ İki Faktörlü Doğrulama Aktif');
const configData = JSON.parse(twoFaConfigJson);
const iv = Buffer.from(configData.iv, 'base64');
const ciphertext = Buffer.from(configData.payload, 'base64');
const tag = Buffer.from(configData.tag, 'base64');
try {
const decryptedConfigStr = decryptData(ciphertext, masterKeyBuffer, iv, tag);
const config = JSON.parse(decryptedConfigStr);
const code = await secureAsk('🔑 2FA Kodunu Girin (6 haneli): ');
const isValid = await verifyTOTP(config.secret, code);
if (!isValid) {
console.error('❌ Hata: Geçersiz 2FA kodu. Erişim reddedildi.');
process.exit(1);
}
console.log('✅ 2FA Doğrulandı!');
} catch (err) {
console.error('❌ Hata: 2FA çözme başarısız.');
process.exit(1);
}
}
if (command === 'list') {
const entries = databaseService.getAllEntries();
console.log(`\n✅ Giriş Başarılı! Toplam ${entries.length} kayıt listeleniyor:\n`);
console.log('ID (Kısa) | Kategori | Favori');
console.log('----------|----------|-------');
for (const entry of entries) {
console.log(`${entry.id.slice(0, 8)} | ${entry.category.padEnd(8)} | ${entry.is_favorite ? '⭐' : ' '}`);
}
} else if (command === 'get') {
const id = subArgs[0];
if (!id) {
console.error('❌ Hata: Lütfen bir kayıt ID\'si belirtin.');
console.error(' Örnek: cli.bat get a1b2c3d4');
} else {
const entries = databaseService.getAllEntries();
const entry = entries.find(e => e.id.startsWith(id));
if (!entry) {
console.error('❌ Hata: Kayıt bulunamadı.');
} else {
const iv = Buffer.from(entry.iv, 'base64');
const tag = Buffer.from(entry.tag, 'base64');
const ciphertext = Buffer.from(entry.payload, 'base64');
const decryptedStr = decryptData(ciphertext, masterKeyBuffer, iv, tag);
const data = JSON.parse(decryptedStr);
console.log('\n📄 Kayıt Detayları:');
console.log('------------------');
console.log(`Başlık: ${data.title}`);
console.log(`Kullanıcı:${data.username || 'Yok'}`);
console.log('------------------');
if (data.sensitive.password) {
const reveal = subArgs.includes('--reveal') || subArgs.includes('-r');
console.log(`Şifre: ${reveal ? data.sensitive.password : '******** (Use --reveal to show)'}`);
}
if (data.sensitive.url) console.log(`URL: ${data.sensitive.url}`);
}
}
}
databaseService.close();
process.exit(0);
} catch (err) {
console.error('\n❌ Kimlik Doğrulama Başarısız: Şifre yanlış.');
process.exit(1);
}
}
main();