|
| 1 | +package init |
| 2 | + |
| 3 | +/* |
| 4 | +Apache License 2.0 |
| 5 | +
|
| 6 | +Copyright 2026 Shane |
| 7 | +
|
| 8 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 9 | +you may not use this file except in compliance with the License. |
| 10 | +You may obtain a copy of the License at |
| 11 | +
|
| 12 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | +
|
| 14 | +Unless required by applicable law or agreed to in writing, software |
| 15 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 16 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | +See the License for the specific language governing permissions and |
| 18 | +limitations under the License. |
| 19 | +*/ |
| 20 | + |
| 21 | +import ( |
| 22 | + "bufio" |
| 23 | + "bytes" |
| 24 | + "context" |
| 25 | + "errors" |
| 26 | + "fmt" |
| 27 | + "io/fs" |
| 28 | + "log" |
| 29 | + "log/slog" |
| 30 | + "os" |
| 31 | + "path/filepath" |
| 32 | + "strings" |
| 33 | + "time" |
| 34 | + |
| 35 | + cryptosv1 "github.com/CryptOS-PKI/api/go/cryptos/v1" |
| 36 | + "github.com/CryptOS-PKI/cryptos/internal/buildinfo" |
| 37 | + "github.com/CryptOS-PKI/cryptos/internal/config" |
| 38 | + "github.com/CryptOS-PKI/cryptos/internal/node" |
| 39 | + "github.com/CryptOS-PKI/cryptos/internal/timesync" |
| 40 | +) |
| 41 | + |
| 42 | +const ( |
| 43 | + // ipconfigNTPPath is where the kernel's ip= autoconfiguration reports the |
| 44 | + // NTP servers (DHCP option 42) from its lease: one IPv4 address per line, |
| 45 | + // at most three. They are not in /proc/net/pnp. |
| 46 | + ipconfigNTPPath = "/proc/net/ipconfig/ntp_servers" |
| 47 | + // clockFloorFile holds the clock floor on the state volume. |
| 48 | + clockFloorFile = "clock-floor" |
| 49 | + // timeSyncLogLevel is the node's level for time-sync logs. The node has |
| 50 | + // no level knob; debug keeps each poll (a few lines a minute at most) |
| 51 | + // in the kernel log, where a clock problem is diagnosed. |
| 52 | + timeSyncLogLevel = slog.LevelDebug |
| 53 | +) |
| 54 | + |
| 55 | +// startTimeSync picks the time source, runs the bounded boot sync and returns |
| 56 | +// the engine. The periodic loop is started by the caller. It never fails the |
| 57 | +// boot: a node that cannot reach time runs on its hardware clock, with signing |
| 58 | +// gated until a later poll succeeds. |
| 59 | +func startTimeSync(ctx context.Context, n config.Network, stateMount string) *timesync.Engine { |
| 60 | + logger := slog.New(slog.NewTextHandler(log.Writer(), &slog.HandlerOptions{Level: timeSyncLogLevel})) |
| 61 | + lease, err := readLease(ipconfigNTPPath) |
| 62 | + if err != nil { |
| 63 | + logger.Warn("time sync: could not read the DHCP NTP servers; ignoring the lease", "path", ipconfigNTPPath, "err", err) |
| 64 | + } |
| 65 | + servers, source := timeSourceFor(n, lease) |
| 66 | + logger.Info("time sync source chosen", "source", source.String(), "servers", strings.Join(servers, ",")) |
| 67 | + |
| 68 | + build := parseBuildTime(buildinfo.Get().BuildDate) |
| 69 | + floorPath := filepath.Join(stateMount, clockFloorFile) |
| 70 | + floor, err := timesync.OpenFloor(floorPath, build) |
| 71 | + if err != nil { |
| 72 | + logger.Error("time sync: clock floor unreadable; holding the floor at the image build time", "path", floorPath, "err", err) |
| 73 | + } |
| 74 | + logger.Debug("clock floor loaded", "floor", floor.Get(), "build_time", build) |
| 75 | + |
| 76 | + e, err := timesync.New(timesync.Config{ |
| 77 | + Servers: servers, |
| 78 | + Source: source, |
| 79 | + Clock: timesync.SystemClock(), |
| 80 | + Floor: floor, |
| 81 | + Logger: logger, |
| 82 | + }) |
| 83 | + if err != nil { |
| 84 | + // Only a list longer than MaxServers fails New, and both sources are |
| 85 | + // capped before this point. |
| 86 | + logger.Error("time sync disabled", "err", err) |
| 87 | + e, _ = timesync.New(timesync.Config{Clock: timesync.SystemClock(), Floor: floor, Logger: logger}) |
| 88 | + return e |
| 89 | + } |
| 90 | + e.BootSync(ctx) |
| 91 | + return e |
| 92 | +} |
| 93 | + |
| 94 | +// wireClockGate connects the signer to the time-sync engine: signing waits for |
| 95 | +// the first good sync, and every issued notBefore raises the clock floor. |
| 96 | +func wireClockGate(s *node.CASigner, e *timesync.Engine) *node.CASigner { |
| 97 | + return s.WithClockGate(e.SignAllowed).WithIssuedHook(e.NoteIssued) |
| 98 | +} |
| 99 | + |
| 100 | +// timeSourceFor picks the node's time servers. network.ntp_servers wins when |
| 101 | +// set. Otherwise the servers from the kernel DHCP lease are used. With |
| 102 | +// neither, the source is TIME_SOURCE_NONE. |
| 103 | +func timeSourceFor(n config.Network, lease []byte) ([]string, cryptosv1.TimeSource) { |
| 104 | + if len(n.NTPServers) > 0 { |
| 105 | + return n.NTPServers, cryptosv1.TimeSource_TIME_SOURCE_MACHINE_CONFIG |
| 106 | + } |
| 107 | + if servers := parseIPConfigNTP(lease); len(servers) > 0 { |
| 108 | + return servers, cryptosv1.TimeSource_TIME_SOURCE_DHCP_LEASE |
| 109 | + } |
| 110 | + return nil, cryptosv1.TimeSource_TIME_SOURCE_NONE |
| 111 | +} |
| 112 | + |
| 113 | +// parseIPConfigNTP extracts the NTP servers from the kernel's option 42 file. |
| 114 | +// The lease is input from the network, so each value is validated like a |
| 115 | +// configured literal and anything else is dropped. |
| 116 | +func parseIPConfigNTP(b []byte) []string { |
| 117 | + var servers []string |
| 118 | + seen := map[string]bool{} |
| 119 | + sc := bufio.NewScanner(bytes.NewReader(b)) |
| 120 | + for sc.Scan() { |
| 121 | + a, err := config.ParseNameserver(strings.TrimSpace(sc.Text())) |
| 122 | + if err != nil || seen[a.String()] || len(servers) == config.MaxNTPServers { |
| 123 | + continue |
| 124 | + } |
| 125 | + seen[a.String()] = true |
| 126 | + servers = append(servers, a.String()) |
| 127 | + } |
| 128 | + return servers |
| 129 | +} |
| 130 | + |
| 131 | +// readLease reads the option 42 file; a missing file is no lease. |
| 132 | +func readLease(path string) ([]byte, error) { |
| 133 | + b, err := os.ReadFile(path) |
| 134 | + if errors.Is(err, fs.ErrNotExist) { |
| 135 | + return nil, nil |
| 136 | + } |
| 137 | + if err != nil { |
| 138 | + return nil, fmt.Errorf("init: read %s: %w", path, err) |
| 139 | + } |
| 140 | + return b, nil |
| 141 | +} |
| 142 | + |
| 143 | +// parseBuildTime parses the stamped build date, or returns the zero time for |
| 144 | +// a development build with none, which leaves the floor to the state volume. |
| 145 | +func parseBuildTime(s string) time.Time { |
| 146 | + t, err := time.Parse(time.RFC3339, s) |
| 147 | + if err != nil { |
| 148 | + return time.Time{} |
| 149 | + } |
| 150 | + return t.UTC() |
| 151 | +} |
0 commit comments