Skip to content

Commit bf63e26

Browse files
committed
feat(init): sync the clock at boot and report it in status
Signed-off-by: Bugs5382 <12115015+Bugs5382@users.noreply.github.com>
1 parent f52f463 commit bf63e26

9 files changed

Lines changed: 501 additions & 4 deletions

File tree

‎cmd/cryptosctl/cli_test.go‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import (
3535
"testing"
3636
"time"
3737

38+
"google.golang.org/protobuf/types/known/durationpb"
3839
"google.golang.org/protobuf/types/known/timestamppb"
3940

4041
cryptosv1 "github.com/CryptOS-PKI/api/go/cryptos/v1"
@@ -292,3 +293,48 @@ func selfSignedCA(t *testing.T) []byte {
292293
}
293294
return der
294295
}
296+
297+
func TestHumanStatusShowsClock(t *testing.T) {
298+
synced := humanStatus(&cryptosv1.NodeStatus{TimeSync: &cryptosv1.TimeSyncStatus{
299+
State: cryptosv1.TimeSyncState_TIME_SYNC_STATE_SYNCED,
300+
Source: cryptosv1.TimeSource_TIME_SOURCE_MACHINE_CONFIG,
301+
Servers: []string{"time.example.org", "192.0.2.123"},
302+
LastServer: "time.example.org",
303+
LastOffset: durationpb.New(-12500 * time.Microsecond),
304+
Stratum: 2,
305+
LastSync: timestamppb.New(time.Date(2026, 9, 29, 12, 0, 0, 0, time.UTC)),
306+
SteppedAtBoot: true,
307+
}})
308+
for _, want := range []string{
309+
"Clock:", "SYNCED", "MACHINE_CONFIG", "time.example.org", "offset -12.5ms", "stratum 2",
310+
"synced 2026-09-29T12:00:00Z", "stepped at boot",
311+
} {
312+
if !strings.Contains(synced, want) {
313+
t.Errorf("humanStatus missing %q in:\n%s", want, synced)
314+
}
315+
}
316+
317+
unsynced := humanStatus(&cryptosv1.NodeStatus{TimeSync: &cryptosv1.TimeSyncStatus{
318+
State: cryptosv1.TimeSyncState_TIME_SYNC_STATE_UNSYNCED,
319+
Source: cryptosv1.TimeSource_TIME_SOURCE_DHCP_LEASE,
320+
Servers: []string{"192.0.2.123"},
321+
LastError: "timesync: sources disagree",
322+
}})
323+
for _, want := range []string{"UNSYNCED", "DHCP_LEASE", "192.0.2.123", "sources disagree"} {
324+
if !strings.Contains(unsynced, want) {
325+
t.Errorf("humanStatus missing %q in:\n%s", want, unsynced)
326+
}
327+
}
328+
329+
none := humanStatus(&cryptosv1.NodeStatus{TimeSync: &cryptosv1.TimeSyncStatus{
330+
State: cryptosv1.TimeSyncState_TIME_SYNC_STATE_NOT_CONFIGURED,
331+
Source: cryptosv1.TimeSource_TIME_SOURCE_NONE,
332+
}})
333+
if !strings.Contains(none, "NOT_CONFIGURED") || !strings.Contains(none, "hardware clock") {
334+
t.Errorf("humanStatus for no time source:\n%s", none)
335+
}
336+
337+
if bare := humanStatus(&cryptosv1.NodeStatus{}); strings.Contains(bare, "Clock:") {
338+
t.Errorf("humanStatus printed an unreported clock line:\n%s", bare)
339+
}
340+
}

‎cmd/cryptosctl/config.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,10 @@ func newConfigApplyCmd(opts *globalOpts) *cobra.Command {
132132
return err
133133
}
134134
}
135-
if w := cfg.RevocationResolverWarning(); w != "" {
135+
for _, w := range []string{cfg.RevocationResolverWarning(), cfg.NTPResolverWarning(), cfg.TimeSourceWarning()} {
136+
if w == "" {
137+
continue
138+
}
136139
if _, err := fmt.Fprintf(cmd.ErrOrStderr(), "WARNING: %s\n", w); err != nil {
137140
return err
138141
}

‎cmd/cryptosctl/config_test.go‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,3 +206,47 @@ func TestConfigApply_WarnsWhenRevocationHostHasNoResolver(t *testing.T) {
206206
})
207207
}
208208
}
209+
210+
// apply warns when the node has no declared time source, and when a hostname
211+
// time server has no static resolver to find it.
212+
func TestConfigApply_WarnsAboutTimeSource(t *testing.T) {
213+
for _, tc := range []struct {
214+
name string
215+
extra string
216+
wantWarns []string
217+
noWarns []string
218+
}{
219+
{"no ntp servers", "", []string{"network.ntp_servers is empty"}, nil},
220+
{"literal ntp server", " ntp_servers: [10.0.0.123]\n", nil, []string{"ntp_servers"}},
221+
{"hostname ntp server without nameservers", " ntp_servers: [time.example.org]\n", []string{"time.example.org", "network.nameservers"}, []string{"is empty. The node syncs"}},
222+
{"hostname ntp server with nameservers", " ntp_servers: [time.example.org]\n nameservers: [10.0.0.53]\n", nil, []string{"ntp_servers"}},
223+
} {
224+
t.Run(tc.name, func(t *testing.T) {
225+
raw := strings.Replace(string(buildMachineYAMLWithInstall(t, "/dev/vdb")),
226+
" gateway: 10.0.0.1\n", " gateway: 10.0.0.1\n"+tc.extra, 1)
227+
file := filepath.Join(t.TempDir(), "machine.yaml")
228+
if err := os.WriteFile(file, []byte(raw), 0o600); err != nil {
229+
t.Fatal(err)
230+
}
231+
missing := filepath.Join(t.TempDir(), "missing.pem")
232+
cmd := newConfigApplyCmd(&globalOpts{endpoint: "127.0.0.1:1", identityCert: missing, identityKey: missing, trustCert: missing})
233+
stderr := &bytes.Buffer{}
234+
cmd.SetOut(&bytes.Buffer{})
235+
cmd.SetErr(stderr)
236+
cmd.SetArgs([]string{"-f", file})
237+
if err := cmd.Execute(); err == nil {
238+
t.Fatal("expected the dial to fail")
239+
}
240+
for _, w := range tc.wantWarns {
241+
if !strings.Contains(stderr.String(), w) {
242+
t.Errorf("stderr missing %q:\n%s", w, stderr.String())
243+
}
244+
}
245+
for _, w := range tc.noWarns {
246+
if strings.Contains(stderr.String(), w) {
247+
t.Errorf("stderr unexpectedly contains %q:\n%s", w, stderr.String())
248+
}
249+
}
250+
})
251+
}
252+
}

‎cmd/cryptosctl/status.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ func humanStatus(s *cryptosv1.NodeStatus) string {
7272
if r := s.GetResolver(); r != nil {
7373
fmt.Fprintf(&b, "DNS: %s\n", humanResolver(r))
7474
}
75+
if ts := s.GetTimeSync(); ts != nil {
76+
fmt.Fprintf(&b, "Clock: %s\n", humanTimeSync(ts))
77+
}
7578
return b.String()
7679
}
7780

@@ -104,6 +107,33 @@ func humanResolver(r *cryptosv1.ResolverStatus) string {
104107
return line
105108
}
106109

110+
// humanTimeSync renders the time-sync state as one line: the state, the
111+
// source and servers, then either the latest good sync or why the latest
112+
// attempt did not adjust the clock.
113+
func humanTimeSync(ts *cryptosv1.TimeSyncStatus) string {
114+
line := trimEnum(ts.GetState().String(), "TIME_SYNC_STATE_")
115+
if ts.GetSource() == cryptosv1.TimeSource_TIME_SOURCE_NONE {
116+
return line + " (no time source; running on the hardware clock)"
117+
}
118+
line += " " + trimEnum(ts.GetSource().String(), "TIME_SOURCE_")
119+
if sv := ts.GetServers(); len(sv) > 0 {
120+
line += " " + strings.Join(sv, ", ")
121+
}
122+
if ts.GetLastSync() != nil {
123+
line += fmt.Sprintf(" (via %s, offset %v, stratum %d, synced %s",
124+
ts.GetLastServer(), ts.GetLastOffset().AsDuration(), ts.GetStratum(),
125+
ts.GetLastSync().AsTime().UTC().Format(time.RFC3339))
126+
if ts.GetSteppedAtBoot() {
127+
line += ", stepped at boot"
128+
}
129+
line += ")"
130+
}
131+
if e := ts.GetLastError(); e != "" {
132+
line += ": " + e
133+
}
134+
return line
135+
}
136+
107137
// trimEnum strips a proto enum prefix for human display.
108138
func trimEnum(s, prefix string) string {
109139
return strings.TrimPrefix(s, prefix)

‎go.mod‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ module github.com/CryptOS-PKI/cryptos
33
go 1.25.0
44

55
require (
6-
github.com/CryptOS-PKI/api v0.0.0-20260929181434-442c13e13c15
6+
github.com/CryptOS-PKI/api v0.0.0-20260929205700-cc4308e5886b
77
github.com/google/go-tpm v0.9.8
88
github.com/google/go-tpm-tools v0.4.8
99
github.com/spf13/cobra v1.10.2

‎go.sum‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
github.com/CryptOS-PKI/api v0.0.0-20260929181434-442c13e13c15 h1:ZSw1gdY7yy2872QDzCnNfchRPA3+d5Bgm4bYVvNZ55A=
2-
github.com/CryptOS-PKI/api v0.0.0-20260929181434-442c13e13c15/go.mod h1:tmeaYhNoUblqPYYNtTbGBGIUsZ7xLATgLdKq4S33rmE=
1+
github.com/CryptOS-PKI/api v0.0.0-20260929205700-cc4308e5886b h1:8IJpCxaCfWAQ0QddBz/CtolWOBDqA/5U7E9k6QbLDzU=
2+
github.com/CryptOS-PKI/api v0.0.0-20260929205700-cc4308e5886b/go.mod h1:tmeaYhNoUblqPYYNtTbGBGIUsZ7xLATgLdKq4S33rmE=
33
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
44
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
55
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=

‎internal/init/run.go‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,18 @@ func boot(ctx context.Context, shutdown *shutdownRequests) (err error) {
323323
log.Printf("init: resolver: %v", err)
324324
}
325325
done()
326+
begin("clock")
327+
328+
// 6b. Time sync. It needs the network and the resolver (a hostname server)
329+
// and runs before etcd, the listeners and signing, so etcd leases, TLS
330+
// validity and issued dates all start on corrected time. The boot sync is
331+
// bounded and never fails the boot; while a configured source has not
332+
// synced, the CA signer refuses to sign (see wireClockGate). The floor is
333+
// recorded on the way down, before the state volume is closed.
334+
timeSync := startTimeSync(ctx, cfg.Network, paths.Mount)
335+
go timeSync.Run(ctx)
336+
defer timeSync.Shutdown()
337+
done()
326338
begin("embedded etcd")
327339

328340
// 7. Master seed (audit + ceremony signing keys derive from it).
@@ -400,6 +412,7 @@ func boot(ctx context.Context, shutdown *shutdownRequests) (err error) {
400412
return revocationPreflightStatus(cfg.PKI.RevocationBaseURL, preflight)
401413
},
402414
Resolver: func() *cryptosv1.ResolverStatus { return resolver },
415+
TimeSync: timeSync.Status,
403416
})
404417
if err != nil {
405418
return err
@@ -487,6 +500,7 @@ func boot(ctx context.Context, shutdown *shutdownRequests) (err error) {
487500
crlBuilder := revocation.NewCRLBuilder(revStore, crlDur)
488501
ocspResp := revocation.NewOCSPResponder(revStore)
489502
caSigner.WithPreflight(preflight.Ensure).WithRecorder(IssuedRecorder(revStore))
503+
wireClockGate(caSigner, timeSync)
490504
revoker := &nodeRevoker{store: revStore, crlBuilder: crlBuilder, load: keyLoader, issuer: issuerFunc,
491505
chain: func(ctx context.Context) ([][]byte, error) {
492506
id, err := store.Identity(ctx)

‎internal/init/timesync.go‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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

Comments
 (0)