summaryrefslogtreecommitdiff
path: root/internal/commands/crypto_hash.go
blob: c29b751c5fa454cdff8aec6c4b136c78a8a19294 (plain)
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
package commands

import (
	"fmt"
	"net/url"
	"strings"

	"github.com/go-crypt/crypt"
	"github.com/go-crypt/crypt/algorithm"
	"github.com/spf13/cobra"

	"github.com/authelia/authelia/v4/internal/authentication"
	"github.com/authelia/authelia/v4/internal/configuration"
	"github.com/authelia/authelia/v4/internal/configuration/schema"
)

func newCryptoHashCmd(ctx *CmdCtx) (cmd *cobra.Command) {
	cmd = &cobra.Command{
		Use:     cmdUseHash,
		Short:   cmdAutheliaCryptoHashShort,
		Long:    cmdAutheliaCryptoHashLong,
		Example: cmdAutheliaCryptoHashExample,
		Args:    cobra.NoArgs,

		DisableAutoGenTag: true,
	}

	cmd.AddCommand(
		newCryptoHashValidateCmd(ctx),
		newCryptoHashGenerateCmd(ctx),
	)

	return cmd
}

func newCryptoHashGenerateCmd(ctx *CmdCtx) (cmd *cobra.Command) {
	defaults := map[string]any{
		prefixFilePassword + suffixAlgorithm:           schema.DefaultPasswordConfig.Algorithm,
		prefixFilePassword + suffixArgon2Variant:       schema.DefaultPasswordConfig.Argon2.Variant,
		prefixFilePassword + suffixArgon2Iterations:    schema.DefaultPasswordConfig.Argon2.Iterations,
		prefixFilePassword + suffixArgon2Memory:        schema.DefaultPasswordConfig.Argon2.Memory,
		prefixFilePassword + suffixArgon2Parallelism:   schema.DefaultPasswordConfig.Argon2.Parallelism,
		prefixFilePassword + suffixArgon2KeyLength:     schema.DefaultPasswordConfig.Argon2.KeyLength,
		prefixFilePassword + suffixArgon2SaltLength:    schema.DefaultPasswordConfig.Argon2.SaltLength,
		prefixFilePassword + suffixSHA2CryptVariant:    schema.DefaultPasswordConfig.SHA2Crypt.Variant,
		prefixFilePassword + suffixSHA2CryptIterations: schema.DefaultPasswordConfig.SHA2Crypt.Iterations,
		prefixFilePassword + suffixSHA2CryptSaltLength: schema.DefaultPasswordConfig.SHA2Crypt.SaltLength,
		prefixFilePassword + suffixPBKDF2Variant:       schema.DefaultPasswordConfig.PBKDF2.Variant,
		prefixFilePassword + suffixPBKDF2Iterations:    schema.DefaultPasswordConfig.PBKDF2.Iterations,
		prefixFilePassword + suffixPBKDF2SaltLength:    schema.DefaultPasswordConfig.PBKDF2.SaltLength,
		prefixFilePassword + suffixBCryptVariant:       schema.DefaultPasswordConfig.BCrypt.Variant,
		prefixFilePassword + suffixBCryptCost:          schema.DefaultPasswordConfig.BCrypt.Cost,
		prefixFilePassword + suffixSCryptIterations:    schema.DefaultPasswordConfig.SCrypt.Iterations,
		prefixFilePassword + suffixSCryptBlockSize:     schema.DefaultPasswordConfig.SCrypt.BlockSize,
		prefixFilePassword + suffixSCryptParallelism:   schema.DefaultPasswordConfig.SCrypt.Parallelism,
		prefixFilePassword + suffixSCryptKeyLength:     schema.DefaultPasswordConfig.SCrypt.KeyLength,
		prefixFilePassword + suffixSCryptSaltLength:    schema.DefaultPasswordConfig.SCrypt.SaltLength,
	}

	cmd = &cobra.Command{
		Use:     cmdUseGenerate,
		Short:   cmdAutheliaCryptoHashGenerateShort,
		Long:    cmdAutheliaCryptoHashGenerateLong,
		Example: cmdAutheliaCryptoHashGenerateExample,
		Args:    cobra.NoArgs,
		PreRunE: ctx.ChainRunE(
			ctx.HelperConfigSetDefaultsRunE(defaults),
			ctx.CryptoHashGenerateMapFlagsRunE,
			ctx.HelperConfigLoadRunE,
			ctx.ConfigValidateSectionPasswordRunE,
		),
		RunE: ctx.CryptoHashGenerateRunE,

		DisableAutoGenTag: true,
	}

	cmdFlagPassword(cmd, true)
	cmdFlagRandomPassword(cmd)

	for _, use := range []string{cmdUseHashArgon2, cmdUseHashSHA2Crypt, cmdUseHashPBKDF2, cmdUseHashBCrypt, cmdUseHashSCrypt} {
		cmd.AddCommand(newCryptoHashGenerateSubCmd(ctx, use))
	}

	return cmd
}

func newCryptoHashGenerateSubCmd(ctx *CmdCtx, use string) (cmd *cobra.Command) {
	defaults := map[string]any{
		prefixFilePassword + suffixAlgorithm:           schema.DefaultPasswordConfig.Algorithm,
		prefixFilePassword + suffixArgon2Variant:       schema.DefaultPasswordConfig.Argon2.Variant,
		prefixFilePassword + suffixArgon2Iterations:    schema.DefaultPasswordConfig.Argon2.Iterations,
		prefixFilePassword + suffixArgon2Memory:        schema.DefaultPasswordConfig.Argon2.Memory,
		prefixFilePassword + suffixArgon2Parallelism:   schema.DefaultPasswordConfig.Argon2.Parallelism,
		prefixFilePassword + suffixArgon2KeyLength:     schema.DefaultPasswordConfig.Argon2.KeyLength,
		prefixFilePassword + suffixArgon2SaltLength:    schema.DefaultPasswordConfig.Argon2.SaltLength,
		prefixFilePassword + suffixSHA2CryptVariant:    schema.DefaultPasswordConfig.SHA2Crypt.Variant,
		prefixFilePassword + suffixSHA2CryptIterations: schema.DefaultPasswordConfig.SHA2Crypt.Iterations,
		prefixFilePassword + suffixSHA2CryptSaltLength: schema.DefaultPasswordConfig.SHA2Crypt.SaltLength,
		prefixFilePassword + suffixPBKDF2Variant:       schema.DefaultPasswordConfig.PBKDF2.Variant,
		prefixFilePassword + suffixPBKDF2Iterations:    schema.DefaultPasswordConfig.PBKDF2.Iterations,
		prefixFilePassword + suffixPBKDF2SaltLength:    schema.DefaultPasswordConfig.PBKDF2.SaltLength,
		prefixFilePassword + suffixBCryptVariant:       schema.DefaultPasswordConfig.BCrypt.Variant,
		prefixFilePassword + suffixBCryptCost:          schema.DefaultPasswordConfig.BCrypt.Cost,
		prefixFilePassword + suffixSCryptIterations:    schema.DefaultPasswordConfig.SCrypt.Iterations,
		prefixFilePassword + suffixSCryptBlockSize:     schema.DefaultPasswordConfig.SCrypt.BlockSize,
		prefixFilePassword + suffixSCryptParallelism:   schema.DefaultPasswordConfig.SCrypt.Parallelism,
		prefixFilePassword + suffixSCryptKeyLength:     schema.DefaultPasswordConfig.SCrypt.KeyLength,
		prefixFilePassword + suffixSCryptSaltLength:    schema.DefaultPasswordConfig.SCrypt.SaltLength,
	}

	useFmt := fmtCryptoHashUse(use)

	cmd = &cobra.Command{
		Use:     use,
		Short:   fmt.Sprintf(fmtCmdAutheliaCryptoHashGenerateSubShort, useFmt),
		Long:    fmt.Sprintf(fmtCmdAutheliaCryptoHashGenerateSubLong, useFmt, useFmt),
		Example: fmt.Sprintf(fmtCmdAutheliaCryptoHashGenerateSubExample, use),
		Args:    cobra.NoArgs,
		PersistentPreRunE: ctx.ChainRunE(
			ctx.HelperConfigSetDefaultsRunE(defaults),
			ctx.CryptoHashGenerateMapFlagsRunE,
			ctx.HelperConfigLoadRunE,
			ctx.ConfigValidateSectionPasswordRunE,
		),
		RunE: ctx.CryptoHashGenerateRunE,

		DisableAutoGenTag: true,
	}

	switch use {
	case cmdUseHashArgon2:
		cmdFlagIterations(cmd, schema.DefaultPasswordConfig.Argon2.Iterations)
		cmdFlagParallelism(cmd, schema.DefaultPasswordConfig.Argon2.Parallelism)
		cmdFlagKeySize(cmd, schema.DefaultPasswordConfig.Argon2.KeyLength)
		cmdFlagSaltSize(cmd, schema.DefaultPasswordConfig.Argon2.SaltLength)

		cmd.Flags().StringP(cmdFlagNameVariant, "v", schema.DefaultPasswordConfig.Argon2.Variant, "variant, options are 'argon2id', 'argon2i', and 'argon2d'")
		cmd.Flags().IntP(cmdFlagNameMemory, "m", schema.DefaultPasswordConfig.Argon2.Memory, "memory in kibibytes")
		cmd.Flags().String(cmdFlagNameProfile, "", "profile to use, options are low-memory and recommended")
	case cmdUseHashSHA2Crypt:
		cmdFlagIterations(cmd, schema.DefaultPasswordConfig.SHA2Crypt.Iterations)
		cmdFlagSaltSize(cmd, schema.DefaultPasswordConfig.SHA2Crypt.SaltLength)

		cmd.Flags().StringP(cmdFlagNameVariant, "v", schema.DefaultPasswordConfig.SHA2Crypt.Variant, "variant, options are sha256 and sha512")
		cmd.PreRunE = ctx.ChainRunE()
	case cmdUseHashPBKDF2:
		cmdFlagIterations(cmd, schema.DefaultPasswordConfig.PBKDF2.Iterations)
		cmdFlagSaltSize(cmd, schema.DefaultPasswordConfig.PBKDF2.SaltLength)

		cmd.Flags().StringP(cmdFlagNameVariant, "v", schema.DefaultPasswordConfig.PBKDF2.Variant, "variant, options are 'sha1', 'sha224', 'sha256', 'sha384', and 'sha512'")
	case cmdUseHashBCrypt:
		cmd.Flags().StringP(cmdFlagNameVariant, "v", schema.DefaultPasswordConfig.BCrypt.Variant, "variant, options are 'standard' and 'sha256'")
		cmd.Flags().IntP(cmdFlagNameCost, "i", schema.DefaultPasswordConfig.BCrypt.Cost, "hashing cost")
	case cmdUseHashSCrypt:
		cmdFlagIterations(cmd, schema.DefaultPasswordConfig.SCrypt.Iterations)
		cmdFlagKeySize(cmd, schema.DefaultPasswordConfig.SCrypt.KeyLength)
		cmdFlagSaltSize(cmd, schema.DefaultPasswordConfig.SCrypt.SaltLength)
		cmdFlagParallelism(cmd, schema.DefaultPasswordConfig.SCrypt.Parallelism)

		cmd.Flags().IntP(cmdFlagNameBlockSize, "r", schema.DefaultPasswordConfig.SCrypt.BlockSize, "block size")
	}

	return cmd
}

func newCryptoHashValidateCmd(ctx *CmdCtx) (cmd *cobra.Command) {
	cmd = &cobra.Command{
		Use:     fmt.Sprintf(cmdUseFmtValidate, cmdUseValidate),
		Short:   cmdAutheliaCryptoHashValidateShort,
		Long:    cmdAutheliaCryptoHashValidateLong,
		Example: cmdAutheliaCryptoHashValidateExample,
		Args:    cobra.ExactArgs(1),
		RunE:    ctx.CryptoHashValidateRunE,

		DisableAutoGenTag: true,
	}

	cmdFlagPassword(cmd, false)

	return cmd
}

// CryptoHashValidateRunE is the RunE for the authelia crypto hash validate command.
func (ctx *CmdCtx) CryptoHashValidateRunE(cmd *cobra.Command, args []string) (err error) {
	var (
		password string
		valid    bool
	)

	if password, _, err = cmdCryptoHashGetPassword(cmd, args, false, false); err != nil {
		return fmt.Errorf("error occurred trying to obtain the password: %w", err)
	}

	if len(password) == 0 {
		return fmt.Errorf("no password provided")
	}

	if valid, err = crypt.CheckPassword(password, args[0]); err != nil {
		return fmt.Errorf("error occurred trying to validate the password against the digest: %w", err)
	}

	switch {
	case valid:
		fmt.Println("The password matches the digest.")
	default:
		fmt.Println("The password does not match the digest.")
	}

	return nil
}

// CryptoHashGenerateMapFlagsRunE is the RunE which configures the flags map configuration source for the
// authelia crypto hash generate commands.
func (ctx *CmdCtx) CryptoHashGenerateMapFlagsRunE(cmd *cobra.Command, args []string) (err error) {
	var flagsMap map[string]string

	switch cmd.Use {
	case cmdUseHashArgon2:
		flagsMap = map[string]string{
			cmdFlagNameVariant:     prefixFilePassword + suffixArgon2Variant,
			cmdFlagNameIterations:  prefixFilePassword + suffixArgon2Iterations,
			cmdFlagNameMemory:      prefixFilePassword + suffixArgon2Memory,
			cmdFlagNameParallelism: prefixFilePassword + suffixArgon2Parallelism,
			cmdFlagNameKeySize:     prefixFilePassword + suffixArgon2KeyLength,
			cmdFlagNameSaltSize:    prefixFilePassword + suffixArgon2SaltLength,
		}
	case cmdUseHashSHA2Crypt:
		flagsMap = map[string]string{
			cmdFlagNameVariant:    prefixFilePassword + suffixSHA2CryptVariant,
			cmdFlagNameIterations: prefixFilePassword + suffixSHA2CryptIterations,
			cmdFlagNameSaltSize:   prefixFilePassword + suffixSHA2CryptSaltLength,
		}
	case cmdUseHashPBKDF2:
		flagsMap = map[string]string{
			cmdFlagNameVariant:    prefixFilePassword + suffixPBKDF2Variant,
			cmdFlagNameIterations: prefixFilePassword + suffixPBKDF2Iterations,
			cmdFlagNameKeySize:    prefixFilePassword + suffixPBKDF2KeyLength,
			cmdFlagNameSaltSize:   prefixFilePassword + suffixPBKDF2SaltLength,
		}
	case cmdUseHashBCrypt:
		flagsMap = map[string]string{
			cmdFlagNameVariant: prefixFilePassword + suffixBCryptVariant,
			cmdFlagNameCost:    prefixFilePassword + suffixBCryptCost,
		}
	case cmdUseHashSCrypt:
		flagsMap = map[string]string{
			cmdFlagNameIterations:  prefixFilePassword + suffixSCryptIterations,
			cmdFlagNameBlockSize:   prefixFilePassword + suffixSCryptBlockSize,
			cmdFlagNameParallelism: prefixFilePassword + suffixSCryptParallelism,
			cmdFlagNameKeySize:     prefixFilePassword + suffixSCryptKeyLength,
			cmdFlagNameSaltSize:    prefixFilePassword + suffixSCryptSaltLength,
		}
	}

	if flagsMap != nil {
		ctx.cconfig.sources = append(ctx.cconfig.sources, configuration.NewCommandLineSourceWithMapping(cmd.Flags(), flagsMap, false, false))
	}

	return nil
}

// CryptoHashGenerateRunE is the RunE for the authelia crypto hash generate commands.
func (ctx *CmdCtx) CryptoHashGenerateRunE(cmd *cobra.Command, args []string) (err error) {
	var (
		hash     algorithm.Hash
		digest   algorithm.Digest
		password string
		random   bool
	)

	if password, random, err = cmdCryptoHashGetPassword(cmd, args, false, true); err != nil {
		return err
	}

	if len(password) == 0 {
		return fmt.Errorf("no password provided")
	}

	switch cmd.Use {
	case cmdUseGenerate:
		break
	default:
		ctx.config.AuthenticationBackend.File.Password.Algorithm = cmd.Use
	}

	if hash, err = authentication.NewFileCryptoHashFromConfig(ctx.config.AuthenticationBackend.File.Password); err != nil {
		return err
	}

	if digest, err = hash.Hash(password); err != nil {
		return err
	}

	if random {
		fmt.Printf("Random Password: %s\n", password)

		if value := url.QueryEscape(password); password != value {
			fmt.Printf("Random Password (URL Encoded): %s\n", value)
		}
	}

	fmt.Printf("Digest: %s\n", digest.Encode())

	return nil
}

func cmdCryptoHashGetPassword(cmd *cobra.Command, args []string, useArgs, useRandom bool) (password string, random bool, err error) {
	if useRandom {
		if random, err = cmd.Flags().GetBool(cmdFlagNameRandom); err != nil {
			return
		}
	}

	switch {
	case random:
		password, err = flagsGetRandomCharacters(cmd.Flags(), cmdFlagNameRandomLength, cmdFlagNameRandomCharSet, cmdFlagNameCharacters)

		return
	case cmd.Flags().Changed(cmdFlagNamePassword):
		password, err = cmd.Flags().GetString(cmdFlagNamePassword)

		return
	case useArgs && len(args) != 0:
		password, err = strings.Join(args, " "), nil

		return
	}

	var (
		noConfirm bool
	)

	if password, err = termReadPasswordWithPrompt("Enter Password: ", "password"); err != nil {
		err = fmt.Errorf("failed to read the password from the terminal: %w", err)

		return
	}

	if cmd.Use == fmt.Sprintf(cmdUseFmtValidate, cmdUseValidate) {
		fmt.Println("")

		return
	}

	if noConfirm, err = cmd.Flags().GetBool(cmdFlagNameNoConfirm); err == nil && !noConfirm {
		var confirm string

		if confirm, err = termReadPasswordWithPrompt("Confirm Password: ", ""); err != nil {
			return
		}

		if password != confirm {
			fmt.Println("")

			err = fmt.Errorf("the password did not match the confirmation password")

			return
		}
	}

	fmt.Println("")

	return
}

func cmdFlagPassword(cmd *cobra.Command, noConfirm bool) {
	cmd.PersistentFlags().String(cmdFlagNamePassword, "", "manually supply the password rather than using the terminal prompt")

	if noConfirm {
		cmd.PersistentFlags().Bool(cmdFlagNameNoConfirm, false, "skip the password confirmation prompt")
	}
}

func cmdFlagRandomPassword(cmd *cobra.Command) {
	cmd.PersistentFlags().Bool(cmdFlagNameRandom, false, "uses a randomly generated password")
	cmd.PersistentFlags().String(cmdFlagNameRandomCharSet, cmdFlagValueCharSet, cmdFlagUsageCharset)
	cmd.PersistentFlags().String(cmdFlagNameRandomCharacters, "", cmdFlagUsageCharacters)
	cmd.PersistentFlags().Int(cmdFlagNameRandomLength, 72, cmdFlagUsageLength)
}

func cmdFlagIterations(cmd *cobra.Command, value int) {
	cmd.Flags().IntP(cmdFlagNameIterations, "i", value, "number of iterations")
}

func cmdFlagKeySize(cmd *cobra.Command, value int) {
	cmd.Flags().IntP(cmdFlagNameKeySize, "k", value, "key size in bytes")
}

func cmdFlagSaltSize(cmd *cobra.Command, value int) {
	cmd.Flags().IntP(cmdFlagNameSaltSize, "s", value, "salt size in bytes")
}

func cmdFlagParallelism(cmd *cobra.Command, value int) {
	cmd.Flags().IntP(cmdFlagNameParallelism, "p", value, "parallelism or threads")
}