forked from reconquest/shadowc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
945 lines (789 loc) · 21.4 KB
/
main.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
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"github.com/kovetskiy/godocs"
"github.com/kovetskiy/lorg"
"github.com/reconquest/colorgful"
"github.com/reconquest/executil-go"
"github.com/reconquest/hierr-go"
srv "github.com/reconquest/srv-go"
)
var version = "3.0"
var usage = `shadowc, client of login distribution service.
shadowc will request shadow hash entries from specified server and update
shadow file (/etc/shadow) accordingly.
It is capable of requesting users list from shadowd server and creating them,
as well as updating theirs SSH keys (authorized_keys).
Most common invocation is:
shadowc -KtC -p <pool> --all
This call will request all users from the pool denoted by <pool>,
create them if necessary, request new hash entries, write them into
/etc/shadow, request SSH keys and overwrite authorized_keys file for each
user.
Requests will be sent to addresses which resolves from SRV record _shadowd.
Usage:
shadowc [options] [-K [-t]] [-C [-g <args>]] [-D [--userdel <args>]] [-p <pool>] [-s <addr>...] -u <user>...
shadowc [options] [-K [-t]] [-C [-g <args>]] [-D [--userdel <args>]] -p <pool> [-s <addr>...] --all
shadowc [options] [-K [-t]] [-p <pool>] -s <addr>... --update
shadowc [options] -P [-s <addr>...] [-p <pool>] -u <user>
shadowc -v | --version
shadowc -h | --help
Options:
-P --password Generate new hash table for specified user. Will prompt
for old and new passwords.
-C --create Create user if it does not exists. User will be created with
command 'useradd'. Additional parameters for 'useradd' can be
passed using option '-g'.
-g --useradd <args> Additional parameters for 'useradd' flag when creating user.
If you want to pass several options to 'useradd', specify
one flag '-g' with quoted argument.
Like that: '-g "-m -Gwheel"'. [default: -m].
-D --delete Delete user if it does not exists in shadowd.
--userdel <args> Additional parameters for 'userdel' flag when deleting user.
Work like '--useradd' flag for 'useradd'. [default: -r].
-K --keys Request SSH keys from shadowd server and append them to the
user's authorized_keys file.
-t --overwrite-keys Overwrite authorized_keys file instead of appending.
-s --server <addr> Use specified login distribution server address.
There are several servers can be specified, then shadowc will
try to request information from the next server is previous
unavailable or do not have required data.
Also, SRV name can be specified by using following syntax:
_<service>._<proto>.<domain> or _<service>.
[default: _shadowd._tcp.zp.s].
-p --pool <pool> Use specified hash tables pool on servers.
-u --user <user> Set user which needs shadow entry.
-a --all Request all users from specified pool and write shadow entries
for them.
-e --update Try to update shadow entries for all users from shadow file
which already has passwords.
-c --cert <path> Set certificate file path [default: /etc/shadowc/cert.pem].
-f --shadow <file> Set shadow file path [default: /etc/shadow].
-w --passwd <passwd> Set passwd file path (for reading user home dir locations).
[default: /etc/passwd]
--no-srv Do not try to find shadowd addresses prefixed by '_' in SRV
records.
--debug Show debug messages.
--trace Show trace messages.
-h --help Show this screen.
-v --version Show version.
`
var (
logger = lorg.NewLog()
debugMode = false
traceMode = false
)
func main() {
args := godocs.MustParse(usage, version, godocs.UsePager)
logger.SetIndentLines(true)
logger.SetFormat(
colorgful.MustApplyDefaultTheme(
"${time} ${level:[%s]:right:short} ${prefix}%s",
colorgful.Dark,
),
)
debugMode = args["--debug"].(bool)
if debugMode {
logger.SetLevel(lorg.LevelDebug)
}
traceMode = args["--trace"].(bool)
if traceMode {
debugMode = true
logger.SetLevel(lorg.LevelTrace)
}
_, err := os.Stat(filepath.Dir(args["--cert"].(string)) + "/key.pem")
if err == nil {
fatalf(
"Key file SHOULD NOT be located on the client machine and " +
"SHOULD NOT leave shadowd server. " +
"Please, generate new certificate pair and " +
"replace certificate file on the clients.",
)
}
addresses := args["--server"].([]string)
if !args["--no-srv"].(bool) {
addresses = tryToResolveSRV(addresses)
}
upstream, err := NewShadowdUpstream(addresses, args["--cert"].(string))
if err != nil {
fatalh(err, "can't initialize shadowd client")
}
switch {
case args["--password"].(bool):
err = handleChangePassword(upstream, args)
default:
err = handlePull(upstream, args)
}
if err != nil {
fatalln(err)
}
}
func handleChangePassword(
upstream *ShadowdUpstream, args map[string]interface{},
) error {
var (
username = args["--user"].([]string)[0]
pool, _ = args["--pool"].(string)
)
if username == "" {
return errors.New("username can't be empty")
}
oldpassword, err := getPassword("Password: ")
if err != nil {
return hierr.Errorf(
err, "can't prompt for password",
)
}
password, err := getPassword("New password: ")
if err != nil {
return hierr.Errorf(
err, "can't prompt for new password",
)
}
proofPassword, err := getPassword("Repeat new password: ")
if err != nil {
return hierr.Errorf(
err, "can't prompt for repeat new password",
)
}
if proofPassword != password {
return errors.New("specified passwords do not match")
}
if password == "" {
return errors.New("password can't be empty")
}
infof("retrieving shadow salts")
salts, err := getPasswordChangeSalts(upstream, pool, username)
if err != nil {
return hierr.Errorf(
err, "can't retrieve salts for changing password",
)
}
infof(
"generating proof shadows using " +
"specified password and retrieved salts",
)
shadows := []string{}
for _, salt := range salts {
shadows = append(shadows, crypt(oldpassword, salt))
}
infof("requesting hash table generating with new password")
err = changePassword(upstream, pool, username, shadows, password)
if err != nil {
return err
}
infof("hash table for %s successfully generated", user{username, pool})
return nil
}
func handlePull(
upstream *ShadowdUpstream, args map[string]interface{},
) error {
var (
shadowFilepath = args["--shadow"].(string)
useUsersFromShadowFile = args["--update"].(bool)
useUsersFromRemotePool = args["--all"].(bool)
shouldCreateUser = args["--create"].(bool)
shouldDeleteUser = args["--delete"].(bool)
shouldUpdateSSHKeys = args["--keys"].(bool)
useraddArgs = args["--useradd"].(string)
userdelArgs = args["--userdel"].(string)
passwdFilePath = args["--passwd"].(string)
pool, _ = args["--pool"].(string)
shouldOverwriteAuthorizedKeys = args["--overwrite-keys"].(bool)
)
var usernames []string
switch {
case useUsersFromShadowFile:
infof(
"retrieving users with passwords from shadow file %s",
shadowFilepath,
)
var err error
usernames, err = getUsersWithPasswords(shadowFilepath)
if err != nil {
return hierr.Errorf(
err, "can't extract users from shadow file %s", shadowFilepath,
)
}
case useUsersFromRemotePool:
infof(
"retrieving users from remote pool %s",
pool,
)
var err error
usernames, err = getAllUsersFromPool(pool, upstream)
if err != nil {
return hierr.Errorf(
err, "can't retrieve users within pool %s", pool,
)
}
default:
usernames = args["--user"].([]string)
for _, username := range usernames {
if username == "" {
return errors.New("username can't be empty")
}
}
}
infof(
"retrieving shadow entries for %s",
users{usernames, pool},
)
shadows, err := getShadows(
usernames, upstream, pool, useUsersFromShadowFile,
)
if err != nil {
return hierr.Errorf(err, "can't retrieve shadow entries")
}
infof(
"retrieving ssh keys for %s",
users{usernames, pool},
)
authorizedKeys, err := getAuthorizedKeys(
usernames, upstream, pool,
)
if err != nil {
return hierr.Errorf(
err, "can't retrieve authorized keys for %s",
users{usernames, pool},
)
}
if shouldCreateUser {
infof("reading shadow file %s", shadowFilepath)
shadowFile, err := ReadShadowFile(shadowFilepath)
if err != nil {
return hierr.Errorf(
err, "can't read shadow file %s", shadowFilepath,
)
}
for _, shadow := range *shadows {
_, err := shadowFile.GetUserIndex(shadow.Username)
if err != nil {
infof("creating user %s", shadow.Username)
err := createUser(shadow.Username, useraddArgs)
if err != nil {
return hierr.Errorf(
err, "can't create user %s", shadow.Username,
)
}
}
}
}
if shouldDeleteUser {
rawRequredGroup, _, err := executil.Run(exec.Command("basename", pool))
if err != nil {
return hierr.Errorf(err, "can't get basename from %s", pool)
}
requiredGroup := strings.TrimSpace(string(rawRequredGroup))
localUsernames, err := getLocalUsers(requiredGroup)
if err != nil {
return hierr.Errorf(
err, "can't get local users with %s group", requiredGroup,
)
}
var outdatedUsernames []string
for _, username := range localUsernames {
outdatedUsernames = append(outdatedUsernames, username)
for _, shadow := range *shadows {
if shadow.Username == username {
outdatedUsernames = outdatedUsernames[:len(outdatedUsernames)-1]
break
}
}
}
for _, username := range outdatedUsernames {
infof("deleting user %s", username)
err := deleteUser(username, userdelArgs)
if err != nil {
return hierr.Errorf(err, "can't delete user %s", username)
}
}
}
if len(*shadows) > 0 {
infof("reading shadow file %s", shadowFilepath)
shadowFile, err := ReadShadowFile(shadowFilepath)
if err != nil {
return hierr.Errorf(
err, "can't read shadow file %s", shadowFilepath,
)
}
infof("updating %d shadow entries", len(*shadows))
err = writeShadows(shadows, shadowFile)
if err != nil {
return hierr.Errorf(
err, "can't write shadow entries to %s", shadowFilepath,
)
}
infof("shadow entries updated", len(*shadows))
}
if shouldUpdateSSHKeys {
infof("updating %d ssh keys", len(authorizedKeys))
written, err := writeSSHKeys(
usernames, authorizedKeys, passwdFilePath,
shouldOverwriteAuthorizedKeys,
)
if err != nil {
return hierr.Errorf(
err, "can't update ssh keys",
)
}
infof(
"ssh keys updated: %d new, %d already installed",
written, len(authorizedKeys)-written,
)
}
return nil
}
func getPasswordChangeSalts(
upstream *ShadowdUpstream, pool, username string,
) ([]string, error) {
shadowdHosts, err := upstream.GetAliveShadowdHosts()
if err != nil {
return nil, err
}
for _, shadowdHost := range shadowdHosts {
salts, err := shadowdHost.GetPasswordChangeSalts(pool, username)
if err != nil {
switch err.(type) {
case NotFoundError:
warningf(
"[%s] is not aware of %s",
shadowdHost.GetAddr(), user{username, pool},
)
default:
shadowdHost.SetIsAlive(false)
errorh(
err,
"[%s] has gone away", shadowdHost.GetAddr(),
)
}
continue
}
return salts, nil
}
return nil, fmt.Errorf(
"no information available for %s in all shadowd servers",
user{username, pool},
)
}
func changePassword(
upstream *ShadowdUpstream,
pool, username string, shadows []string, password string,
) error {
shadowdHosts, err := upstream.GetAliveShadowdHosts()
if err != nil {
return err
}
tracef("shadows: %q", shadows)
for _, shadowdHost := range shadowdHosts {
err = shadowdHost.ChangePassword(
pool, username, shadows, password,
)
if err != nil {
switch err.(type) {
case NotFoundError:
warningf(
"[%s] is not aware of %s",
shadowdHost.GetAddr(), user{username, pool},
)
default:
shadowdHost.SetIsAlive(false)
errorh(
err,
"[%s] has gone away", shadowdHost.GetAddr(),
)
}
continue
}
return nil
}
return errors.New("can't change password")
}
func writeShadows(shadows *Shadows, shadowFile *ShadowFile) error {
// create temporary file in same directory for preventing 'cross-device
// link' error.
temporaryFile, err := ioutil.TempFile(
path.Dir(shadowFile.GetPath()), "shadow",
)
if err != nil {
return hierr.Errorf(
err, "can't create temporary file",
)
}
defer temporaryFile.Close()
for _, shadow := range *shadows {
err := shadowFile.SetShadow(shadow)
if err != nil {
return hierr.Errorf(
err, "can't set shadow record for user %s",
shadow.Username,
)
}
}
_, err = shadowFile.Write(temporaryFile)
if err != nil {
return hierr.Errorf(
err, "can't write temporary shadow file",
)
}
err = temporaryFile.Close()
if err != nil {
return hierr.Errorf(
err, "can't close temporary shadow file",
)
}
err = os.Rename(temporaryFile.Name(), shadowFile.GetPath())
if err != nil {
return hierr.Errorf(
err,
"can't rename temporary file (%s) to shadow file (%s)",
temporaryFile.Name(), shadowFile.GetPath(),
)
}
return nil
}
func writeSSHKeys(
usernames []string, keys AuthorizedKeys, passwdFilePath string,
shouldOverwriteAuthorizedKeys bool,
) (int, error) {
homeDirs, err := getUsersHomeDirs(passwdFilePath)
if err != nil {
return 0, hierr.Errorf(
err, "can't get users home directories from passwd file %s",
passwdFilePath,
)
}
total := 0
for _, user := range usernames {
key, ok := keys[user]
if !ok {
continue
}
home, ok := homeDirs[user]
if !ok {
infof("no home directory found for user %s, skipping", user)
continue
}
path := filepath.Join(
home, ".ssh", "authorized_keys",
)
written, err := writeAuthorizedKeysFile(
user, path, key, shouldOverwriteAuthorizedKeys,
)
if err != nil {
return total, hierr.Errorf(
err, "can't update user %s ssh keys", user,
)
}
total += written
}
return total, nil
}
func writeAuthorizedKeysFile(
user string,
path string, sshKeys SSHKeys,
shouldOverwrite bool,
) (int, error) {
dir := filepath.Dir(path)
_, err := os.Stat(dir)
if os.IsNotExist(err) {
err = os.MkdirAll(dir, 0700)
if err != nil {
return 0, hierr.Errorf(
err, "can't create directory at %s", dir,
)
}
err = changeOwner(user, dir)
if err != nil {
return 0, hierr.Errorf(
err, "can't change directory %s owner to %s", dir, user,
)
}
}
var authorizedKeysFile *AuthorizedKeysFile
if shouldOverwrite {
authorizedKeysFile = NewAuthorizedKeysFile(path)
} else {
authorizedKeysFile, err = ReadAuthorizedKeysFile(path)
if err != nil {
if os.IsNotExist(err) {
authorizedKeysFile = NewAuthorizedKeysFile(path)
} else {
return 0, hierr.Errorf(
err, "can't read authorized keys file %s", path,
)
}
}
}
added := 0
for _, sshKey := range sshKeys {
success := authorizedKeysFile.AddSSHKey(sshKey)
if success {
infof(
"SSH key with comment '%s' added to user %s",
sshKey.GetComment(), user,
)
added++
}
}
temporaryFile, err := ioutil.TempFile(dir, filepath.Base(dir))
if err != nil {
return 0, hierr.Errorf(
err, "can't create temporary file at %s", dir,
)
}
_, err = authorizedKeysFile.Write(temporaryFile)
if err != nil {
return 0, hierr.Errorf(
err, "can't write authorized_keys file",
)
}
err = temporaryFile.Close()
if err != nil {
return 0, hierr.Errorf(
err, "can't close authorized_keys temporary file",
)
}
err = changeOwner(user, temporaryFile.Name())
if err != nil {
return 0, hierr.Errorf(
err, "can't change file %s owner to %s",
temporaryFile.Name(), user,
)
}
err = os.Rename(temporaryFile.Name(), path)
if err != nil {
return 0, hierr.Errorf(
err, "can't rename %s to %s",
temporaryFile.Name(), path,
)
}
return added, nil
}
func getShadows(
usernames []string, upstream *ShadowdUpstream, pool string,
useUsersFromShadowFile bool,
) (*Shadows, error) {
shadows := Shadows{}
for _, username := range usernames {
shadowdHosts, err := upstream.GetAliveShadowdHosts()
if err != nil {
return nil, err
}
shadowFound := false
for _, shadowdHost := range shadowdHosts {
shadow, err := shadowdHost.GetShadow(pool, username)
if err != nil {
switch err.(type) {
case NotFoundError:
warningf(
"[%s] is not aware of %s",
shadowdHost.GetAddr(), user{username, pool},
)
default:
shadowdHost.SetIsAlive(false)
errorh(
err, "[%s] has gone away", shadowdHost.GetAddr(),
)
}
continue
}
shadowFound = true
shadows = append(shadows, shadow)
break
}
if useUsersFromShadowFile && !shadowFound && len(shadowdHosts) > 1 {
return &shadows, fmt.Errorf(
"all shadowd servers are not aware of %s",
user{username, pool},
)
}
}
if useUsersFromShadowFile && len(shadows) == 0 {
return nil, fmt.Errorf(
"no information available for %s in all shadowd servers",
users{usernames, pool},
)
}
return &shadows, nil
}
func getAuthorizedKeys(
usernames []string, upstream *ShadowdUpstream, pool string,
) (AuthorizedKeys, error) {
keys := make(AuthorizedKeys)
for _, username := range usernames {
shadowdHosts, err := upstream.GetAliveShadowdHosts()
if err != nil {
return nil, err
}
sshKeysFound := false
for _, shadowdHost := range shadowdHosts {
userKeys, err := shadowdHost.GetSSHKeys(pool, username)
if err != nil {
switch err.(type) {
case NotFoundError:
warningf(
"[%s] is not aware of ssh keys for %s",
shadowdHost.GetAddr(), user{username, pool},
)
continue
default:
shadowdHost.SetIsAlive(false)
errorh(
err, "[%s] has gone away", shadowdHost.GetAddr(),
)
}
continue
}
sshKeysFound = true
keys[username] = userKeys
break
}
if !sshKeysFound && len(shadowdHosts) > 1 {
warningf("no ssh keys found for %s", user{username, pool})
}
}
return keys, nil
}
func getUsersWithPasswords(shadowFilepath string) ([]string, error) {
contents, err := ioutil.ReadFile(shadowFilepath)
if err != nil {
return []string{}, hierr.Errorf(
err, "can't read shadow file %s", shadowFilepath,
)
}
usernames := []string{}
lines := strings.Split(string(contents), "\n")
for number, line := range lines {
if line == "" {
continue
}
shadowEntry := strings.Split(line, ":")
if len(shadowEntry) < 2 {
return []string{}, hierr.Errorf(
errors.New(line),
"invalid shadow line #%d", number+1,
)
}
hash := shadowEntry[1]
if len(hash) > 1 && hash[0] == '$' {
usernames = append(usernames, shadowEntry[0])
}
}
if len(usernames) == 0 {
return nil, errors.New(
"shadow file does not contains users with passwords",
)
}
return usernames, nil
}
func getAllUsersFromPool(
pool string, upstream *ShadowdUpstream,
) ([]string, error) {
shadowdHosts, err := upstream.GetAliveShadowdHosts()
if err != nil {
return nil, err
}
var tokens []string
for _, shadowdHost := range shadowdHosts {
tokens, err = shadowdHost.GetTokens(pool)
if err != nil {
switch err.(type) {
case NotFoundError:
warningf(
"[%s] is not aware about pool %s",
shadowdHost.GetAddr(), pool,
)
default:
shadowdHost.SetIsAlive(false)
errorh(
err, "[%s] has gone away", shadowdHost.GetAddr(),
)
}
}
}
if len(tokens) == 0 {
return nil, fmt.Errorf(
"no users found within pool %s in all upstream",
pool,
)
}
return tokens, nil
}
func createUser(name, args string) error {
_, _, err := executil.Run(
exec.Command(
"sh", "-c", fmt.Sprintf("useradd %s %s", args, name),
),
)
return err
}
func deleteUser(name, args string) error {
_, _, err := executil.Run(
exec.Command(
"sh", "-c", fmt.Sprintf("userdel %s %s", args, name),
),
)
return err
}
func tryToResolveSRV(records []string) []string {
addresses := []string{}
for _, record := range records {
if !strings.HasPrefix(record, "_") {
addresses = append(addresses, record)
continue
}
infof("resolving SRV DNS record %s", record)
resolved, err := srv.Resolve(record)
if err != nil {
errorln(err)
addresses = append(addresses, record)
continue
}
addresses = append(addresses, resolved...)
}
return addresses
}
func changeOwner(user, path string) error {
_, _, err := executil.Run(exec.Command("chown", user+":", path))
return err
}
func getLocalUsers(requiredGroup string) ([]string, error) {
var correctUsernames []string
rawUsernames, _, err := executil.Run(
exec.Command("cut", "-d:", "-f1", "/etc/passwd"),
)
if err != nil {
return correctUsernames, hierr.Errorf(
err, "can't get users from /etc/password",
)
}
usernames := strings.Split(strings.TrimSpace(string(rawUsernames)), "\n")
for _, username := range usernames {
rawUserGroups, _, err := executil.Run(
exec.Command("id", "-Gn", username),
)
if err != nil {
return correctUsernames, hierr.Errorf(
err, "can't get groups for user %s", username,
)
}
groups := strings.Split(
strings.Trim(string(rawUserGroups), "\n"), " ",
)
for _, group := range groups {
if group == requiredGroup {
correctUsernames = append(correctUsernames, username)
break
}
}
}
return correctUsernames, nil
}