/
device_manager_file.go
1259 lines (1157 loc) · 36.9 KB
/
device_manager_file.go
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package file
import (
"bytes"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
"github.com/lf-edge/adam/pkg/driver/common"
"github.com/lf-edge/adam/pkg/util"
ax "github.com/lf-edge/adam/pkg/x509"
eveuuid "github.com/lf-edge/eve-api/go/eveuuid"
uuid "github.com/satori/go.uuid"
"google.golang.org/protobuf/proto"
)
const (
// DeviceCertFilename the location in the device-specific directory that contains the device certificate
DeviceCertFilename = "device-certificate.pem"
// DeviceOnboardFilename the location in the device-specific directory that contains the onboarding certificate used
DeviceOnboardFilename = "onboard-certificate.pem"
deviceConfigFilename = "config.json"
deviceAttestCertsFilename = "certs.json"
deviceStorageKeysFilename = "storage-keys.json"
deviceSerialFilename = "serial.txt"
onboardCertFilename = "cert.pem"
onboardCertSerials = "onboard-serials.txt"
deviceOptionsFilename = "options.json"
globalOptionsFilename = "global-options.json"
logDir = "logs"
metricsDir = "metrics"
infoDir = "info"
deviceDir = "device"
onboardDir = "onboard"
requestsDir = "requests"
flowMessageDir = "flow_message"
MB = common.MB
maxLogSizeFile = 100 * MB
maxInfoSizeFile = 100 * MB
maxMetricSizeFile = 100 * MB
maxRequestsSizeFile = 100 * MB
maxAppLogsSizeFile = 100 * MB
maxFlowMessageSizeFile = 100 * MB
fileSplit = 10
)
type ManagedFile struct {
dir string
file *os.File
maxSize int64
currentSize int64
totalSize int64
dirReader *DirReader
}
func (m *ManagedFile) Get(index int) ([]byte, error) {
return nil, errors.New("unsupported")
}
func (m *ManagedFile) Write(b []byte) (int, error) {
if m.file == nil {
f, err := openTimestampFile(m.dir)
if err != nil {
return 0, fmt.Errorf("failed to open file: %v", err)
}
m.file = f
}
written, err := m.file.Write(b)
if err != nil {
return 0, fmt.Errorf("failed to write log: %v", err)
}
m.currentSize += int64(written)
m.totalSize += int64(written)
// do we need to open a new file?
if m.currentSize > m.maxSize/fileSplit {
m.file.Close()
f, err := openTimestampFile(m.dir)
if err != nil {
return 0, fmt.Errorf("failed top open file: %v", err)
}
// use the new log file pointer and reset the size
m.file = f
m.currentSize = 0
}
if m.totalSize > m.maxSize {
// get all of the files from the directory
fi, err := os.ReadDir(m.dir)
if err != nil {
return written, fmt.Errorf("could not read directory %s: %v", m.dir, err)
}
// sort the file names
sort.Slice(fi, func(i int, j int) bool {
return fi[i].Name() < fi[j].Name()
})
for _, f := range fi {
if m.totalSize < m.maxSize {
break
}
filename := path.Join(m.dir, f.Name())
fileInfo, err := os.Stat(filename)
if err != nil {
return written, fmt.Errorf("could not get file info for %s: %v", filename, err)
}
size := fileInfo.Size()
if err := os.Remove(filename); err != nil {
return written, fmt.Errorf("failed to remove %s: %v", filename, err)
}
m.totalSize -= size
}
}
return written, nil
}
func (m *ManagedFile) Reader() (common.ChunkReader, error) {
r := &DirReader{
Path: m.dir,
}
return r, nil
}
// DeviceManager implementation of DeviceManager interface with a directory as the backing store
type DeviceManager struct {
databasePath string
cacheTimeout int
lastUpdate time.Time
// thse are for caching only
onboardCerts map[string]map[string]bool
deviceCerts map[string]uuid.UUID
devices map[uuid.UUID]common.DeviceStorage
maxLogSize int
maxInfoSize int
maxMetricSize int
maxRequestsSize int
maxFlowMessageSize int
maxAppLogsSize int
currentLogFile *os.File
currentInfoFile *os.File
currentMetricFile *os.File
currentRequestsFile *os.File
currentLogFileSize int
currentInfoFileSize int
currentMetricFileSize int
currentRequestsFileSize int
}
// Name return name
func (d *DeviceManager) Name() string {
return "file"
}
// Database return database path
func (d *DeviceManager) Database() string {
return d.databasePath
}
// MaxLogSize return the default maximum log size in bytes for this device manager
func (d *DeviceManager) MaxLogSize() int {
return maxLogSizeFile
}
// MaxInfoSize return the default maximum info size in bytes for this device manager
func (d *DeviceManager) MaxInfoSize() int {
return maxInfoSizeFile
}
// MaxMetricSize return the maximum metrics size in bytes for this device manager
func (d *DeviceManager) MaxMetricSize() int {
return maxMetricSizeFile
}
// MaxRequestsSize return the maximum request logs size in bytes for this device manager
func (d *DeviceManager) MaxRequestsSize() int {
return maxRequestsSizeFile
}
// MaxAppLogsSize return the maximum app logs size in bytes for this device manager
func (d *DeviceManager) MaxAppLogsSize() int {
return maxAppLogsSizeFile
}
// MaxFlowMessageSize return the maximum FlowMessage logs size in bytes for this device manager
func (d *DeviceManager) MaxFlowMessageSize() int {
return maxFlowMessageSizeFile
}
// Init check if a URL is valid and initialize
func (d *DeviceManager) Init(s string, sizes common.MaxSizes) (bool, error) {
// parse the URL
// we accept the following:
// - scheme = file
// - invalid URL (everything is path)
URL, err := url.Parse(s)
if err != nil {
return false, err
}
if URL.Scheme != "file" && URL.Scheme != "" {
return false, nil
}
fi, err := os.Stat(s)
if err == nil && !fi.IsDir() {
return false, fmt.Errorf("database path %s exists and is not a directory", s)
}
// we use MkdirAll, since we are willing to continue if the directory already exists; we only error if we cannot make it
err = os.MkdirAll(s, 0755)
if err != nil {
return false, fmt.Errorf("could not create database path %s: %v", s, err)
}
d.databasePath = s
// ensure everything exists
err = d.initializeDB()
if err != nil {
return false, err
}
if sizes.MaxLogSize == 0 {
d.maxLogSize = maxLogSizeFile
} else {
d.maxLogSize = sizes.MaxLogSize
}
if sizes.MaxInfoSize == 0 {
d.maxInfoSize = maxInfoSizeFile
} else {
d.maxInfoSize = sizes.MaxInfoSize
}
if sizes.MaxMetricSize == 0 {
d.maxMetricSize = maxMetricSizeFile
} else {
d.maxMetricSize = sizes.MaxMetricSize
}
if sizes.MaxRequestsSize == 0 {
d.maxRequestsSize = maxRequestsSizeFile
} else {
d.maxRequestsSize = sizes.MaxRequestsSize
}
if sizes.MaxAppLogsSize == 0 {
d.maxAppLogsSize = maxAppLogsSizeFile
} else {
d.maxAppLogsSize = sizes.MaxAppLogsSize
}
if sizes.MaxFlowMessageSize == 0 {
d.maxFlowMessageSize = maxFlowMessageSizeFile
} else {
d.maxFlowMessageSize = sizes.MaxFlowMessageSize
}
return true, nil
}
// SetCacheTimeout set the timeout for refreshing the cache, unused in memory
func (d *DeviceManager) SetCacheTimeout(timeout int) {
d.cacheTimeout = timeout
}
// OnboardCheck see if a particular certificate and serial combination is valid
func (d *DeviceManager) OnboardCheck(cert *x509.Certificate, serial string) error {
// do not accept a nil certificate
if cert == nil {
return fmt.Errorf("invalid nil certificate")
}
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
if err := d.checkValidOnboardSerial(cert, serial); err != nil {
return err
}
if d.getOnboardSerialDevice(cert, serial) != nil {
return &common.UsedSerialError{Err: fmt.Sprintf("serial already used for onboarding certificate: %s", serial)}
}
return nil
}
// OnboardGet get the onboard cert and its serials based on Common Name
func (d *DeviceManager) OnboardGet(cn string) (*x509.Certificate, []string, error) {
if cn == "" {
return nil, nil, fmt.Errorf("empty cn")
}
// easiest to just check the filesystem
onboardDir := d.getOnboardPath(cn)
// does it exist?
found, err := exists(onboardDir)
if err != nil {
return nil, nil, fmt.Errorf("error reading onboard directory: %v", err)
}
if !found {
return nil, nil, &common.NotFoundError{Err: fmt.Sprintf("onboard directory not found %s", onboardDir)}
}
// get the certificate and serials
certPath := path.Join(onboardDir, onboardCertFilename)
cert, err := ax.ReadCert(certPath)
if err != nil {
return nil, nil, fmt.Errorf("error reading onboard certificate at %s: %v", certPath, err)
}
serialPath := path.Join(onboardDir, onboardCertSerials)
serial, err := os.ReadFile(serialPath)
if err != nil {
return nil, nil, fmt.Errorf("error reading onboard serials at %s: %v", serialPath, err)
}
// done
return cert, strings.Fields(string(serial)), nil
}
// OnboardList list all of the known Common Names for onboard
func (d *DeviceManager) OnboardList() ([]string, error) {
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return nil, fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
cns := make([]string, 0)
for certStr := range d.onboardCerts {
certRaw := []byte(certStr)
cert, err := x509.ParseCertificate(certRaw)
if err != nil {
return nil, fmt.Errorf("unable to parse certificate: %v", err)
}
cns = append(cns, cert.Subject.CommonName)
}
return cns, nil
}
// OnboardRemove remove an onboard certificate based on Common Name
func (d *DeviceManager) OnboardRemove(cn string) error {
_, _, err := d.OnboardGet(cn)
if err != nil {
return err
}
onboardPath := d.getOnboardPath(cn)
// remove the directory
err = os.RemoveAll(onboardPath)
if err != nil {
return fmt.Errorf("unable to remove the onboard directory: %v", err)
}
// refresh the cache
err = d.refreshCache()
if err != nil {
return fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
return nil
}
// OnboardClear remove all onboarding certs
func (d *DeviceManager) OnboardClear() error {
// remove the directory and clear the cache
onboardPath := path.Join(d.databasePath, onboardDir)
candidates, err := os.ReadDir(onboardPath)
if err != nil {
return fmt.Errorf("unable to read onboarding certificates at %s: %v", onboardPath, err)
}
// remove each directory
for _, fi := range candidates {
// we only are interested in directories
if !fi.IsDir() {
continue
}
name := fi.Name()
f := path.Join(onboardPath, name)
err = os.RemoveAll(f)
if err != nil {
return fmt.Errorf("unable to remove the onboard directory: %v", err)
}
}
d.onboardCerts = map[string]map[string]bool{}
return nil
}
// DeviceCheckCert see if a particular certificate is a valid registered device certificate
func (d *DeviceManager) DeviceCheckCert(cert *x509.Certificate) (*uuid.UUID, error) {
if cert == nil {
return nil, fmt.Errorf("invalid nil certificate")
}
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return nil, fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
if u, ok := d.deviceCerts[string(cert.Raw)]; ok {
return &u, nil
}
return nil, nil
}
// DeviceCheckCertHash see if a particular certificate hash is a valid registered device certificate
func (d *DeviceManager) DeviceCheckCertHash(hash []byte) (*uuid.UUID, error) {
if hash == nil {
return nil, fmt.Errorf("invalid empty hash")
}
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return nil, fmt.Errorf("unable to refresh certs from Redis: %v", err)
}
for k, u := range d.deviceCerts {
s := sha256.Sum256([]byte(k))
if bytes.Equal(hash, s[:]) {
return &u, nil
}
}
return nil, nil
}
// DeviceRemove remove a device
func (d *DeviceManager) DeviceRemove(u *uuid.UUID) error {
_, _, _, err := d.DeviceGet(u)
if err != nil {
return err
}
// remove the directory
devicePath := d.getDevicePath(*u)
err = os.RemoveAll(devicePath)
if err != nil {
return fmt.Errorf("unable to remove the device directory: %v", err)
}
// refresh the cache
err = d.refreshCache()
if err != nil {
return fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
return nil
}
// DeviceClear remove all devices
func (d *DeviceManager) DeviceClear() error {
// remove the directory and clear the cache
devicePath := path.Join(d.databasePath, deviceDir)
candidates, err := os.ReadDir(devicePath)
if err != nil {
return fmt.Errorf("unable to read device certificates at %s: %v", devicePath, err)
}
// remove each directory
for _, fi := range candidates {
// we only are interested in directories
if !fi.IsDir() {
continue
}
name := fi.Name()
f := path.Join(devicePath, name)
err = os.RemoveAll(f)
if err != nil {
return fmt.Errorf("unable to remove the device directory: %v", err)
}
}
d.deviceCerts = map[string]uuid.UUID{}
d.devices = map[uuid.UUID]common.DeviceStorage{}
return nil
}
// DeviceGet get an individual device by UUID
func (d *DeviceManager) DeviceGet(u *uuid.UUID) (*x509.Certificate, *x509.Certificate, string, error) {
if u == nil {
return nil, nil, "", fmt.Errorf("empty UUID")
}
// easiest to just check the filesystem
devicePath := d.getDevicePath(*u)
// does it exist?
found, err := exists(devicePath)
if err != nil {
return nil, nil, "", fmt.Errorf("error reading device directory: %v", err)
}
if !found {
return nil, nil, "", &common.NotFoundError{Err: fmt.Sprintf("device directory %s not found", onboardDir)}
}
// get the certificate, onboard certificate, serial
certPath := path.Join(devicePath, DeviceCertFilename)
cert, err := ax.ReadCert(certPath)
if err != nil {
return nil, nil, "", fmt.Errorf("error reading device certificate at %s: %v", certPath, err)
}
certPath = path.Join(devicePath, DeviceOnboardFilename)
onboard, err := ax.ReadCert(certPath)
// we can accept not reading the onboard cert
if err != nil && !os.IsNotExist(err) {
return nil, nil, "", fmt.Errorf("error reading onboard certificate at %s: %v", certPath, err)
}
serialPath := path.Join(devicePath, deviceSerialFilename)
serial, err := os.ReadFile(serialPath)
// we can accept not reading the onboard serial
if err != nil && !os.IsNotExist(err) {
return nil, nil, "", fmt.Errorf("error reading device serial at %s: %v", serialPath, err)
}
// done
return cert, onboard, string(serial), nil
}
// DeviceList list all of the known UUIDs for devices
func (d *DeviceManager) DeviceList() ([]*uuid.UUID, error) {
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return nil, fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
ids := make([]uuid.UUID, 0, len(d.devices))
for u := range d.devices {
ids = append(ids, u)
}
pids := make([]*uuid.UUID, 0, len(ids))
for i := range ids {
pids = append(pids, &ids[i])
}
return pids, nil
}
// initDevice initialize all structures for one device
func (d *DeviceManager) initDevice(u uuid.UUID) error {
// create filesystem tree and subdirs for the new device
devicePath := d.getDevicePath(u)
err := os.MkdirAll(devicePath, 0755)
if err != nil {
return fmt.Errorf("error creating new device tree %s: %v", devicePath, err)
}
// create the necessary directories for data uploads
for _, p := range []string{logDir, metricsDir, infoDir, requestsDir} {
cur := path.Join(devicePath, p)
err = os.MkdirAll(cur, 0755)
if err != nil {
return fmt.Errorf("error creating new device sub-path %s: %v", cur, err)
}
}
// save new one to cache - just the serial and onboard; the rest is on disk
if d.deviceCerts == nil {
d.deviceCerts = map[string]uuid.UUID{}
}
if d.devices == nil {
d.devices = map[uuid.UUID]common.DeviceStorage{}
}
if d.maxLogSize == 0 {
d.maxLogSize = maxLogSizeFile
}
if d.maxInfoSize == 0 {
d.maxInfoSize = maxInfoSizeFile
}
if d.maxMetricSize == 0 {
d.maxMetricSize = maxMetricSizeFile
}
d.devices[u] = common.DeviceStorage{
Logs: &ManagedFile{
dir: path.Join(devicePath, logDir),
maxSize: int64(d.maxLogSize),
},
Info: &ManagedFile{
dir: path.Join(devicePath, infoDir),
maxSize: int64(d.maxInfoSize),
},
Metrics: &ManagedFile{
dir: path.Join(devicePath, metricsDir),
maxSize: int64(d.maxMetricSize),
},
Requests: &ManagedFile{
dir: path.Join(devicePath, requestsDir),
maxSize: int64(d.maxRequestsSize),
},
FlowMessage: &ManagedFile{
dir: path.Join(devicePath, flowMessageDir),
maxSize: int64(d.maxFlowMessageSize),
},
AppLogs: map[uuid.UUID]common.BigData{},
}
return nil
}
// DeviceRegister register a new device cert
func (d *DeviceManager) DeviceRegister(unew uuid.UUID, cert, onboard *x509.Certificate, serial string, conf []byte) error {
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
// check if it already exists - this also checks for nil cert
u, err := d.DeviceCheckCert(cert)
if err != nil {
return err
}
// if we found a uuid, then it already exists
if u != nil {
return fmt.Errorf("device already registered")
}
// create filesystem tree and subdirs for the new device
if err := d.initDevice(unew); err != nil {
return fmt.Errorf("error initializing device: %v", err)
}
devicePath := d.getDevicePath(unew)
// save the device certificate
certPath := path.Join(devicePath, DeviceCertFilename)
err = ax.WriteCert(cert.Raw, certPath, true)
if err != nil {
return fmt.Errorf("error saving device certificate to %s: %v", certPath, err)
}
// save the onboard certificate and serial, if provided
certPath = path.Join(devicePath, DeviceOnboardFilename)
if onboard != nil {
err = ax.WriteCert(onboard.Raw, certPath, true)
if err != nil {
return fmt.Errorf("error saving device onboard certificate to %s: %v", certPath, err)
}
}
if serial != "" {
serialPath := path.Join(devicePath, deviceSerialFilename)
err = os.WriteFile(serialPath, []byte(serial), 0644)
if err != nil {
return fmt.Errorf("error saving device serial to %s: %v", serialPath, err)
}
}
// save the base configuration
err = d.writeJSONFile(unew, "", deviceConfigFilename, conf)
if err != nil {
return fmt.Errorf("error saving device config to %s: %v", deviceConfigFilename, err)
}
// save new one to cache - just the serial and onboard; the rest is on disk
d.deviceCerts[string(cert.Raw)] = unew
// this already was initialized in initDevice()
ds := d.devices[unew]
ds.Serial = serial
ds.Onboard = onboard
return nil
}
// OnboardRegister register an onboard cert and update its serials
func (d *DeviceManager) OnboardRegister(cert *x509.Certificate, serial []string) error {
if cert == nil {
return fmt.Errorf("empty nil certificate")
}
certStr := string(cert.Raw)
cn := cert.Subject.CommonName
// ensure everything exists
err := d.initializeDB()
if err != nil {
return err
}
// update the filesystem
// onboard cert file
onboardPath := path.Join(d.databasePath, onboardDir, common.GetOnboardCertName(cn))
// need the directory
err = os.MkdirAll(onboardPath, 0755)
if err != nil {
return fmt.Errorf("unable to create onboard certificate path path %s: %v", onboardPath, err)
}
f := path.Join(onboardPath, onboardCertFilename)
// fix contents!!
err = ax.WriteCert(cert.Raw, f, true)
if err != nil {
return fmt.Errorf("unable to write onboard cert file %s: %v", f, err)
}
// serials file
f = path.Join(onboardPath, onboardCertSerials)
err = os.WriteFile(f, []byte(strings.Join(serial, "\n")), 0644)
if err != nil {
return fmt.Errorf("unable to write onboard serials file %s: %v", f, err)
}
// update the cache
if d.onboardCerts == nil {
d.onboardCerts = map[string]map[string]bool{}
}
serialList := map[string]bool{}
for _, s := range serial {
serialList[s] = true
}
d.onboardCerts[certStr] = serialList
return nil
}
// WriteRequest record a request
func (d *DeviceManager) WriteRequest(u uuid.UUID, b []byte) error {
if dev, ok := d.devices[u]; ok {
dev.AddRequest(b)
return nil
}
return fmt.Errorf("device not found: %s", u)
}
// WriteInfo write an info message
func (d *DeviceManager) WriteInfo(u uuid.UUID, b []byte) error {
// make sure it is not nil
if len(b) < 1 {
return nil
}
// check that the device actually exists
if !d.deviceExists(u) {
return fmt.Errorf("unregistered device UUID: %s", u)
}
dev := d.devices[u]
return dev.AddInfo(b)
}
// WriteLogs write a message of logs
func (d *DeviceManager) WriteLogs(u uuid.UUID, b []byte) error {
// make sure it is not nil
if len(b) < 1 {
return nil
}
// check that the device actually exists
if !d.deviceExists(u) {
return fmt.Errorf("unregistered device UUID: %s", u)
}
dev := d.devices[u]
return dev.AddLogs(b)
}
// appExists return if an app has been created
func (d *DeviceManager) appExists(u, instanceID uuid.UUID) bool {
_, err := os.Stat(d.getAppPath(u, instanceID))
if err != nil {
return false
}
if _, ok := d.devices[u]; !ok {
return false
}
return true
}
// WriteAppInstanceLogs write a message of AppInstanceLogBundle
func (d *DeviceManager) WriteAppInstanceLogs(instanceID uuid.UUID, deviceID uuid.UUID, b []byte) error {
// make sure it is not nil
if len(b) == 0 {
return nil
}
// get the uuid
// check that the device actually exists
if !d.deviceExists(deviceID) {
return fmt.Errorf("unregistered device UUID: %s", deviceID)
}
if !d.appExists(deviceID, instanceID) {
d.devices[deviceID].AppLogs[instanceID] = &ManagedFile{
dir: d.getAppPath(deviceID, instanceID),
maxSize: int64(d.maxAppLogsSize),
}
}
dev := d.devices[deviceID]
return dev.AddAppLog(instanceID, b)
}
// WriteMetrics write a metrics message
func (d *DeviceManager) WriteMetrics(u uuid.UUID, b []byte) error {
// make sure it is not nil
if len(b) < 1 {
return nil
}
// check that the device actually exists
if !d.deviceExists(u) {
return fmt.Errorf("unregistered device UUID: %s", u)
}
dev := d.devices[u]
return dev.AddMetrics(b)
}
// WriteCerts write an attestation certs information
func (d *DeviceManager) WriteCerts(u uuid.UUID, b []byte) error {
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
// look up the device by uuid
_, ok := d.devices[u]
if !ok {
return fmt.Errorf("unregistered device UUID %s", u.String())
}
if len(b) < 1 {
return fmt.Errorf("empty configuration")
}
// save the base configuration
err = d.writeJSONFile(u, "", deviceAttestCertsFilename, b)
if err != nil {
return fmt.Errorf("error saving attestation to %s: %v", deviceAttestCertsFilename, err)
}
return nil
}
// GetCerts retrieve the attest certs for a particular device
func (d *DeviceManager) GetCerts(u uuid.UUID) ([]byte, error) {
// read the config from disk
fullAttestPath := path.Join(d.getDevicePath(u), deviceAttestCertsFilename)
b, err := os.ReadFile(fullAttestPath)
if err != nil {
return nil, fmt.Errorf("could not read certificates from %s: %v", fullAttestPath, err)
}
return b, nil
}
// WriteStorageKeys write storage keys information
func (d *DeviceManager) WriteStorageKeys(u uuid.UUID, b []byte) error {
// refresh cache from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return fmt.Errorf("unable to refresh cache from filesystem: %v", err)
}
// look up the device by uuid
_, ok := d.devices[u]
if !ok {
return fmt.Errorf("unregistered device UUID %s", u.String())
}
if len(b) < 1 {
return fmt.Errorf("empty configuration")
}
err = d.writeJSONFile(u, "", deviceStorageKeysFilename, b)
if err != nil {
return fmt.Errorf("error saving storage keys to %s: %v", deviceStorageKeysFilename, err)
}
return nil
}
// GetStorageKeys retrieve storage keys for a particular device
func (d *DeviceManager) GetStorageKeys(u uuid.UUID) ([]byte, error) {
// read storage keys from disk
fullStorageKeysPath := path.Join(d.getDevicePath(u), deviceStorageKeysFilename)
b, err := os.ReadFile(fullStorageKeysPath)
if err != nil {
return nil, fmt.Errorf("could not read storage keys from %s: %v", fullStorageKeysPath, err)
}
return b, nil
}
// GetConfig retrieve the config for a particular device
func (d *DeviceManager) GetConfig(u uuid.UUID) ([]byte, error) {
// read the config from disk
fullConfigPath := path.Join(d.getDevicePath(u), deviceConfigFilename)
b, err := os.ReadFile(fullConfigPath)
switch {
case err != nil && os.IsNotExist(err):
// create the base file if it does not exist
b = common.CreateBaseConfig(u)
err = d.writeJSONFile(u, "", deviceConfigFilename, b)
if err != nil {
return nil, fmt.Errorf("error saving device config to %s: %v", deviceConfigFilename, err)
}
case err != nil:
return nil, fmt.Errorf("could not read config from %s: %v", fullConfigPath, err)
}
return b, nil
}
// SetConfig set the config for a particular device
func (d *DeviceManager) SetConfig(u uuid.UUID, b []byte) error {
// refresh certs from filesystem, if needed - includes checking if necessary based on timer
err := d.refreshCache()
if err != nil {
return fmt.Errorf("unable to refresh certs from filesystem: %v", err)
}
// look up the device by uuid
_, ok := d.devices[u]
if !ok {
return fmt.Errorf("unregistered device UUID %s", u.String())
}
if len(b) < 1 {
return fmt.Errorf("empty configuration")
}
// save the base configuration
err = d.writeJSONFile(u, "", deviceConfigFilename, b)
if err != nil {
return fmt.Errorf("error saving device config to %s: %v", deviceConfigFilename, err)
}
return nil
}
// refreshCache refresh cache from disk
func (d *DeviceManager) refreshCache() error {
// is it time to update the cache again?
now := time.Now()
if now.Sub(d.lastUpdate).Seconds() < float64(d.cacheTimeout) {
return nil
}
// ensure everything exists
err := d.initializeDB()
if err != nil {
return err
}
// create new vars to hold while we load
d.onboardCerts = make(map[string]map[string]bool)
d.deviceCerts = make(map[string]uuid.UUID)
d.devices = make(map[uuid.UUID]common.DeviceStorage)
// scan the onboard path for all files which end in ".pem" and load them
onboardPath := path.Join(d.databasePath, onboardDir)
candidates, err := os.ReadDir(onboardPath)
if err != nil {
return fmt.Errorf("unable to read onboarding certificates at %s: %v", onboardPath, err)
}
// check each file to make sure it is an onboarding cert
for _, fi := range candidates {
// we only are interested in directories
if !fi.IsDir() {
continue
}
name := fi.Name()
f := path.Join(onboardPath, name, onboardCertFilename)
_, err = os.Stat(f)
// if we cannot list the file, we do not care why, just continue
if err != nil {
continue
}
// read the file
b, err := os.ReadFile(f)
if err != nil {
return fmt.Errorf("unable to read onboard certificate file %s: %v", f, err)
}
// convert into a certificate
certPem, _ := pem.Decode(b)
cert, err := x509.ParseCertificate(certPem.Bytes)
if err != nil {
return fmt.Errorf("unable to convert data from file %s to onboard certificate: %v", f, err)
}
certStr := string(cert.Raw)
d.onboardCerts[certStr] = make(map[string]bool)
// get the serial list
f = path.Join(onboardPath, name, onboardCertSerials)
_, err = os.Stat(f)
// if we cannot list the file, we do not care why, just continue
// we already have the onboard cert saved, so no serials to add
if err != nil {
continue
}
b, err = os.ReadFile(f)
if err != nil {
return fmt.Errorf("unable to read onboard serial file %s: %v", f, err)
}
// convert the []byte to string, split and save
for _, serial := range strings.Fields(string(b)) {
d.onboardCerts[certStr][serial] = true
}
}
// scan the device path for each dir which is the UUID
// and in each one, if a cert exists with the appropriate name, load it
devicePath := path.Join(d.databasePath, deviceDir)
candidates, err = os.ReadDir(devicePath)
if err != nil {
return fmt.Errorf("unable to read devices at %s: %v", devicePath, err)
}
// check each directory to see if it is a valid device directory
for _, fi := range candidates {
// we only are interested in directories
if !fi.IsDir() {
continue
}
name := fi.Name()
// convert the path name to a UUID
u, err := uuid.FromString(name)
if err != nil {
return fmt.Errorf("unable to convert device uuid from directory name %s: %v", name, err)
}
devicePath := d.getDevicePath(u)
// load the device certificate
f := path.Join(devicePath, DeviceCertFilename)
_, err = os.Stat(f)
// if we cannot list the file, we do not care why, just continue
if err != nil {
continue
}
// read the file
b, err := os.ReadFile(f)
if err != nil {
return fmt.Errorf("unable to read device certificate file %s: %v", f, err)
}
// convert into a certificate
certPem, _ := pem.Decode(b)
cert, err := x509.ParseCertificate(certPem.Bytes)
if err != nil {
return fmt.Errorf("unable to convert data from file %s to device certificate: %v", f, err)
}