-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
563 lines (465 loc) · 13.6 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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"runtime"
"strings"
"sync"
"time"
"gopkg.in/ldap.v2"
)
type Connection struct {
url string
login string
password string
}
type Users struct {
UsersList []User `json:"user,omitempty"`
}
type User struct {
Id int `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
Href string `json:"href"`
Mail string `json:"email"`
}
type Groups struct {
GroupList []Group `json:"group"`
}
type Group struct {
Key string `json:"key"`
Name string `json:"name"`
Href string `json:"href,omitempty"`
Description string `json:"description,omitempty"`
Users *Users `json:"users,omitempty"`
}
// TODO: есть ощущение, что количество кода можно сильно сократить через одну функцию которая принимает реквест и параметр, а внутри select'ом решает, что-куда
func getLDAPUsers(groupName, baseDN string, link *ldap.Conn) []User {
var userList []User
filter := fmt.Sprintf("(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=%s))", groupName)
searchRequest := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
0,
0,
false,
filter,
[]string{},
nil,
)
sr, err := link.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
for _, entry := range sr.Entries {
userList = append(userList, getLDAPUserAttributes(entry.DN, baseDN, link))
}
return userList
}
func getLDAPUserAttributes(userDN, baseDN string, link *ldap.Conn) User {
var user User
filter := fmt.Sprintf("(distinguishedName=%s)", userDN)
searchRequest := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
0,
0,
false,
filter,
[]string{"sn", "givenName", "mail", "sAMAccountName"},
nil,
)
sr, err := link.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
fullName := sr.Entries[0].GetAttributeValue("givenName") + " " + sr.Entries[0].GetAttributeValue("sn")
user.Name = fullName
user.Username = sr.Entries[0].GetAttributeValue("sAMAccountName")
user.Mail = sr.Entries[0].GetAttributeValue("mail")
return user
}
func getGroupDN(groupName, baseDN string, link *ldap.Conn) map[string]string {
filter := fmt.Sprintf("(&(objectClass=group)(cn=%s))", groupName)
searchRequest := ldap.NewSearchRequest(
baseDN,
ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
0,
0,
false,
filter,
[]string{},
nil,
)
sr, err := link.Search(searchRequest)
if err != nil {
log.Fatal(err)
}
ldapGroups := make(map[string]string)
for _, group := range sr.Entries {
ldapGroups[group.GetAttributeValues("cn")[0]] = group.DN
}
return ldapGroups
}
func getTCGroups(conn Connection, client http.Client) Groups {
url := conn.url + "/app/rest/userGroups"
searcherReq, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println(err)
}
searcherReq.Header.Add("Content-type", "application/json")
searcherReq.Header.Add("Accept", "application/json")
searcherReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(searcherReq)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
var raw_groups Groups
err = json.Unmarshal(body, &raw_groups)
if err != nil {
log.Println(err)
}
// var groups []string
// for _, group := range raw_groups.GroupList {
// groups = append(groups, group.Name)
// }
return raw_groups
}
func getTCUsers(conn Connection, client http.Client) Users {
url := conn.url + "/app/rest/users"
searcherReq, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println(err)
}
searcherReq.Header.Add("Content-type", "application/json")
searcherReq.Header.Add("Accept", "application/json")
searcherReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(searcherReq)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
var users Users
err = json.Unmarshal(body, &users)
if err != nil {
log.Println(err)
}
return users
}
func (group Group) getUsersFromGroup(conn Connection, client http.Client) Users {
url := conn.url + group.Href
searcherReq, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println(err)
}
searcherReq.Header.Add("Content-type", "application/json")
searcherReq.Header.Add("Accept", "application/json")
searcherReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(searcherReq)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// log.Println(err)
// }
if FancyHandleError(err) {
log.Print(err)
}
var users Group
err = json.Unmarshal(body, &users)
// if err != nil {
// log.Println(err)
// }
if FancyHandleError(err) {
log.Print(err)
}
return *users.Users
}
func createGroup(groupName string, conn Connection, client http.Client) {
fmt.Println("Creating group", groupName)
url := conn.url + "/app/rest/userGroups"
group := Group{
Key: generateGroupKey(16),
Name: groupName,
}
data, err := json.Marshal(group)
if err != nil {
panic(err)
}
createReq, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
log.Println(err)
}
createReq.Header.Add("Content-type", "application/json")
createReq.Header.Add("Accept", "application/json")
createReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(createReq)
if err != nil || resp.StatusCode > 300 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
fmt.Println("response Body:", string(body))
}
defer resp.Body.Close()
}
func (user User) getUserGroups(conn Connection, client http.Client) Groups {
url := conn.url + "/app/rest/users/" + user.Username + "/groups"
searcherReq, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println(err)
}
searcherReq.Header.Add("Content-type", "application/json")
searcherReq.Header.Add("Accept", "application/json")
searcherReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(searcherReq)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
var userGroups Groups
err = json.Unmarshal(body, &userGroups)
if err != nil {
log.Println(err)
}
return userGroups
}
func (user User) addUserToGroup(group Group, userGroups Groups, conn Connection, client http.Client) {
fmt.Printf("Adding user %s to group %s\n", user.Name, group.Name)
url := conn.url + "/app/rest/users/" + user.Username + "/groups"
userGroups.GroupList = append(userGroups.GroupList, group)
data, err := json.Marshal(userGroups)
if err != nil {
panic(err)
}
createReq, err := http.NewRequest("PUT", url, bytes.NewBuffer(data))
if err != nil {
log.Println(err)
}
createReq.Header.Add("Content-type", "application/json")
createReq.Header.Add("Accept", "application/json")
createReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(createReq)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
if err != nil || resp.StatusCode != 200 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
fmt.Printf("Error: Couldn't add user %s to group %s\nresponse Body:%s\n", user.Name, group.Name, string(body))
}
}
func (user User) removeUserFromGroup(group Group, userGroups Groups, conn Connection, client http.Client) {
fmt.Printf("Removing user %s from group %s\n", user.Name, group.Name)
url := conn.url + "/app/rest/users/" + user.Username + "/groups"
for idx, gr := range userGroups.GroupList {
if gr.Name == group.Name {
userGroups.GroupList = append(userGroups.GroupList[:idx], userGroups.GroupList[idx+1:]...)
}
}
data, err := json.Marshal(userGroups)
if err != nil {
panic(err)
}
createReq, err := http.NewRequest("PUT", url, bytes.NewBuffer(data))
if err != nil {
log.Println(err)
}
createReq.Header.Add("Content-type", "application/json")
createReq.Header.Add("Accept", "application/json")
createReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(createReq)
if err != nil && resp.StatusCode != 200 {
log.Println(err)
//print("Error: Couldn't remove user {} from group {}\n{}".format(user, group_name, resp.content))
}
defer resp.Body.Close()
if err != nil || resp.StatusCode != 200 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
fmt.Printf("Error: Couldn't add user %s to group %s\nresponse Body:%s\n", user.Name, group.Name, string(body))
}
}
func (user User) createUser(conn Connection, client http.Client, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("Creating user", user.Username)
url := conn.url + "/app/rest/users"
data, err := json.Marshal(user)
if err != nil {
panic(err)
}
searcherReq, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
log.Println(err)
}
searcherReq.Header.Add("Content-type", "application/json")
searcherReq.Header.Add("Accept", "application/json")
searcherReq.SetBasicAuth(conn.login, conn.password)
resp, err := client.Do(searcherReq)
if err != nil {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
defer resp.Body.Close()
}
func userExist(ldapUser User, tcUsers Users) bool {
for _, tcUser := range tcUsers.UsersList {
if strings.ToLower(tcUser.Username) == strings.ToLower(ldapUser.Username) {
return true
}
}
return false
}
func userInTCGroup(currentUser User, userGroups Users) bool {
for _, user := range userGroups.UsersList {
if currentUser.Name == user.Name {
return true
}
}
return false
}
func userInLDAPGroup(currentUser User, userGroups []User) bool {
for _, user := range userGroups {
if currentUser.Name == user.Name {
return true
}
}
return false
}
func groupExist(ldapGroup string, tcGroups Groups) bool {
for _, tcGroup := range tcGroups.GroupList {
if tcGroup.Name == ldapGroup {
return true
}
}
return false
}
func findTCgroup(groupName string, tcGroups Groups) Group {
var dah Group
for _, group := range tcGroups.GroupList {
if group.Name == groupName {
return group
}
}
return dah
}
func generateGroupKey(n int) string {
rand.Seed(time.Now().UTC().UnixNano())
letterBytes := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(16)]
}
return string(b)
}
func HandleError(err error) (b bool) {
if err != nil {
// notice that we're using 1, so it will actually log where
// the error happened, 0 = this function, we don't want that.
_, fn, line, _ := runtime.Caller(1)
log.Printf("[error] %s:%d %v", fn, line, err)
b = true
}
return
}
//this logs the function name as well.
func FancyHandleError(err error) (b bool) {
if err != nil {
// notice that we're using 1, so it will actually log the where
// the error happened, 0 = this function, we don't want that.
pc, fn, line, _ := runtime.Caller(1)
log.Printf("[error] in %s[%s:%d] %v", runtime.FuncForPC(pc).Name(), fn, line, err)
b = true
}
return
}
func main() {
username := flag.String("username", "username@domain.com", "Domain login for auth")
password := flag.String("password", "topSecret", "Password for auth")
server := flag.String("server", "domain.com", "Address of LDAP server")
tcServer := flag.String("tcServer", "https://teamcity.domain.com", "Address of LDAP server")
port := flag.String("port", "389", "Port of LDAP server")
tcUser := flag.String("tcUser", "", "User for TC with admin permissions")
tcPassword := flag.String("tcPassword", "", "User for TC with admin permissions")
flag.Parse()
// No TLS, not recommended
l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%s", *server, *port))
if err != nil {
log.Fatal(err)
}
defer l.Close()
err = l.Bind(*username, *password)
if err != nil {
log.Fatal(err)
}
client := &http.Client{}
connection := Connection{*tcServer, *tcUser, *tcPassword}
ldapGroups := getGroupDN("*Teamcity*", "dc=ptsecurity,dc=ru", l) // добавить выбор группы, base брать из лдап конекшн
for groupName, groupDN := range ldapGroups {
// // if self.ldap_object.group_exist( groupDN): ### проверяем, что группа существует в АД
fmt.Printf("Syncing group: %s\n", groupName)
// Create group if not exist
tcGroups := getTCGroups(connection, *client)
if !groupExist(groupName, tcGroups) {
createGroup(groupName, connection, *client)
tcGroups = getTCGroups(connection, *client)
}
// Create user if not exist
ldapUsers := getLDAPUsers(groupDN, "dc=ptsecurity,dc=ru", l) // base брать из лдап конекшн
tcUsers := getTCUsers(connection, *client)
wg := &sync.WaitGroup{}
for _, ldapUser := range ldapUsers {
if !userExist(ldapUser, tcUsers) {
wg.Add(1)
go ldapUser.createUser(connection, *client, wg)
}
}
// Get users from TC group
currеntGroup := findTCgroup(groupName, tcGroups)
tcGroupUsers := currеntGroup.getUsersFromGroup(connection, *client)
// Add users to TC group
for _, ldapUser := range ldapUsers {
userGroups := ldapUser.getUserGroups(connection, *client)
if !userInTCGroup(ldapUser, tcGroupUsers) {
ldapUser.addUserToGroup(currеntGroup, userGroups, connection, *client)
}
}
// Remove users from TC group
for _, tcUser := range tcGroupUsers.UsersList {
userGroups := tcUser.getUserGroups(connection, *client)
if !userInLDAPGroup(tcUser, ldapUsers) {
tcUser.removeUserFromGroup(currеntGroup, userGroups, connection, *client)
}
}
}
fmt.Println("\nDone")
}