Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
606 lines (542 loc) · 20.4 KB
/
Copy pathmain.go
File metadata and controls
606 lines (542 loc) · 20.4 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
package main
import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
"embed"
"encoding/pem"
"fmt"
"io/fs"
"log/slog"
"net/http"
"os"
"path/filepath"
"github.com/addspin/tlss/check"
"github.com/addspin/tlss/crl"
"github.com/addspin/tlss/crypts"
"github.com/addspin/tlss/middleware"
"github.com/addspin/tlss/models"
"github.com/addspin/tlss/routes"
"github.com/addspin/tlss/utils"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/compress"
"github.com/gofiber/template/html/v2"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/viper"
)
//go:embed template
var templateFS embed.FS
//go:embed static
var staticFS embed.FS
//go:embed configInit.yaml
var defaultConfigInit []byte
const bitSize int = 4096
func main() {
// Создаем первичный конфигурационный файл config.yaml из configInit.yaml
execPath, err := os.Executable()
if err != nil {
slog.Error("Cannot determine executable path", "error", err)
os.Exit(1)
}
execDir := filepath.Dir(execPath)
configPath := filepath.Join(execDir, "config.yaml")
if _, statErr := os.Stat(configPath); os.IsNotExist(statErr) {
if writeErr := os.WriteFile(configPath, defaultConfigInit, 0644); writeErr != nil {
slog.Error("Cannot write default config.yaml", "path", configPath, "error", writeErr)
os.Exit(1)
}
slog.Info("Default config.yaml created", "path", configPath)
}
viper.SetConfigName("config")
viper.SetConfigType("yaml")
// Читаем конфиг
viper.AddConfigPath(".")
viper.AddConfigPath(execDir)
err = viper.ReadInConfig()
if err != nil {
slog.Error("Error reading config file", "error", err)
os.Exit(1)
}
// Настраиваем структурированное логирование
logFile, err := utils.SetupSlogLogger()
if err != nil {
slog.Error("Error setting up logging", "error", err)
// Продолжаем со стандартным логированием
}
if logFile != nil {
defer logFile.Close()
}
database := viper.GetString("database.path")
//---------------------------------------Database initialization
db, err := sqlx.Open("sqlite3", database)
if err != nil {
slog.Error("Database connection error", "error", err)
os.Exit(1)
}
slog.Info("Database connection successful", "database", database)
defer db.Close()
// init
// Создание необходимых директорий если они не существуют
dirs := []string{"db", "root_ca_tlss", "https", "crlFile", "logs"}
for _, dir := range dirs {
err := os.MkdirAll(dir, 0755)
if err != nil {
slog.Error("Error creating directory", "directory", dir, "error", err)
} else {
slog.Debug("Directory created or already exists", "directory", dir)
}
}
// create add_server tables in db (хранит данные серверов)
_, err = db.Exec(models.SchemaServer)
if err != nil {
slog.Error("Error creating server table", "error", err)
}
// create SchemaKey tables in db (хранит данные ключа)
_, err = db.Exec(models.SchemaKey)
if err != nil {
slog.Error("Error creating key table", "error", err)
}
// create SchemaCerts tables in db (хранит данные сертификатов)
_, err = db.Exec(models.SchemaCerts)
if err != nil {
slog.Error("Error creating certs table", "error", err)
}
// create SchemaCA tables in db (хранит данные CA)
_, err = db.Exec(models.SchemaCA)
if err != nil {
slog.Error("Error creating CA table", "error", err)
}
// create SchemaCrlInfoSubCA tables in db (хранит данные CRL подписанных сертификатами Sub CA)
_, err = db.Exec(models.SchemaCrlInfoSubCA)
if err != nil {
slog.Error("Error creating CRL info SubCA table", "error", err)
}
// create SchemaCrlInfoRootCA tables in db (хранит данные CRL подписанных сертификатами Root CA)
_, err = db.Exec(models.SchemaCrlInfoRootCA)
if err != nil {
slog.Error("Error creating CRL info RootCA table", "error", err)
}
// create SchemaCRL tables in db (хранит данные CRL)
_, err = db.Exec(models.SchemaCRL)
if err != nil {
slog.Error("Error creating CRL table", "error", err)
}
// create SchemaSSHKey tables in db (хранит данные ssh ключей)
_, err = db.Exec(models.SchemaSSHKey)
if err != nil {
slog.Error("Error creating SSH key table", "error", err)
}
// create Users tables in db (хранит данные Users)
_, err = db.Exec(models.UsersData)
if err != nil {
slog.Error("Error creating users table", "error", err)
}
// create SchemaEntity tables in db (хранит данные сущностей)
_, err = db.Exec(models.SchemaEntity)
if err != nil {
slog.Error("Error creating entity table", "error", err)
}
// create SchemaEntityCA tables in db (хранит данные сущностей для внешних CA)
_, err = db.Exec(models.SchemaEntityCA)
if err != nil {
slog.Error("Error creating entity CA table", "error", err)
}
// create SchemaCAExt tables in db (хранит данные внешних CA сертификатов)
_, err = db.Exec(models.SchemaCAExt)
if err != nil {
slog.Error("Error creating CA ext table", "error", err)
}
// create SchemaOID tables in db (хранит данные OID)
_, err = db.Exec(models.SchemaOID)
if err != nil {
slog.Error("Error creating OID table", "error", err)
}
// create SchemaUserCerts tables in db (хранит данные пользовательских сертификатов)
_, err = db.Exec(models.SchemaUserCerts)
if err != nil {
slog.Error("Error creating user certs table", "error", err)
}
// create SchemaAPIKey tables in db (хранит API ключи внешних сервисов)
_, err = db.Exec(models.SchemaAPIKey)
if err != nil {
slog.Error("Error creating API keys table", "error", err)
}
// create SchemaESTUser tables in db (хранит пользователей EST для basic auth)
_, err = db.Exec(models.SchemaESTUser)
if err != nil {
slog.Error("Error creating est user table", "error", err)
}
// create SchemaESTCerts tables in db (хранит сертификаты, выпущенные через EST)
_, err = db.Exec(models.SchemaESTCerts)
if err != nil {
slog.Error("Error creating est certs table", "error", err)
}
// Миграция: добавляем колонку key_status в api_keys
db.Exec("ALTER TABLE api_keys ADD COLUMN key_status INTEGER DEFAULT 0")
// Миграция: добавляем колонку signing_ca_id в certs и user_certs
db.Exec("ALTER TABLE certs ADD COLUMN signing_ca_id INTEGER DEFAULT 0")
db.Exec("ALTER TABLE user_certs ADD COLUMN signing_ca_id INTEGER DEFAULT 0")
// Миграция: добавляем колонку passphrase в ssh_key
db.Exec("ALTER TABLE ssh_key ADD COLUMN passphrase TEXT NOT NULL DEFAULT ''")
// db.Exec("UPDATE ssh_key SET passphrase = '' WHERE passphrase IS NULL")
var password, salt []byte
var login string
//проверяем, есть ли в таблице хотя-бы одно значение ключа
var exists bool
err = db.Get(&exists, "SELECT EXISTS (SELECT 1 FROM secret_key)")
if err != nil {
slog.Error("Error checking if secret key exists", "error", err)
os.Exit(1)
}
//если в базе нет ключа, то просим ввести ключ
aes := crypts.Aes{}
if !exists {
// если данные авторизации берутся из конфига, то проверяем, что они не пустые
if viper.GetBool("login.authConfig") {
login = viper.GetString("login.username")
if login == "" {
slog.Error("Login cannot be empty")
os.Exit(1)
}
password = []byte(viper.GetString("login.password"))
if len(password) == 0 {
slog.Error("Password cannot be empty")
os.Exit(1)
}
salt = []byte(viper.GetString("login.salt"))
if len(salt) == 0 {
slog.Error("Salt cannot be empty")
os.Exit(1)
}
} else {
// Init-ввод при первом старте
fmt.Print("Init Login: ")
_, err = fmt.Scanln(&login)
if err != nil {
slog.Error("Error reading login", "error", err)
os.Exit(1)
}
fmt.Print("Init password: ")
_, err = fmt.Scanln(&password)
if err != nil {
slog.Error("Error reading password", "error", err)
os.Exit(1)
}
fmt.Print("Init salt: ")
_, err = fmt.Scanln(&salt)
if err != nil {
slog.Error("Error reading salt", "error", err)
os.Exit(1)
}
if len(password) == 0 || len(salt) == 0 {
slog.Error("Password and salt cannot be empty")
os.Exit(1)
}
}
// Генерируем итоговый пароль через PBKDF2
p := crypts.PWD{}
pwd := p.CreatePWDKeyFromUserInput(password, salt)
// генерируем случайный ключ
key := make([]byte, 32)
_, err := rand.Read(key)
if err != nil {
slog.Error("Error generating random key", "error", err)
os.Exit(1)
}
// шифруем ключ паролем
cryptoKey, err := aes.Encrypt(key, pwd) // cryptoKey - зашифрованный ключ
if err != nil {
slog.Error("Fatal error", "error", err)
os.Exit(1)
}
tx := db.MustBegin()
// записываем в таблицу key зашифрованный ключ
keyInsert := `INSERT INTO secret_key (key_data) VALUES ($1)`
_, err = tx.Exec(keyInsert, cryptoKey)
if err != nil {
slog.Error("Error inserting secret key", "error", err)
os.Exit(1)
}
// записываем в таблицу login владельца (избегаем дубликатов)
loginInsert := `INSERT OR IGNORE INTO users (username) VALUES ($1)`
_, err = tx.Exec(loginInsert, login)
if err != nil {
slog.Error("Error inserting user", "error", err)
os.Exit(1)
}
err = tx.Commit()
if err != nil {
slog.Error("Error committing transaction", "error", err)
os.Exit(1)
}
//расшифровываем и передаем в переменную ключ
var keyData []models.Key
err = db.Select(&keyData, "SELECT key_data FROM secret_key WHERE id = 1")
if err != nil {
return
}
for _, keyData := range keyData {
decryptKey, err := aes.Decrypt([]byte(keyData.Key), pwd)
if err != nil {
slog.Error("Error decrypting key", "error", err)
os.Exit(1)
}
//записываем расшифрованный ключ в переменную
crypts.AesSecretKey.Key = decryptKey
}
}
// если в базе есть ключ, то получаем логин/пароль/соль для расшифровки ключа
if exists {
// если данные авторизации берутся из конфига, то проверяем, что они не пустые
if viper.GetBool("login.authConfig") {
login = viper.GetString("login.username")
if login == "" {
slog.Error("Login cannot be empty")
os.Exit(1)
}
password = []byte(viper.GetString("login.password"))
if len(password) == 0 {
slog.Error("Password cannot be empty")
os.Exit(1)
}
salt = []byte(viper.GetString("login.salt"))
if len(salt) == 0 {
slog.Error("Salt cannot be empty")
os.Exit(1)
}
// проверяем, что пользователь существует в БД
var userCount int
err = db.Get(&userCount, "SELECT COUNT(1) FROM users WHERE username = ?", login)
if err != nil {
slog.Error("Error checking user existence", "error", err)
os.Exit(1)
}
if userCount == 0 {
slog.Error("Login not found")
os.Exit(1)
}
} else {
fmt.Print("Enter Login: ")
_, err = fmt.Scanln(&login)
if err != nil {
slog.Error("Error reading login", "error", err)
os.Exit(1)
}
if len(login) == 0 {
slog.Error("Login cannot be empty")
os.Exit(1)
}
// проверяем, что пользователь существует в БД
var userCount int
err = db.Get(&userCount, "SELECT COUNT(1) FROM users WHERE username = ?", login)
if err != nil {
slog.Error("Error checking user existence", "error", err)
os.Exit(1)
}
if userCount == 0 {
slog.Error("Login not found")
os.Exit(1)
}
fmt.Print("Enter password: ")
_, err = fmt.Scanln(&password)
if err != nil {
slog.Error("Error reading password", "error", err)
os.Exit(1)
}
if len(password) == 0 {
slog.Error("Password cannot be empty")
os.Exit(1)
}
fmt.Print("Enter salt: ")
_, err = fmt.Scanln(&salt)
if err != nil {
slog.Error("Error reading salt", "error", err)
os.Exit(1)
}
if len(salt) == 0 {
slog.Error("Salt cannot be empty")
os.Exit(1)
}
}
}
// Генерируем итоговый пароль через PBKDF2
p := crypts.PWD{}
pwd := p.CreatePWDKeyFromUserInput(password, salt)
var keyData []models.Key
err = db.Select(&keyData, "SELECT key_data FROM secret_key WHERE id = 1")
if err != nil {
return
}
for _, keyData := range keyData {
decryptKey, err := aes.Decrypt([]byte(keyData.Key), pwd)
if err != nil {
slog.Error("Error decrypting key", "error", err)
os.Exit(1)
}
//записываем расшифрованный ключ в переменную
crypts.AesSecretKey.Key = decryptKey
}
//---------------------------------------Генерируем Default ssh key для подключения к серверам
var testKey models.SSHKey
err = db.Get(&testKey, "SELECT * FROM ssh_key WHERE name_ssh_key = ?", "Default")
if err != nil {
privateKey, err := crypts.GeneratePrivateKeyForSSH(bitSize)
if err != nil {
slog.Error("Fatal error", "error", err)
os.Exit(1)
}
keyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
publicKeyBytes, err := crypts.GeneratePublicKeyForSSH(&privateKey.PublicKey)
if err != nil {
slog.Error("Fatal error", "error", err)
os.Exit(1)
}
encryptedKey, err := aes.Encrypt(keyPEM, crypts.AesSecretKey.Key)
if err != nil {
slog.Error("Fatal error", "error", err)
os.Exit(1)
}
// Если записи нет, вставляем новую
_, err = db.Exec("INSERT INTO ssh_key (name_ssh_key, public_key, private_key, key_length, algorithm) VALUES (?, ?, ?, ?, ?)", "Default", string(publicKeyBytes), string(encryptedKey), bitSize, "RSA")
if err != nil {
slog.Error("Fatal error", "error", err)
os.Exit(1)
}
}
// Извлекаем CA из базы данных для использования в разных пакетах
err = crypts.ExtractCA.ExtractSubCA(db)
if err != nil {
slog.Error("Error occurred", "error", err)
} else {
slog.Info("ExtractCA: Intermediate CA certificate and key successfully extracted")
}
//---------------------------------------Start Monitor
TCPInterval := utils.SelectTime(viper.GetString("monitor.unitTCP"), viper.GetInt("monitor.TCPInterval"))
RecreateCertsInterval := utils.SelectTime(viper.GetString("monitor.unitRecreateCerts"), viper.GetInt("monitor.RecreateCertsInterval"))
CheckValidCertsInterval := utils.SelectTime(viper.GetString("monitor.unitCheckValidCerts"), viper.GetInt("monitor.CheckValidCertsInterval"))
go check.Monitore(TCPInterval, RecreateCertsInterval, CheckValidCertsInterval)
//---------------------------------------Start Generate Root and Sub CRL
combinedCRLUpdateInterval := utils.SelectTime(viper.GetString("CAcrl.unit"), viper.GetInt("CAcrl.updateInterval"))
go crl.StartCombinedCRLGeneration(combinedCRLUpdateInterval, db)
// --------------------------------------Start check server
serverInterval := utils.SelectTime(viper.GetString("checkServer.unit"), viper.GetInt("checkServer.checkServerInterval"))
checkTCP := check.StatusCodeTcp{}
go checkTCP.TCPPortAvailable(serverInterval)
//---------------------------------------Start Check valid certs
validationInterval := utils.SelectTime(viper.GetString("certsValidation.unit"), viper.GetInt("certsValidation.certsValidationInterval"))
go check.CheckValidCerts(validationInterval)
//---------------------------------------Start Recreate certs
recreateCertsInterval := utils.SelectTime(viper.GetString("recreateCerts.unit"), viper.GetInt("recreateCerts.recreateCertsInterval"))
go check.RecreateCerts(recreateCertsInterval)
//---------------------------------------Create a new engine Template
// Создаем поддиректорию для шаблонов
templateFiles, err := fs.Sub(templateFS, "template")
if err != nil {
slog.Error("Error creating filesystem for templates", "error", err)
os.Exit(1)
}
// Инициализируем движок шаблонов с встроенными файлами
engine := html.NewFileSystem(http.FS(templateFiles), ".html")
//---------------------------------------Pass the engine to the Views
app := fiber.New(fiber.Config{
Views: engine,
})
//---------------------------------------Compress response
app.Use(compress.New(compress.Config{
Level: compress.LevelBestCompression,
}))
//---------------------------------------Initialize session store
// Инициализируем хранилище сессий на основе протокола из конфига
middleware.InitSessionStore()
// Настраиваем маршруты
routes.Setup(app, staticFS)
// Запуск CRL и OCSP сервера (общий публичный listener)
crlApp := fiber.New()
routes.CRLsetup(crlApp)
routes.OCSPsetup(crlApp)
crlAddress := viper.GetString("app.hostname") + ":" + viper.GetString("app.crl_port")
crlProtocol := viper.GetString("app.crl_protocol")
go func() {
var err error
if crlProtocol == "https" {
slog.Info("Starting HTTPS CRL server", "address", crlAddress)
err = crlApp.Listen(crlAddress, fiber.ListenConfig{
CertFile: viper.GetString("app.certFile"),
CertKeyFile: viper.GetString("app.keyFile"),
})
} else {
slog.Info("Starting HTTP CRL server", "address", crlAddress)
err = crlApp.Listen(crlAddress)
}
if err != nil {
slog.Error("Error starting HTTP CRL server", "error", err)
os.Exit(1)
}
}()
// Запуск EST сервера (всегда TLS с mTLS - RFC 7030 требует TLS)
certFile := viper.GetString("app.certFile")
keyFile := viper.GetString("app.keyFile")
if certFile == "" || keyFile == "" {
slog.Warn("EST server requires TLS but certFile/keyFile are not configured — EST will be unavailable")
} else {
estApp := fiber.New()
routes.ESTsetup(estApp)
// Проверяем, что пул собирается: пустой список CA означает, что mTLS
// не сможет проверить ни одного клиента
if _, err := crypts.BuildESTClientCAPool(db); err != nil {
slog.Error("Error building EST client CA pool", "error", err)
os.Exit(1)
}
estAddress := viper.GetString("app.hostname") + ":" + viper.GetString("app.est_port")
slog.Info("Starting EST mTLS server", "address", estAddress)
go func() {
err := estApp.Listen(estAddress, fiber.ListenConfig{
CertFile: certFile,
CertKeyFile: keyFile,
TLSConfigFunc: func(tlsConfig *tls.Config) {
tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
tlsConfig.ClientCAs = crypts.ESTClientCAPool(db)
// Пул берётся заново на каждое рукопожатие, иначе после
// пересоздания CA клиенты с новыми сертификатами не пройдут
// проверку до перезапуска приложения
tlsConfig.GetConfigForClient = func(*tls.ClientHelloInfo) (*tls.Config, error) {
cfg := tlsConfig.Clone()
cfg.GetConfigForClient = nil // без этого получится рекурсия
cfg.ClientCAs = crypts.ESTClientCAPool(db)
return cfg, nil
}
},
})
if err != nil {
slog.Error("Error starting EST server", "error", err)
os.Exit(1)
}
}()
}
// Запуск основного приложения
if viper.GetString("app.protocol") == "https" {
address := viper.GetString("app.hostname") + ":" + viper.GetString("app.port")
slog.Info("Starting TLSS UI server with HTTPS",
"address", address,
"cert_file", certFile,
"key_file", keyFile)
if err := app.Listen(address, fiber.ListenConfig{
CertFile: certFile,
CertKeyFile: keyFile,
}); err != nil {
slog.Error("Error starting TLSS UI HTTPS server", "error", err)
os.Exit(1)
}
} else {
address := viper.GetString("app.hostname") + ":" + viper.GetString("app.port")
slog.Info("Starting TLSS UI server with HTTP", "address", address)
if err := app.Listen(address); err != nil {
slog.Error("Error starting TLSS UI HTTP server", "error", err)
os.Exit(1)
}
}
}