-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathadclient.cpp
1809 lines (1500 loc) · 53.8 KB
/
adclient.cpp
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdlib.h"
#include "adclient.h"
/*
Active Directory class.
adclient::login can throw ADBindException on errors.
all search functions can throw ADSearchException on errors.
all modify functions can throw both ADSearchException and ADOperationalException on errors.
text description will be in 'msg' property
numeric code in 'code' property
*/
adclient::adclient() {
/*
Constructor, to initialize default values of global variables.
*/
ds = NULL;
}
adclient::~adclient() {
/*
Destructor, to automaticaly free initial values allocated at login().
*/
logout(ds);
}
void adclient::logout(LDAP *ds) {
if (ds != NULL) {
ldap_unbind_ext(ds, NULL, NULL);
}
}
void adclient::login(adConnParams _params) {
ldap_prefix = _params.use_ldaps ? "ldaps" : "ldap";
if (!_params.uries.empty()) {
for (vector <string>::iterator it = _params.uries.begin(); it != _params.uries.end(); ++it) {
if (it->find("://") == string::npos) {
_params.uri = ldap_prefix + "://" + *it;
} else {
_params.uri = *it;
}
try {
login(&ds, _params);
params = _params;
return;
}
catch (ADBindException&) {
if (ds != NULL) {
ldap_unbind_ext(ds, NULL, NULL);
ds = NULL;
}
if (it != (_params.uries.end() - 1)) {
continue;
} else {
throw;
}
}
}
throw ADBindException("No suitable connection uries found", AD_PARAMS_ERROR);
} else if (!_params.domain.empty()) {
if (_params.search_base.empty()) {
_params.search_base = domain2dn(_params.domain);
}
_params.uries = get_ldap_servers(_params.domain, _params.site);
login(_params);
} else {
throw ADBindException("No suitable connection params found", AD_PARAMS_ERROR);
}
}
void adclient::login(vector <string> uries, string binddn, string bindpw, string search_base, bool secured) {
/*
Wrapper around login to support list of uries
*/
adConnParams _params;
_params.uries = uries;
_params.binddn = binddn;
_params.bindpw = bindpw;
_params.search_base = search_base;
_params.secured = secured;
login(_params);
}
void adclient::login(string _uri, string binddn, string bindpw, string search_base, bool secured) {
/*
Wrapper around login to fill LDAP* structure
*/
adConnParams _params;
_params.uries.push_back(_uri);
_params.binddn = binddn;
_params.bindpw = bindpw;
_params.search_base = search_base;
_params.secured = secured;
login(_params);
}
void adclient::login(LDAP **ds, adConnParams& _params) {
/*
To set various LDAP options and bind to LDAP server.
It set private pointer to LDAP connection identifier - ds.
It returns nothing if operation was successfull, throws ADBindException otherwise.
*/
logout(*ds);
int result, version, bindresult = -1;
string error_msg;
if (_params.use_ldaps && _params.use_tls) {
error_msg = "Error in passed params: use_ldaps and use_tls are mutually exclusive";
throw ADBindException(error_msg, AD_PARAMS_ERROR);
}
#if defined OPENLDAP
result = ldap_initialize(ds, _params.uri.c_str());
#elif defined SUNLDAP
result = ldapssl_init(_params.uri.c_str(), LDAPS_PORT, 1);
#else
#error LDAP library required
#endif
if (result != LDAP_SUCCESS) {
error_msg = "Error in ldap_initialize to " + _params.uri + ": ";
error_msg.append(ldap_err2string(result));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
if (_params.nettimeout != -1) {
struct timeval optTimeout;
optTimeout.tv_usec = 0;
optTimeout.tv_sec = _params.nettimeout;
result = ldap_set_option(*ds, LDAP_OPT_TIMEOUT, &optTimeout);
if (result != LDAP_OPT_SUCCESS) {
error_msg = "Error in ldap_set_option (general timeout): ";
error_msg.append(ldap_err2string(result));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
result = ldap_set_option(*ds, LDAP_OPT_NETWORK_TIMEOUT, &optTimeout);
if (result != LDAP_OPT_SUCCESS) {
error_msg = "Error in ldap_set_option (network timeout): ";
error_msg.append(ldap_err2string(result));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
}
if (_params.timelimit != -1) {
result = ldap_set_option(*ds, LDAP_OPT_TIMELIMIT, &_params.timelimit);
if (result != LDAP_OPT_SUCCESS) {
error_msg = "Error in ldap_set_option (time limit): ";
error_msg.append(ldap_err2string(result));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
}
version = LDAP_VERSION3;
result = ldap_set_option(*ds, LDAP_OPT_PROTOCOL_VERSION, &version);
if (result != LDAP_OPT_SUCCESS) {
error_msg = "Error in ldap_set_option (protocol->v3): ";
error_msg.append(ldap_err2string(result));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
result = ldap_set_option(*ds, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
if (result != LDAP_OPT_SUCCESS) {
error_msg = "Error in ldap_set_option (referrals->off): ";
error_msg.append(ldap_err2string(result));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
if (_params.use_tls) {
result = ldap_start_tls_s(*ds, NULL, NULL);
if (result != LDAP_SUCCESS) {
error_msg = "Error in ldap_start_tls_s: ";
error_msg.append(ldap_err2string(result));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
_params.bind_method = "StartTLS";
} else {
_params.bind_method = _params.use_ldaps ? "LDAPS" : "plain";
}
if (_params.secured) {
#ifdef KRB5
if (_params.use_gssapi) {
if (krb5_create_cache(_params.domain.c_str()) == 0) {
_params.login_method = "GSSAPI";
bindresult = sasl_bind_gssapi(*ds);
if (bindresult == LDAP_SUCCESS) {
ldap_set_rebind_proc(*ds, sasl_rebind_gssapi, NULL);
}
} else {
bindresult = -1;
}
} else {
#endif
_params.login_method = "DIGEST-MD5";
bindresult = sasl_bind_digest_md5(*ds, _params.binddn, _params.bindpw);
#ifdef KRB5
}
#endif
} else {
_params.login_method = "SIMPLE";
bindresult = sasl_bind_simple(*ds, _params.binddn, _params.bindpw);
}
if (bindresult != LDAP_SUCCESS) {
error_msg = "Error while " + _params.login_method + " ldap binding to " + _params.uri + ": ";
error_msg.append(ldap_err2string(bindresult));
throw ADBindException(error_msg, AD_SERVER_CONNECT_FAILURE);
}
}
bool adclient::checkUserPassword(string user, string password) {
/*
It returns true of false depends on user credentials correctness.
*/
LDAP *ld = NULL;
bool result = true;
try {
adConnParams _params(params);
_params.binddn = user;
_params.bindpw = password;
_params.use_gssapi = false;
login(&ld, _params);
}
catch (ADBindException& ex) {
result = false;
}
logout(ld);
return result;
}
map < string, map < string, vector<string> > > adclient::search(string OU, int scope, string filter, const vector <string> &attributes) {
/*
General search function.
It returns map with users found with 'filter' with specified 'attributes'.
*/
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
int result, errcodep;
char *attrs[50];
int attrsonly = 0;
string error_msg = "";
ber_int_t pagesize = 1000;
ber_int_t totalcount;
struct berval *cookie = NULL;
int iscritical = 1;
LDAPControl *serverctrls[2] = { NULL, NULL };
LDAPControl *pagecontrol = NULL;
LDAPControl **returnedctrls = NULL;
LDAPMessage *res = NULL;
LDAPMessage *entry;
char *dn;
bool morepages;
map < string, map < string, vector<string> > > search_result;
if (attributes.size() > 50) throw ADSearchException("Cant return more than 50 attributes", AD_PARAMS_ERROR);
unsigned int i;
for (i = 0; i < attributes.size(); ++i) {
attrs[i] = strdup(attributes[i].c_str());
}
attrs[i] = NULL;
replace(filter, "\\", "\\\\");
do {
result = ldap_create_page_control(ds, pagesize, cookie, iscritical, &pagecontrol);
if (result != LDAP_SUCCESS) {
error_msg = "Failed to create page control: ";
error_msg.append(ldap_err2string(result));
break;
}
serverctrls[0] = pagecontrol;
/* Search for entries in the directory using the parmeters. */
result = ldap_search_ext_s(ds, OU.c_str(), scope, filter.c_str(), attrs, attrsonly, serverctrls, NULL, NULL, LDAP_NO_LIMIT, &res);
if ((result != LDAP_SUCCESS) & (result != LDAP_PARTIAL_RESULTS)) {
error_msg = "Error in paged ldap_search_ext_s: ";
error_msg.append(ldap_err2string(result));
break;
}
serverctrls[0] = NULL;
ldap_control_free(pagecontrol);
pagecontrol = NULL;
int num_results = ldap_count_entries(ds, res);
if (num_results == 0) {
error_msg = filter + " not found";
result = AD_OBJECT_NOT_FOUND;
break;
}
map < string, vector<string> > valuesmap;
for ( entry = ldap_first_entry(ds, res);
entry != NULL;
entry = ldap_next_entry(ds, entry) ) {
dn = ldap_get_dn(ds, entry);
valuesmap = _getvalues(entry);
search_result[dn] = valuesmap;
ldap_memfree(dn);
}
/* Parse the results to retrieve the contols being returned. */
result = ldap_parse_result(ds, res, &errcodep, NULL, NULL, NULL, &returnedctrls, false);
if (result != LDAP_SUCCESS) {
error_msg = "Failed to parse result: ";
error_msg.append(ldap_err2string(result));
break;
}
/* Parse the page control returned to get the cookie and */
/* determine whether there are more pages. */
pagecontrol = ldap_control_find(LDAP_CONTROL_PAGEDRESULTS, returnedctrls, NULL);
if (pagecontrol == NULL) {
error_msg = "Failed to find PAGEDRESULTS control";
result = 255;
break;
}
struct berval newcookie;
result = ldap_parse_pageresponse_control(ds, pagecontrol, &totalcount, &newcookie);
if (result != LDAP_SUCCESS) {
error_msg = "Failed to parse pageresponse control: ";
error_msg.append(ldap_err2string(result));
break;
}
ber_bvfree(cookie);
cookie = reinterpret_cast<berval*>(ber_memalloc( sizeof( struct berval ) ));
if (cookie == NULL) {
error_msg = "Failed to allocate memory for cookie";
result = 255;
break;
}
*cookie = newcookie;
/* Cleanup the controls used. */
ldap_controls_free(returnedctrls);
returnedctrls = NULL;
/* Determine if the cookie is not empty, indicating there are more pages for these search parameters. */
if (cookie->bv_val != NULL && (strlen(cookie->bv_val) > 0)) {
morepages = true;
} else {
morepages = false;
}
ldap_msgfree(res);
} while (morepages);
for (i = 0; i < attributes.size(); ++i) {
free(attrs[i]);
}
if (cookie != NULL) {
ber_bvfree(cookie);
}
if (error_msg.empty()) {
return search_result;
} else {
ldap_msgfree(res);
throw ADSearchException(error_msg, result);
}
}
bool adclient::ifDNExists(string dn) {
/*
Wrapper around two arguments ifDNExists for searching any objectclass DN
*/
return ifDNExists(dn, "*");
}
bool adclient::ifDNExists(string dn, string objectclass) {
/*
It returns true of false depends on object DN existence.
*/
int result;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
char *attrs[] = {"1.1", NULL};
#pragma GCC diagnostic pop
LDAPMessage *res;
string error_msg;
int attrsonly = 1;
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
string filter = "(objectclass=" + objectclass + ")";
result = ldap_search_ext_s(ds, dn.c_str(), LDAP_SCOPE_SUBTREE, filter.c_str(), attrs, attrsonly, NULL, NULL, NULL, LDAP_NO_LIMIT, &res);
ldap_msgfree(res);
return (result == LDAP_SUCCESS);
}
vector <string> adclient::searchDN(string search_base, string filter, int scope) {
/*
It returns vector with DNs found with 'filter'.
*/
map < string, map < string, vector<string> > > search_result;
vector <string> attributes;
attributes.push_back("1.1");
search_result = search(search_base.c_str(), scope, filter, attributes);
vector <string> result;
map < string, map < string, vector<string> > >::iterator res_it;
for ( res_it=search_result.begin() ; res_it != search_result.end(); ++res_it ) {
string dn = (*res_it).first;
result.push_back(dn);
}
return result;
}
string adclient::getObjectDN(string object) {
/*
It returns user DN by short name.
*/
if (ifDNExists(object)) {
return object;
} else {
replace(object, "(", "\\(");
replace(object, ")", "\\)");
vector <string> dn = searchDN(params.search_base, "(sAMAccountName=" + object + ")", LDAP_SCOPE_SUBTREE);
return dn[0];
}
}
void adclient::mod_add(string object, string attribute, string value) {
/*
It performs generic LDAP_MOD_ADD operation on object (short_name/DN).
It adds value to attribute.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
string dn = getObjectDN(object);
LDAPMod *attrs[2];
LDAPMod attr;
char *values[2];
int result;
string error_msg;
values[0] = strdup(value.c_str());
values[1] = NULL;
attr.mod_op = LDAP_MOD_ADD;
attr.mod_type = strdup(attribute.c_str());
attr.mod_values = values;
attrs[0] = &attr;
attrs[1] = NULL;
result = ldap_modify_ext_s(ds, dn.c_str(), attrs, NULL, NULL);
free(values[0]);
free(attr.mod_type);
if (result != LDAP_SUCCESS) {
error_msg = "Error in mod_add, ldap_modify_ext_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
void adclient::mod_delete(string object, string attribute, string value) {
/*
It performs generic LDAP_MOD_DELETE operation on object (short_name/DN).
It removes value from attribute.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
string dn = getObjectDN(object);
LDAPMod *attrs[2];
LDAPMod attr;
char *values[2];
int result;
string error_msg;
if (value.empty()) {
values[0] = NULL;
} else {
values[0] = strdup(value.c_str());
}
values[1] = NULL;
attr.mod_op = LDAP_MOD_DELETE;
attr.mod_type = strdup(attribute.c_str());
attr.mod_values = values;
attrs[0] = &attr;
attrs[1] = NULL;
result = ldap_modify_ext_s(ds, dn.c_str(), attrs, NULL, NULL);
if (!value.empty()) {
free(values[0]);
}
free(attr.mod_type);
if (result != LDAP_SUCCESS) {
error_msg = "Error in mod_delete, ldap_modify_ext_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
void adclient::mod_move(string object, string new_container) {
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
if (!ifDNExists(new_container)) {
string error_msg = "Error in mod_move, destination OU does not exists: ";
error_msg.append(new_container);
throw ADOperationalException(error_msg, AD_PARAMS_ERROR);
}
string dn = getObjectDN(object);
std::pair<string, string> rdn = explode_dn(dn)[0];
string newrdn = rdn.first + "=" + rdn.second;
int result = ldap_rename_s(ds, dn.c_str(), newrdn.c_str(), new_container.c_str(), 1, NULL, NULL);
if (result != LDAP_SUCCESS) {
string error_msg = "Error in mod_move, ldap_rename_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
void adclient::mod_rename(string object, string cn) {
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
string dn = getObjectDN(object);
string newrdn = "CN=" + cn;
int result = ldap_rename_s(ds, dn.c_str(), newrdn.c_str(), NULL, 1, NULL, NULL);
if (result != LDAP_SUCCESS){
string error_msg = "Error in mod_rename, ldap_rename_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg,result);
}
}
void adclient::mod_replace(string object, string attribute, vector <string> list) {
/*
It performs generic LDAP_MOD_REPLACE operation on object (short_name/DN).
It removes list from attribute.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
string dn = getObjectDN(object);
LDAPMod *attrs[2];
LDAPMod attr;
int result;
string error_msg;
char** values = new char*[list.size() + 1];
size_t i;
for (i = 0; i < list.size(); ++i) {
values[i] = new char[list[i].size() + 1];
strcpy(values[i], list[i].c_str());
}
values[i] = NULL;
attr.mod_op = LDAP_MOD_REPLACE;
attr.mod_type = strdup(attribute.c_str());
attr.mod_values = values;
attrs[0] = &attr;
attrs[1] = NULL;
result = ldap_modify_ext_s(ds, dn.c_str(), attrs, NULL, NULL);
if (result != LDAP_SUCCESS) {
error_msg = "Error in mod_replace, ldap_modify_ext_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
for (i = 0; i < list.size(); ++i) {
delete[] values[i];
}
delete[] values;
free(attr.mod_type);
}
void adclient::mod_replace(string object, string attribute, string value) {
/*
It performs generic LDAP_MOD_REPLACE operation on object (short_name/DN).
It removes value from attribute.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
vector<string> values;
values.push_back(value);
return mod_replace(object, attribute, values);
}
void adclient::CreateOU(string ou) {
/*
It creates given OU (with subOUs if needed).
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
if (ifDNExists(ou)) {
return;
}
vector < std::pair<string, string> > ou_exploded = explode_dn(ou);
std::pair<string, string> front_ou = ou_exploded.front();
ou_exploded.erase(ou_exploded.begin());
string sub_ou = merge_dn(ou_exploded);
if ((!sub_ou.empty()) && (!ifDNExists(sub_ou))) {
CreateOU(sub_ou);
}
if (upper(front_ou.first) != "OU") {
string error_msg = "Error in CreateOU, incorrect OU syntax: ";
error_msg.append(front_ou.first + "=" + front_ou.second);
throw ADOperationalException(error_msg, AD_PARAMS_ERROR);
}
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
LDAPMod *attrs[3];
LDAPMod attr1, attr2;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
char *objectClass_values[] = {"organizationalUnit", NULL};
attr1.mod_op = LDAP_MOD_ADD;
attr1.mod_type = "objectClass";
attr1.mod_values = objectClass_values;
char *name_values[2];
name_values[0] = strdup(front_ou.second.c_str());
name_values[1] = NULL;
attr2.mod_op = LDAP_MOD_ADD;
attr2.mod_type = "name";
attr2.mod_values = name_values;
#pragma GCC diagnostic pop
attrs[0] = &attr1;
attrs[1] = &attr2;
attrs[2] = NULL;
int result = ldap_add_ext_s(ds, ou.c_str(), attrs, NULL, NULL);
free(name_values[0]);
if (result != LDAP_SUCCESS) {
string error_msg = "Error in CreateOU, ldap_add_ext_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
void adclient::DeleteDN(string dn) {
/*
It deletes given DN.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
int result = ldap_delete_ext_s(ds, dn.c_str(), NULL, NULL);
if (result != LDAP_SUCCESS) {
string error_msg = "Error in DeleteDN, ldap_delete_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
string adclient::dn2domain(string dn) {
string domain = "";
vector < std::pair<string, string> > dn_exploded = explode_dn(dn);
vector < std::pair<string, string> >::iterator it;
for (it = dn_exploded.begin(); it != dn_exploded.end(); ++it) {
if (upper(it->first) == "DC") {
domain += it->second;
domain += ".";
}
}
if (domain.size() > 0) {
domain.erase(domain.size()-1, 1);
}
return domain;
}
string adclient::merge_dn(vector < std::pair<string, string> > dn_exploded) {
std::stringstream result;
vector < std::pair<string, string> >::iterator it;
for (it = dn_exploded.begin(); it != dn_exploded.end(); ++it) {
result << it->first;
result << "=";
result << it->second;
if (it != dn_exploded.end() - 1) {
result << ",";
}
}
return result.str();
}
vector < std::pair<string, string> > adclient::explode_dn(string dn) {
#if defined OPENLDAP
#ifdef LDAP21
LDAPDN *exp_dn;
#else
LDAPDN exp_dn;
#endif
int i;
struct berval la_attr;
struct berval la_value;
vector < std::pair<string, string> > dn_exploded;
int result = ldap_str2dn(dn.c_str(), &exp_dn, LDAP_DN_FORMAT_LDAPV3);
if (result != LDAP_SUCCESS || exp_dn == NULL) {
throw ADOperationalException("Wrong OU syntax", AD_OU_SYNTAX_ERROR);
}
for (i = 0; exp_dn[i] != NULL; ++i) {
#ifdef LDAP21
la_attr = (****exp_dn[i]).la_attr;
la_value = (****exp_dn[i]).la_value;
#else
la_attr = (**exp_dn[i]).la_attr;
la_value = (**exp_dn[i]).la_value;
#endif
dn_exploded.push_back( std::make_pair(la_attr.bv_val, la_value.bv_val) );
}
ldap_dnfree(exp_dn);
return dn_exploded;
}
#elif defined SUNLDAP
char** dns;
char* pcDn = strdup(dn.c_str());
dns = ldap_explode_dn(pcDn, 0);
free(pcDn);
char* next;
unsigned int i = 0;
vector < std::pair<string, string> > dn_exploded;
while ((next = dns[i]) != NULL) {
string temp(next);
size_t pos = temp.find("=");
if (pos != temp.npos) {
string first = temp.substr(0, pos);
string second = temp.substr(pos+1);
dn_exploded.push_back( std::make_pair(first, second) );
}
i++;
}
ldap_value_free(dns);
return dn_exploded;
}
#else
throw ADOperationalException("Don't know how to do explode_dn", 255);
}
#endif
void adclient::CreateComputer(string name, string container) {
/*
It creates computer with given name in given container.
It will create container if not exists.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
LDAPMod *attrs[4];
LDAPMod attr1, attr2, attr3;
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
if (!ifDNExists(container)) CreateOU(container);
string dn = "CN=" + name + "," + container;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
char *objectClass_values[] = {"top", "person", "organizationalPerson",
"user", "computer", NULL};
char *name_values[2];
char *accountControl_values[] = {"4128", NULL};
string upn;
string domain;
attr1.mod_op = LDAP_MOD_ADD;
attr1.mod_type = "objectClass";
attr1.mod_values = objectClass_values;
std::transform(name.begin(), name.end(), name.begin(), ::toupper);
name += "$";
name_values[0] = strdup(name.c_str());
name_values[1] = NULL;
attr2.mod_op = LDAP_MOD_ADD;
attr2.mod_type = "sAMAccountName";
attr2.mod_values = name_values;
attr3.mod_op = LDAP_MOD_ADD;
attr3.mod_type = "userAccountControl";
attr3.mod_values = accountControl_values;
#pragma GCC diagnostic pop
attrs[0] = &attr1;
attrs[1] = &attr2;
attrs[2] = &attr3;
attrs[3] = NULL;
int result;
result = ldap_add_ext_s(ds, dn.c_str(), attrs, NULL, NULL);
free(name_values[0]);
if (result != LDAP_SUCCESS) {
string error_msg = "Error in CreateComputer, ldap_add_ext_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
void adclient::RenameDN(string object, string cn) {
string dn = getObjectDN(object);
mod_rename(dn, cn);
}
void adclient::RenameGroup(string group, string shortname, string cn) {
string dn = getObjectDN(group);
if (cn.empty()) {
cn = shortname;
}
mod_replace(dn, "sAMAccountName", shortname);
mod_rename(dn, cn);
}
void adclient::RenameUser(string user, string shortname, string cn) {
string dn = getObjectDN(user);
if (cn.empty()) {
cn = shortname;
}
mod_replace(dn, "sAMAccountName", shortname);
string upn = shortname + "@" + dn2domain(dn);
mod_replace(dn, "userPrincipalName", upn);
mod_rename(dn, cn);
}
void adclient::CreateUser(string cn, string container, string user_short) {
/*
It creates user with given common name and short name in given container.
It will create container if not exists.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
LDAPMod *attrs[5];
LDAPMod attr1, attr2, attr3, attr4;
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
if (!ifDNExists(container)) CreateOU(container);
string dn = "CN=" + cn + "," + container;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
char *objectClass_values[] = {"user", NULL};
char *name_values[2];
char *accountControl_values[] = {"66050", NULL};
char *upn_values[2];
string upn;
string domain;
attr1.mod_op = LDAP_MOD_ADD;
attr1.mod_type = "objectClass";
attr1.mod_values = objectClass_values;
name_values[0] = strdup(user_short.c_str());
name_values[1] = NULL;
attr2.mod_op = LDAP_MOD_ADD;
attr2.mod_type = "sAMAccountName";
attr2.mod_values = name_values;
attr3.mod_op = LDAP_MOD_ADD;
attr3.mod_type = "userAccountControl";
attr3.mod_values = accountControl_values;
domain = dn2domain(dn);
upn = user_short + "@" + domain;
upn_values[0] = strdup(upn.c_str());
upn_values[1] = NULL;
attr4.mod_op = LDAP_MOD_ADD;
attr4.mod_type = "userPrincipalName";
attr4.mod_values = upn_values;
#pragma GCC diagnostic pop
attrs[0] = &attr1;
attrs[1] = &attr2;
attrs[2] = &attr3;
attrs[3] = &attr4;
attrs[4] = NULL;
int result;
result = ldap_add_ext_s(ds, dn.c_str(), attrs, NULL, NULL);
free(name_values[0]);
free(upn_values[0]);
if (result != LDAP_SUCCESS) {
string error_msg = "Error in CreateUser, ldap_add_ext_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
void adclient::CreateGroup(string cn, string container, string group_short) {
/*
It creates new global security group with
samaccountname=group_short and distinguishedName="CN=cn,container"
It will create container if not exists.
It returns nothing if operation was successfull, throw ADOperationalException - otherwise.
*/
if (ds == NULL) throw ADSearchException("Failed to use LDAP connection handler", AD_LDAP_CONNECTION_ERROR);
LDAPMod *attrs[4];
LDAPMod attr1, attr2, attr3;
if (!ifDNExists(container)) CreateOU(container);
string dn = "CN=" + cn + "," + container;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wwrite-strings"
char *objectClass_values[] = {"group", NULL};
char *name_values[2];
char *sAMAccountName_values[2];
attr1.mod_op = LDAP_MOD_ADD;
attr1.mod_type = "objectClass";
attr1.mod_values = objectClass_values;
name_values[0] = strdup(group_short.c_str());
name_values[1] = NULL;
attr2.mod_op = LDAP_MOD_ADD;
attr2.mod_type = "name";
attr2.mod_values = name_values;
sAMAccountName_values[0] = strdup(group_short.c_str());
sAMAccountName_values[1] = NULL;
attr3.mod_op = LDAP_MOD_ADD;
attr3.mod_type = "sAMAccountName";
attr3.mod_values = sAMAccountName_values;
#pragma GCC diagnostic pop
attrs[0] = &attr1;
attrs[1] = &attr2;
attrs[2] = &attr3;
attrs[3] = NULL;
int result;
result = ldap_add_ext_s(ds, dn.c_str(), attrs, NULL, NULL);
free(name_values[0]);
free(sAMAccountName_values[0]);
if (result != LDAP_SUCCESS) {
string error_msg = "Error in CreateGroup, ldap_add_ext_s: ";
error_msg.append(ldap_err2string(result));
throw ADOperationalException(error_msg, result);
}
}
struct berval adclient::password2berval(string password) {
/*
Convert string password to unicode quoted bervalue.
Caller must explicitly free bv_val field with delete[].
*/
struct berval pw;