-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathmain.go
More file actions
588 lines (507 loc) · 23.3 KB
/
main.go
File metadata and controls
588 lines (507 loc) · 23.3 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
// Copyright 2025 OpenPubkey
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
/*
OPKSSH is a command-line tool that allows users to authenticate with OpenID Connect providers and generate SSH keys for secure access to servers.
*/
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"strings"
"syscall"
"text/tabwriter"
"github.com/openpubkey/opkssh/commands"
config "github.com/openpubkey/opkssh/commands/config"
"github.com/openpubkey/opkssh/internal/sysdetails"
"github.com/openpubkey/opkssh/policy"
"github.com/openpubkey/opkssh/policy/files"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"github.com/thediveo/enumflag/v2"
"golang.org/x/mod/semver"
"golang.org/x/term"
)
var (
// These can be overridden at build time using ldflags. For example:
// go build -v -o /usr/local/bin/opkssh -ldflags "-X main.Version=version"
Version = "unversioned"
)
func main() {
os.Exit(run())
}
func run() int {
rootCmd := &cobra.Command{
SilenceUsage: true,
Use: "opkssh",
Short: "SSH with OpenPubkey",
Version: Version,
Long: `SSH with OpenPubkey
This program allows users to:
- Login and create SSH key pairs using their OpenID Connect identity
- Add policies to auth_id policy files
- Verify OpenPubkey SSH certificates for use with sshd's AuthorizedKeysCommand`,
Example: ` opkssh login
opkssh add root [email protected] https://accounts.google.com`,
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
rootCmd.CompletionOptions.DisableDefaultCmd = true
addCmd := &cobra.Command{
SilenceUsage: true,
Use: "add <principal> <email|sub|group> <issuer>",
Short: "Appends new rule to the policy file",
Long: `Add appends a new policy entry in the auth_id policy file granting SSH access to the specified email or subscriber ID (sub) or group.
It first attempts to write to the system-wide file (/etc/opk/auth_id). If it lacks permissions to update this file it falls back to writing to the user-specific file (~/.opk/auth_id).
Arguments:
principal The target user account (requested principal).
email|sub|group Email address, subscriber ID or group authorized to assume this principal. If using an OIDC group, the argument needs to be in the format of oidc:groups:<groupId>.
issuer OpenID Connect provider (issuer) URL associated with the email/sub/group.
`,
Args: cobra.ExactArgs(3),
Example: ` opkssh add root [email protected] https://accounts.google.com
opkssh add alice 103030642802723203118 https://accounts.google.com
opkssh add developer oidc:groups:developer https://accounts.google.com`,
RunE: func(cmd *cobra.Command, args []string) error {
inputPrincipal := args[0]
inputEmail := args[1]
inputIssuer := args[2]
// Convenience aliases to save user time (who is going to remember the hideous Azure issuer string)
switch inputIssuer {
case "google":
inputIssuer = "https://accounts.google.com"
case "azure", "microsoft":
inputIssuer = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0"
case "gitlab":
inputIssuer = "https://gitlab.com"
case "hello":
inputIssuer = "https://issuer.hello.coop"
}
add := commands.AddCmd{
HomePolicyLoader: policy.NewHomePolicyLoader(),
SystemPolicyLoader: policy.NewSystemPolicyLoader(),
Username: inputPrincipal,
}
policyFilePath, err := add.Run(inputPrincipal, inputEmail, inputIssuer)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to add to policy: %v\n", err)
return err
}
fmt.Fprintf(os.Stdout, "Successfully added new policy to %s\n", policyFilePath)
return nil
},
}
rootCmd.AddCommand(addCmd)
inspectCmd := &cobra.Command{
SilenceUsage: true,
Use: "inspect <path>",
Short: "Inspect and view details of an opkssh generated SSH key",
Example: " opkssh inspect ~/.ssh/id_ecdsa_sk-cert.pub",
RunE: func(cmd *cobra.Command, args []string) error {
keyPathArg := args[0]
inspect := commands.NewInspectCmd(keyPathArg, cmd.OutOrStdout())
if err := inspect.Run(); err != nil {
log.Println("Error executing inspect command:", err)
return err
}
return nil
},
Args: cobra.ExactArgs(1),
}
rootCmd.AddCommand(inspectCmd)
var autoRefreshArg bool
var configPathArg string
var createConfigArg bool
var configureArg bool
var logDirArg string
var providerArg string
var sendAccessTokenArg bool
var disableBrowserOpenArg bool
var printIdTokenArg bool
var printKeyArg bool
var inspectCertArg bool
var verboseArg bool
var keyPathArg string
var keyTypeArg commands.KeyType
var remoteRedirectURIArg string
loginCmd := &cobra.Command{
SilenceUsage: true,
Use: "login [alias]",
Short: "Authenticate with an OpenID Provider to generate an SSH key for opkssh",
Long: `Login creates opkssh SSH keys
Login generates a key pair, then opens a browser to authenticate the user with the OpenID Provider. Upon successful authentication, opkssh creates an SSH public key (~/.ssh/id_ecdsa) containing the user's PK token. By default, this SSH key expires after 24 hours, after which the user must run "opkssh login" again to generate a new key.
Users can then SSH into servers configured to use opkssh as the AuthorizedKeysCommand. The server verifies the PK token and grants access if the token is valid and the user is authorized per the auth_id policy.
Arguments:
alias The provider alias to use. If not specified, the OPKSSH_DEFAULT provider will be used. The aliases are defined by the OPKSSH_PROVIDERS environment variable. The format is <alias>,<issuer>,<client_id>,<client_secret>,<scopes>
`,
Example: ` opkssh login
opkssh login google
opkssh login --provider=<issuer>,<client_id>,<client_secret>,<scopes>`,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
cancel()
}()
var providerAliasArg string
if len(args) > 0 {
providerAliasArg = args[0]
}
if verboseArg {
inspectCertArg = true
}
login := commands.NewLogin(autoRefreshArg, configPathArg, createConfigArg, configureArg, logDirArg,
sendAccessTokenArg, disableBrowserOpenArg, printIdTokenArg, providerArg, printKeyArg, keyPathArg,
providerAliasArg, keyTypeArg, remoteRedirectURIArg, inspectCertArg)
if err := login.Run(ctx); err != nil {
log.Println("Error executing login command:", err)
return err
}
return nil
},
Args: cobra.MaximumNArgs(1),
}
// Define flags for login.
loginCmd.Flags().BoolVar(&autoRefreshArg, "auto-refresh", false, "Automatically refresh PK token after login")
loginCmd.Flags().StringVar(&configPathArg, "config-path", "", "Path to the client config file. Default: ~/.opk/config.yml on linux and %APPDATA%\\.opk\\config.yml on windows")
loginCmd.Flags().BoolVar(&createConfigArg, "create-config", false, "Creates a client config file if it does not exist")
loginCmd.Flags().BoolVar(&configureArg, "configure", false, "Apply changes to ssh config and create ~/.ssh/opkssh directory")
loginCmd.Flags().StringVar(&logDirArg, "log-dir", "", "Directory to write output logs")
loginCmd.Flags().BoolVar(&disableBrowserOpenArg, "disable-browser-open", false, "Set this flag to disable opening the browser. Useful for choosing the browser you want to use")
loginCmd.Flags().BoolVar(&printIdTokenArg, "print-id-token", false, "Set this flag to print out the contents of the id_token. Useful for inspecting claims")
loginCmd.Flags().BoolVar(&sendAccessTokenArg, "send-access-token", false, "Set this flag to send the Access Token as well as the PK Token in the SSH cert. The Access Token is used to call the userinfo endpoint to get claims not included in the ID Token")
loginCmd.Flags().StringVar(&providerArg, "provider", "", "OpenID Provider specification in the format: <issuer>,<client_id> or <issuer>,<client_id>,<client_secret> or <issuer>,<client_id>,<client_secret>,<scopes>")
loginCmd.Flags().BoolVarP(&printKeyArg, "print-key", "p", false, "Print the raw private key and SSH cert to stdout instead of writing them to the filesystem")
loginCmd.Flags().BoolVar(&inspectCertArg, "inspect-cert", false, "Print a human-readable inspection of the generated SSH certificate (public information only)")
loginCmd.Flags().BoolVarP(&verboseArg, "verbose", "v", false, "Enable verbose output")
loginCmd.Flags().StringVarP(&keyPathArg, "private-key-file", "i", "", "Path where private keys is written")
loginCmd.Flags().StringVar(&remoteRedirectURIArg, "remote-redirect-uri", "", "Remote redirect URI used for non-localhost redirects. This is an advanced option for embedding opkssh in server-side logic.")
loginCmd.Flags().VarP(enumflag.New(&keyTypeArg, "Key Type", map[commands.KeyType][]string{commands.ECDSA: {commands.ECDSA.String()}, commands.ED25519: {commands.ED25519.String()}}, enumflag.EnumCaseInsensitive), "key-type", "t", "Type of key to generate")
rootCmd.AddCommand(loginCmd)
var logoutKeyPathArg string
var logoutVerboseArg bool
logoutCmd := &cobra.Command{
SilenceUsage: true,
Use: "logout",
Short: "Remove opkssh-generated SSH keys and certificates",
Long: `Logout removes SSH keys and certificates that were generated by opkssh.
By default it searches the standard SSH key locations (~/.ssh/) and the opkssh identity directory (~/.ssh/opkssh/) for keys generated by opkssh and removes them.
Use the -i flag to remove a specific key pair.`,
Example: ` opkssh logout
opkssh logout -i ~/.ssh/id_ecdsa`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
logout := commands.NewLogoutCmd(logoutKeyPathArg)
if logoutVerboseArg {
logout.Verbosity = 1
}
if err := logout.Run(); err != nil {
log.Println("Error executing logout command:", err)
return err
}
return nil
},
}
logoutCmd.Flags().StringVarP(&logoutKeyPathArg, "private-key-file", "i", "", "Path to the specific private key to remove")
logoutCmd.Flags().BoolVarP(&logoutVerboseArg, "verbose", "v", false, "Print verbose output to stderr")
rootCmd.AddCommand(logoutCmd)
readhomeCmd := &cobra.Command{
SilenceUsage: true,
Use: "readhome <principal>",
Short: "Read the principal's home policy file",
Long: `Read the principal's policy file (/home/<principal>/.opk/auth_id).
You should not call this command directly. It is called by the opkssh verify command as part of the AuthorizedKeysCommand process to read the user's policy (principals) home file (~/.opk/auth_id) with sudoer permissions. This allows us to use an unprivileged user as the AuthorizedKeysCommand user.
`,
Args: cobra.ExactArgs(1),
Example: ` opkssh readhome alice`,
RunE: func(cmd *cobra.Command, args []string) error {
userArg := os.Args[2]
if fileBytes, err := commands.ReadHome(userArg); err != nil {
fmt.Fprintf(os.Stderr, "Failed to read user's home policy file: %v\n", err)
return err
} else {
fmt.Fprint(os.Stdout, string(fileBytes))
return nil
}
},
}
rootCmd.AddCommand(readhomeCmd)
var serverConfigPathArg string
verifyCmd := &cobra.Command{
SilenceUsage: true,
Use: "verify <principal> <cert> <key_type>",
Short: "Verify an SSH key (used by sshd AuthorizedKeysCommand)",
Long: `Verify extracts a PK token from a base64-encoded SSH certificate and verifies it against policy. It expects an allowed provider file at /etc/opk/providers and a user policy file at either /etc/opk/auth_id or ~/.opk/auth_id.
This command is intended to be called by sshd as an AuthorizedKeysCommand:
https://man.openbsd.org/sshd_config#AuthorizedKeysCommand
During installation, opkssh typically adds these lines to /etc/ssh/sshd_config:
AuthorizedKeysCommand /usr/local/bin/opkssh verify %%u %%k %%t
AuthorizedKeysCommandUser opksshuser
Where the tokens in /etc/ssh/sshd_config are defined as:
%%u Target username (requested principal)
%%k Base64-encoded SSH public key (SSH certificate) provided for authentication
%%t Public key type (SSH certificate format, e.g., [email protected])
Verification checks performed:
1. Ensures the PK token is properly formed, signed, and issued by the specified OpenID Provider (OP).
2. Confirms the PK token's issue (iss) and client ID (audience) are listed in the allowed provider file (/etc/opk/providers) and the token is not expired.
3. Validates the identity (email or sub) in the PK token against user policies (/etc/opk/auth_id or ~/.opk/auth_id) to ensure it can assume the requested username (principal).
If all checks pass, Verify authorizes the SSH connection.
Arguments:
principal Target username.
cert Base64-encoded SSH certificate.
key_type SSH certificate key type (e.g., [email protected])`,
Args: cobra.MinimumNArgs(3),
Example: ` opkssh verify root <base64-encoded-cert> [email protected]`,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
// Setup logger
logFilePath := GetLogFilePath()
logFile, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0660) // Owner and group can read/write
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening log file: %v\n", err)
// It could be very difficult to figure out what is going on if the log file was deleted. Hopefully this message saves someone an hour of debugging.
if runtime.GOOS == "windows" {
fmt.Fprintf(os.Stderr, "Check if the log file exists at %v. If it does not, create it and ensure the account running sshd has read/write access (for example, via the file's Security properties or using icacls). The log directory may be under %%ProgramData%%.\n", logFilePath)
} else {
fmt.Fprintf(os.Stderr, "Check if log exists at %v, if it does not create it with permissions: chown root:opksshuser %v; chmod 660 %v\n", logFilePath, logFilePath, logFilePath)
}
} else {
defer logFile.Close()
log.SetOutput(logFile)
}
// Logs if using an unsupported OpenSSH version
checkOpenSSHVersion()
// The "AuthorizedKeysCommand" func is designed to be used by sshd and specified as an AuthorizedKeysCommand
// ref: https://man.openbsd.org/sshd_config#AuthorizedKeysCommand
log.Println(strings.Join(os.Args, " "))
userArg := args[0]
certB64Arg := args[1]
typArg := args[2]
extraArgs := args[3:]
providerPolicyPath := filepath.Join(policy.GetSystemConfigBasePath(), "providers")
providerPolicy, err := policy.NewProviderFileLoader().LoadProviderPolicy(providerPolicyPath)
if err != nil {
log.Printf("Failed to open %s: %v\n", providerPolicyPath, err)
return err
}
printConfigProblems()
log.Println("Providers loaded: ", providerPolicy.ToString())
pktVerifier, err := providerPolicy.CreateVerifier()
if err != nil {
log.Println("Failed to create pk token verifier (likely bad configuration):", err)
return err
}
v := commands.NewVerifyCmd(*pktVerifier, commands.OpkPolicyEnforcerFunc(userArg), serverConfigPathArg)
if err := v.ReadFromServerConfig(); err != nil {
log.Println("Failed to set environment variables in config:", err)
}
if authKey, err := v.AuthorizedKeysCommand(ctx, userArg, typArg, certB64Arg, extraArgs); err != nil {
log.Println("failed to verify:", err)
return err
} else {
log.Println("successfully verified")
// sshd is awaiting a specific line, which we print here. Printing anything else before or after will break our solution
fmt.Println(authKey)
return nil
}
},
}
defaultConfigPath := filepath.Join(policy.GetSystemConfigBasePath(), "config.yml")
verifyCmd.Flags().StringVar(&serverConfigPathArg, "config-path", defaultConfigPath, fmt.Sprintf("Path to the server config file. Default: %s", defaultConfigPath))
rootCmd.AddCommand(verifyCmd)
auditCmd := &cobra.Command{
SilenceUsage: true,
Use: "audit",
Short: "Validate policy file entries against provider definitions",
Long: `Audit validates all entries in the system policy file and user policy files against the provider definitions in the providers file. For complete audit details use the --json flag. Returns a non-zero exit code if any warnings or errors are found.
The audit command checks that:
- Each issuer in policy files is defined in the providers file
- The protocol (http:// or https://) exactly matches between policy and provider files
- The auth_id policy files do not throw parsing errors
Results are reported with the following status:
SUCCESS - Entry is valid
WARNING - Entry is valid but may cause problems
ERROR - Entry has issues (missing provider, protocol mismatch, etc.)
Exit code: 0 if all entries are valid, 1 if any warnings or errors are found.`,
Example: ` opkssh audit`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
audit := commands.NewAuditCmd(os.Stdout, os.Stderr)
// Apply command-line flags
providersFile, _ := cmd.Flags().GetString("providers-file")
if providersFile != "" {
audit.ProviderPath = providersFile
}
policyFile, _ := cmd.Flags().GetString("policy-file")
if policyFile != "" {
audit.PolicyPath = policyFile
}
skipUser, _ := cmd.Flags().GetBool("skip-user-policy")
audit.SkipUserPolicy = skipUser
audit.JsonOutput, _ = cmd.Flags().GetBool("json")
return audit.Run(Version)
},
}
auditCmd.Flags().String("providers-file", policy.SystemDefaultProvidersPath, "Path to providers file")
auditCmd.Flags().String("policy-file", policy.SystemDefaultPolicyPath, "Path to policy file")
auditCmd.Flags().Bool("skip-user-policy", runtime.GOOS == "windows", "Skip auditing user policy file (~/.opk/auth_id)")
auditCmd.Flags().BoolP("json", "j", false, "Output complete audit results in JSON")
rootCmd.AddCommand(auditCmd)
clientCmd := &cobra.Command{
Use: "client [subcommand]",
Short: "Interact with client configuration",
Example: ` opkssh client provider list`,
Args: cobra.ExactArgs(0),
}
providerCmd := &cobra.Command{
Use: "provider [subcommand]",
Short: "Interact with provider configuration",
Example: ` opkssh client provider list`,
Args: cobra.ExactArgs(0),
}
providerListCmd := &cobra.Command{
Use: "list",
Short: "List configured providers",
Example: ` opkssh client provider list`,
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
client_config, err := config.GetClientConfigFromFile(configPathArg, afero.NewOsFs())
if err != nil {
log.Fatal("Unable to load providers. ", err)
}
isTTY := term.IsTerminal(int(os.Stdout.Fd()))
var w *tabwriter.Writer
if isTTY {
// Nice aligned table for TTY output
w = tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "Alias\tIssuer")
fmt.Fprintln(w, "-----\t------")
} else {
// Simpler formatting for non-TTY (e.g., when piping to a file)
w = tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.DiscardEmptyColumns)
}
for _, p := range client_config.Providers {
for _, alias := range p.AliasList {
fmt.Fprintf(w, "%s\t%s\n", alias, p.Issuer)
}
}
w.Flush()
// and lets check it can be loaded into a map, after we print the contents
if _, err = config.CreateProvidersMap(client_config.Providers); err != nil {
log.Fatal("Unable to parse providers. ", err)
}
return nil
},
}
providerListCmd.Flags().StringVar(&configPathArg, "config-path", "", "Path to the client config file. Default: ~/.opk/config.yml on linux and %APPDATA%\\.opk\\config.yml on windows.")
providerCmd.AddCommand(providerListCmd)
clientCmd.AddCommand(providerCmd)
rootCmd.AddCommand(clientCmd)
// permissions command for checking and fixing file permissions/ACLs
permsCmd := commands.NewPermissionsCmd(os.Stdout, os.Stderr)
rootCmd.AddCommand(permsCmd.CobraCommand())
// genDocsCmd is a hidden command used as a helper for generating our
// command line reference documentation.
genDocsCmd := &cobra.Command{
Use: "gendocs <output_dir>",
Hidden: true,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
path := "./docs/cli/"
if len(args) > 1 {
path = args[1]
}
err := os.MkdirAll(path, 0775)
if err != nil {
return err
}
return doc.GenMarkdownTree(rootCmd, path)
},
}
rootCmd.AddCommand(genDocsCmd)
err := rootCmd.Execute()
if err != nil {
return 1
}
return 0
}
func printConfigProblems() {
problems := files.ConfigProblems().GetProblems()
if len(problems) > 0 {
log.Println("Warning: Encountered the following configuration problems:")
for _, problem := range problems {
log.Println(problem.String())
}
}
}
// OpenSSH used to impose a 4096-octet limit on the string buffers available to
// the percent_expand function. In October 2019 as part of the 8.1 release,
// that limit was removed. If you exceeded this amount it would fail with
// fatal: percent_expand: string too long
// The following two functions check whether the OpenSSH version on the
// system running the verifier is greater than or equal to 8.1;
// if not then prints a warning
func checkOpenSSHVersion() {
version := sysdetails.GetOpenSSHVersion()
if version == "" {
log.Println("Warning: Could not determine OpenSSH version")
return
}
if ok, _ := isOpenSSHVersion8Dot1OrGreater(version); !ok {
log.Println("Warning: OpenPubkey SSH requires OpenSSH v. 8.1 or greater")
}
}
func isOpenSSHVersion8Dot1OrGreater(opensshVersion string) (bool, error) {
// Extract version number from various formats:
// - "OpenSSH_9.5p1" -> "9.5"
// - "OpenSSH_for_Windows_9.5p2, LibreSSL 3.8.2" -> "9.5"
// First, get the part before comma (to handle LibreSSL suffix on Windows)
opensshVersion = strings.Split(opensshVersion, ",")[0]
// Try to extract version using regex that handles both Unix and Windows formats
// Matches: "OpenSSH_9.5", "OpenSSH_for_Windows_9.5", etc.
re, err := regexp.Compile(`OpenSSH[_a-zA-Z]*[_](\d+\.\d+)`)
if err != nil {
fmt.Println("Error compiling regex:", err)
return false, err
}
matches := re.FindStringSubmatch(opensshVersion)
if len(matches) < 2 {
// If regex didn't match, try a simpler approach: find any version pattern
simpleRe := regexp.MustCompile(`(\d+\.\d+)`)
matches = simpleRe.FindStringSubmatch(opensshVersion)
if len(matches) < 2 {
log.Printf("Invalid OpenSSH version format: %s", opensshVersion)
return false, fmt.Errorf("invalid OpenSSH version format: %s", opensshVersion)
}
}
version := "v" + matches[1] // semver requires that version strings start with 'v'
// OpenSSH doesn't use semantic versioning, but does use major.minor which after stripping the patch version can be compared using semver
if semver.Compare(version, "v8.1.0") >= 0 {
// if version is greater than or equal to v8.1.0
return true, nil
}
return false, nil
}