File: AuthKeysManager.cpp

package info (click to toggle)
veyon 4.9.7%2Brepack1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,028 kB
  • sloc: cpp: 52,043; ansic: 7,307; python: 228; makefile: 222; sh: 48
file content (556 lines) | stat: -rw-r--r-- 15,716 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/*
 * AuthKeysManager.cpp - implementation of AuthKeysManager class
 *
 * Copyright (c) 2018-2025 Tobias Junghans <tobydox@veyon.io>
 *
 * This file is part of Veyon - https://veyon.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program (see COPYING); if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 */

#include <QDir>
#include <QFileInfo>
#include <QRegularExpression>

#include "AuthKeysManager.h"
#include "CommandLineIO.h"
#include "CryptoCore.h"
#include "Filesystem.h"
#include "PlatformFilesystemFunctions.h"
#include "VeyonConfiguration.h"


AuthKeysManager::AuthKeysManager( QObject* parent ) :
	QObject( parent ),
	m_keyTypePrivate( QStringLiteral("private") ),
	m_keyTypePublic( QStringLiteral("public") ),
	m_checkPermissions( tr( "Please check your permissions." ) ),
	m_invalidKeyName( tr( "Key name contains invalid characters!" ) ),
	m_invalidKeyType( tr( "Invalid key type specified! Please specify \"%1\" or \"%2\"." ).arg( m_keyTypePrivate, m_keyTypePublic ) ),
	m_keyDoesNotExist( tr( "Specified key does not exist! Please use the \"list\" command to list all installed keys." ) ),
	m_keysAlreadyExists( tr( "One or more key files already exist! Please delete them using the \"delete\" command." ) ),
	m_resultMessage()
{
}



bool AuthKeysManager::createKeyPair( const QString& name )
{
	if( VeyonCore::isAuthenticationKeyNameValid( name ) == false)
	{
		m_resultMessage = m_invalidKeyName;
		return false;
	}

	const auto privateKeyFileName = VeyonCore::filesystem().privateKeyPath( name );
	const auto publicKeyFileName = VeyonCore::filesystem().publicKeyPath( name );

	if( QFileInfo::exists( privateKeyFileName ) || QFileInfo::exists( publicKeyFileName ) )
	{
		m_resultMessage = m_keysAlreadyExists;
		return false;
	}

	CommandLineIO::print( tr( "Creating new key pair for \"%1\"" ).arg( name ) );

	const auto privateKey = CryptoCore::KeyGenerator().createRSA( CryptoCore::RsaKeySize );
	const auto publicKey = privateKey.toPublicKey();

	if( privateKey.isNull() || publicKey.isNull() )
	{
		m_resultMessage = tr( "Failed to create public or private key!" );
		return false;
	}

	if( writePrivateKeyFile( privateKey, privateKeyFileName ) == false ||
			writePublicKeyFile( publicKey, publicKeyFileName ) == false )
	{
		// m_resultMessage already set by write functions
		return false;
	}

	m_resultMessage = tr( "Newly created key pair has been saved to \"%1\" and \"%2\"." ).arg( privateKeyFileName, publicKeyFileName );

	return true;
}



bool AuthKeysManager::deleteKey( const QString& name, const QString& type )
{
	if( checkKey( name, type ) == false )
	{
		return false;
	}

	const auto keyFileName = keyFilePathFromType( name, type );

	QFile keyFile( keyFileName );
	keyFile.setPermissions( QFile::WriteOwner | QFile::WriteGroup | QFile::WriteOther );

	if( keyFile.remove() == false )
	{
		m_resultMessage = tr( "Could not remove key file \"%1\"!" ).arg( keyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	auto keyFileDirectory = QFileInfo( keyFileName ).absoluteDir();
	auto keyFileBaseDirectory = keyFileDirectory;
	keyFileBaseDirectory.cdUp();

	if( keyFileBaseDirectory.rmdir( keyFileDirectory.dirName() ) == false )
	{
		m_resultMessage = tr( "Could not remove key file directory \"%1\"!" ).arg( keyFileDirectory.path() ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	return true;
}



bool AuthKeysManager::exportKey( const QString& name, const QString& type, const QString& outputFile, bool overwriteExisting )
{
	if( checkKey( name, type ) == false )
	{
		return false;
	}

	const auto keyFileName = keyFilePathFromType( name, type );

	if( VeyonCore::filesystem().ensurePathExists( QFileInfo( outputFile ).path() ) == false )
	{
		m_resultMessage = tr( "Failed to create directory for output file." );
		return false;
	}

	if( overwriteExisting == false && QFileInfo::exists( outputFile ) )
	{
		m_resultMessage = tr( "File \"%1\" already exists." ).arg( outputFile );
		return false;
	}

	if( QFile::copy( keyFileName, outputFile ) == false )
	{
		m_resultMessage = tr( "Failed to write output file." ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	m_resultMessage = tr( "Key \"%1/%2\" has been exported to \"%3\" successfully." ).arg( name, type, outputFile );

	return true;
}



bool AuthKeysManager::importKey( const QString& name, const QString& type, const QString& inputFile )
{
	if( VeyonCore::isAuthenticationKeyNameValid( name ) == false)
	{
		m_resultMessage = m_invalidKeyName;
		return false;
	}

	if( QFileInfo( inputFile ).isReadable() == false )
	{
		m_resultMessage = tr( "Failed read input file." ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	QString keyFileName;

	if( type == m_keyTypePrivate )
	{
		const auto privateKey = CryptoCore::PrivateKey( inputFile );
		if( privateKey.isNull() || privateKey.isPrivate() == false )
		{
			m_resultMessage = tr( "File \"%1\" does not contain a valid private key!" ).arg( inputFile );
			return false;
		}

		keyFileName = VeyonCore::filesystem().privateKeyPath( name );
	}
	else if( type == m_keyTypePublic )
	{
		const auto publicKey = CryptoCore::PublicKey( inputFile );
		if( publicKey.isNull() || publicKey.isPublic() == false )
		{
			m_resultMessage = tr( "File \"%1\" does not contain a valid public key!" ).arg( inputFile );
			return false;
		}

		keyFileName = VeyonCore::filesystem().publicKeyPath( name );
	}
	else
	{
		m_resultMessage = m_invalidKeyType;
		return false;
	}

	if( QFileInfo::exists( keyFileName ) )
	{
		m_resultMessage = m_keysAlreadyExists;
		return false;
	}

	if( VeyonCore::filesystem().ensurePathExists( QFileInfo( keyFileName ).path() ) == false )
	{
		m_resultMessage = tr( "Failed to create directory for key file." ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	if( QFile::copy( inputFile, keyFileName ) == false )
	{
		m_resultMessage = tr( "Failed to write key file \"%1\"." ).arg( keyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	if( setKeyFilePermissions( name, type ) == false )
	{
		m_resultMessage = tr( "Failed to set permissions for key file \"%1\"!" ).arg( keyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	m_resultMessage = tr( "Key \"%1/%2\" has been imported successfully. Please check file permissions of \"%3\" "
						  "in order to prevent unauthorized accesses." ).arg( name, type, keyFileName );

	return true;
}



QStringList AuthKeysManager::listKeys()
{
	const auto privateKeyBaseDir = VeyonCore::filesystem().expandPath( VeyonCore::config().privateKeyBaseDir() );
	const auto privateKeyDirs = QDir( privateKeyBaseDir ).entryList( QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name );

	const auto publicKeyBaseDir = VeyonCore::filesystem().expandPath( VeyonCore::config().publicKeyBaseDir() );
	const auto publicKeyDirs = QDir( publicKeyBaseDir ).entryList( QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name );

	QStringList keys;
	keys.reserve( privateKeyDirs.size() + publicKeyDirs.size() );

	for( const auto& privateKeyDir : privateKeyDirs )
	{
		if( QFileInfo( keyFilePathFromType( privateKeyDir, m_keyTypePrivate) ).isFile() )
		{
			keys.append( QStringLiteral("%1/%2").arg( privateKeyDir, m_keyTypePrivate ) );
		}
	}

	for( const auto& publicKeyDir : publicKeyDirs )
	{
		if( QFileInfo( keyFilePathFromType( publicKeyDir, m_keyTypePublic ) ).isFile() )
		{
			keys.append( QStringLiteral("%1/%2").arg( publicKeyDir, m_keyTypePublic ) );
		}
	}

	std::sort( keys.begin(), keys.end() );

	return keys;
}



bool AuthKeysManager::extractPublicFromPrivateKey( const QString& name )
{
	if( VeyonCore::isAuthenticationKeyNameValid( name ) == false)
	{
		m_resultMessage = m_invalidKeyName;
		return false;
	}

	const auto privateKeyFileName = VeyonCore::filesystem().privateKeyPath( name );
	const auto publicKeyFileName = VeyonCore::filesystem().publicKeyPath( name );

	if( QFileInfo::exists( privateKeyFileName ) == false )
	{
		m_resultMessage = m_keyDoesNotExist;
		return false;
	}

	if( QFileInfo::exists( publicKeyFileName ) )
	{
		m_resultMessage = m_keysAlreadyExists;
		return false;
	}

	const auto publicKey = CryptoCore::PrivateKey( privateKeyFileName ).toPublicKey();
	if( publicKey.isNull() || publicKey.isPublic() == false )
	{
		m_resultMessage = tr( "Failed to convert private key to public key" );
		return false;
	}

	return writePublicKeyFile( publicKey, publicKeyFileName );
}



bool AuthKeysManager::writePrivateKeyFile( const CryptoCore::PrivateKey& privateKey, const QString& privateKeyFileName )
{
	if( VeyonCore::filesystem().ensurePathExists( QFileInfo( privateKeyFileName ).path() ) == false )
	{
		m_resultMessage = tr( "Failed to create directory for private key file \"%1\"." ).arg( privateKeyFileName) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	if( privateKey.toPEMFile( privateKeyFileName ) == false )
	{
		m_resultMessage = tr( "Failed to save private key in file \"%1\"!" ).arg( privateKeyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	if( setPrivateKeyFilePermissions( privateKeyFileName ) == false )
	{
		m_resultMessage = tr( "Failed to set permissions for private key file \"%1\"!" ).arg( privateKeyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	return true;
}



bool AuthKeysManager::writePublicKeyFile( const CryptoCore::PublicKey& publicKey, const QString& publicKeyFileName )
{
	if(	VeyonCore::filesystem().ensurePathExists( QFileInfo( publicKeyFileName ).path() ) == false )
	{
		m_resultMessage = tr( "Failed to create directory for public key file \"%1\"." ).arg( publicKeyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	if( publicKey.toPEMFile( publicKeyFileName ) == false )
	{
		m_resultMessage = tr( "Failed to save public key in file \"%1\"!" ).arg( publicKeyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	if( setPublicKeyFilePermissions( publicKeyFileName ) == false )
	{
		m_resultMessage = tr( "Failed to set permissions for public key file \"%1\"!" ).arg( publicKeyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	return true;
}



QString AuthKeysManager::detectKeyType( const QString& keyFile )
{
	const auto privateKey = CryptoCore::PrivateKey( keyFile );
	if( privateKey.isNull() == false && privateKey.isPrivate()  )
	{
		return m_keyTypePrivate;
	}

	const auto publicKey = CryptoCore::PublicKey( keyFile );
	if( publicKey.isNull() == false && publicKey.isPublic()  )
	{
		return m_keyTypePublic;
	}

	return {};
}



bool AuthKeysManager::setAccessGroup( const QString& key, const QString& group )
{
	const auto nameAndType = key.split( QLatin1Char('/') );
	const auto name = nameAndType.value( 0 );
	const auto type = nameAndType.value( 1 );

	if( checkKey( name, type ) == false )
	{
		return false;
	}

	const auto keyFileName = keyFilePathFromType( name, type );

	if( VeyonCore::platform().filesystemFunctions().setFileOwnerGroup( keyFileName, group ) == false )
	{
		m_resultMessage = tr( "Failed to set owner of key file \"%1\" to \"%2\"." ).
				arg( keyFileName, group ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	if( VeyonCore::platform().filesystemFunctions().
			setFileOwnerGroupPermissions( keyFileName, QFile::ReadOwner | QFile::ReadGroup ) == false )
	{
		m_resultMessage = tr( "Failed to set permissions for key file \"%1\"." ).arg( keyFileName ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	m_resultMessage = tr( "Key \"%1\" is now accessible by user group \"%2\"." ).arg( key, group );

	return true;
}



QString AuthKeysManager::accessGroup( const QString& key )
{
	const auto nameAndType = key.split( QLatin1Char('/') );
	const auto name = nameAndType.value( 0 );
	const auto type = nameAndType.value( 1 );

	if( checkKey( name, type, false ) == false )
	{
		return {};
	}

	return VeyonCore::platform().filesystemFunctions().fileOwnerGroup( keyFilePathFromType( name, type ) );
}



QString AuthKeysManager::keyPairId(const QString& key) // clazy:exclude=qt6-qhash-signature
{
	const auto nameAndType = key.split( QLatin1Char('/') );
	const auto name = nameAndType.value( 0 );
	const auto type = nameAndType.value( 1 );

	if( checkKey( name, type ) == false )
	{
		return tr("<N/A>");
	}

	const auto keyFileName = keyFilePathFromType( name, type );

	const auto privateKey = CryptoCore::PrivateKey( keyFileName );
	if( privateKey.isNull() == false && privateKey.isPrivate()  )
	{
		return QStringLiteral("%1").arg( qHash( privateKey.toPublicKey().toDER() ), 8, 16, QLatin1Char('0') );
	}

	const auto publicKey = CryptoCore::PublicKey( keyFileName );
	if( publicKey.isNull() == false && publicKey.isPublic()  )
	{
		return QStringLiteral("%1").arg( qHash( publicKey.toDER() ), 8, 16, QLatin1Char('0') );
	}

	return QStringLiteral("???");
}



QString AuthKeysManager::exportedKeyFileName( const QString& name, const QString& type )
{
	return QStringLiteral("%1_%2_key.pem").arg( name, type );
}



QString AuthKeysManager::keyNameFromExportedKeyFile( const QString& keyFile )
{
	static const QRegularExpression keyNameRX{QStringLiteral("^(.*)_(.*)_key.pem$")};
	const auto keyNameMatch = keyNameRX.match(QFileInfo(keyFile).fileName());

	if( keyNameMatch.hasMatch() )
	{
		return keyNameMatch.captured( 1 );
	}

	return {};
}



bool AuthKeysManager::checkKey( const QString& name, const QString& type, bool checkIsReadable )
{
	if( VeyonCore::isAuthenticationKeyNameValid( name ) == false )
	{
		m_resultMessage = m_invalidKeyName;
		return false;
	}

	const auto keyFileName = keyFilePathFromType( name, type );

	if( keyFileName.isEmpty() )
	{
		m_resultMessage = m_invalidKeyType;
		return false;
	}

	QFileInfo keyFileInfo( keyFileName );

	if( keyFileInfo.exists() == false )
	{
		m_resultMessage = m_keyDoesNotExist;
		return false;
	}

	if( checkIsReadable && keyFileInfo.isReadable() == false )
	{
		m_resultMessage = tr( "Failed to read key file." ) + QLatin1Char(' ') + m_checkPermissions;
		return false;
	}

	return true;
}



QString AuthKeysManager::keyFilePathFromType( const QString& name, const QString& type ) const
{
	if( type == m_keyTypePrivate )
	{
		return VeyonCore::filesystem().privateKeyPath( name );
	}
	else if( type == m_keyTypePublic )
	{
		return VeyonCore::filesystem().publicKeyPath( name );
	}

	return {};
}



bool AuthKeysManager::setKeyFilePermissions( const QString& name, const QString& type ) const
{
	const auto keyFilePath = keyFilePathFromType( name, type );

	if( type == m_keyTypePrivate )
	{
		return setPrivateKeyFilePermissions( keyFilePath );
	}
	else if( type == m_keyTypePublic )
	{
		return setPublicKeyFilePermissions( keyFilePath );
	}

	return false;
}



bool AuthKeysManager::setPrivateKeyFilePermissions( const QString& fileName ) const
{
	return QFile::setPermissions( fileName, QFile::ReadOwner | QFile::ReadUser | QFile::ReadGroup );
}



bool AuthKeysManager::setPublicKeyFilePermissions( const QString& fileName ) const
{
	return QFile::setPermissions( fileName, QFile::ReadOwner | QFile::ReadUser | QFile::ReadGroup | QFile::ReadOther );
}