summaryrefslogtreecommitdiffstats
path: root/daemons/ipa-slapi-plugins/ipa-pwd-extop/ipa_pwd_extop.c
blob: 09c877f7010d3cc252c9f38e827cd33b63dea3b6 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
/** BEGIN COPYRIGHT BLOCK
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Additional permission under GPLv3 section 7:
 *
 * In the following paragraph, "GPL" means the GNU General Public
 * License, version 3 or any later version, and "Non-GPL Code" means
 * code that is governed neither by the GPL nor a license
 * compatible with the GPL.
 *
 * You may link the code of this Program with Non-GPL Code and convey
 * linked combinations including the two, provided that such Non-GPL
 * Code only links to the code of this Program through those well
 * defined interfaces identified in the file named EXCEPTION found in
 * the source code files (the "Approved Interfaces"). The files of
 * Non-GPL Code may instantiate templates or use macros or inline
 * functions from the Approved Interfaces without causing the resulting
 * work to be covered by the GPL. Only the copyright holders of this
 * Program may make changes or additions to the list of Approved
 * Interfaces.
 *
 * Authors:
 * Simo Sorce <ssorce@redhat.com>
 *
 * Copyright (C) 2007-2010 Red Hat, Inc.
 * All rights reserved.
 * END COPYRIGHT BLOCK **/

#include "ipapwd.h"
#include "util.h"
#include "../libotp/otp_config.h"
#include "ipa_asn1.h"

/*
 * Password Modify - LDAP Extended Operation.
 * RFC 3062
 *
 *
 * This plugin implements the "Password Modify - LDAP3"
 * extended operation for LDAP. The plugin function is called by
 * the server if an LDAP client request contains the OID:
 * "1.3.6.1.4.1.4203.1.11.1".
 *
 */

/* ber tags for the PasswdModifyRequestValue sequence */
#define LDAP_EXTOP_PASSMOD_TAG_USERID	0x80U
#define LDAP_EXTOP_PASSMOD_TAG_OLDPWD	0x81U
#define LDAP_EXTOP_PASSMOD_TAG_NEWPWD	0x82U

/* ber tags for the PasswdModifyResponseValue sequence */
#define LDAP_EXTOP_PASSMOD_TAG_GENPWD	0x80U

/* OID of the extended operation handled by this plug-in */
#define EXOP_PASSWD_OID	"1.3.6.1.4.1.4203.1.11.1"

/* OID to retrieve keytabs */
#define KEYTAB_SET_OID "2.16.840.1.113730.3.8.10.1"
#define KEYTAB_RET_OID "2.16.840.1.113730.3.8.10.2"



/* base DN of IPA realm tree */
const char *ipa_realm_tree;
/* dn of Kerberos realm entry */
const char *ipa_realm_dn;
const char *ipa_pwd_config_dn;
const char *ipa_etc_config_dn;
const char *ipa_changepw_principal_dn;

Slapi_PluginDesc ipapwd_plugin_desc = {
    IPAPWD_FEATURE_DESC,
    "FreeIPA project",
    "FreeIPA/1.0",
    IPAPWD_PLUGIN_DESC
};

void *ipapwd_plugin_id;
static int usetxn = 0;

extern struct otp_config *otp_config;

void *ipapwd_get_plugin_id(void)
{
    return ipapwd_plugin_id;
}

static void filter_keys(struct ipapwd_krbcfg *krbcfg,
                        struct ipapwd_keyset *kset)
{
    int i, j;

    for (i = 0; i < kset->num_keys; i++) {
        for (j = 0; j < krbcfg->num_supp_encsalts; j++) {
            if (kset->keys[i].key_data_type[0] ==
                    krbcfg->supp_encsalts[j].ks_enctype) {
                break;
            }
        }
        if (j == krbcfg->num_supp_encsalts) { /* not valid */

            /* free key */
            free(kset->keys[i].key_data_contents[0]);
            free(kset->keys[i].key_data_contents[1]);

            /* move all remaining keys up by one */
            kset->num_keys -= 1;

            for (j = i; j < kset->num_keys; j++) {
                kset->keys[j] = kset->keys[j + 1];
            }

            /* new key has been moved to this position, make sure
             * we do not skip it, by neutralizing next increment */
            i--;
        }
    }
}

static void filter_enctypes(struct ipapwd_krbcfg *krbcfg,
                            krb5_key_salt_tuple *kenctypes,
                            int *num_kenctypes)
{
    /* first filter for duplicates */
    for (int i = 0; i + 1 < *num_kenctypes; i++) {
        for (int j = i + 1; j < *num_kenctypes; j++) {
            if (kenctypes[i].ks_enctype == kenctypes[j].ks_enctype) {
                /* duplicate, filter out */
                for (int k = j; k + 1 < *num_kenctypes; k++) {
                    kenctypes[k].ks_enctype = kenctypes[k + 1].ks_enctype;
                    kenctypes[k].ks_salttype = kenctypes[k + 1].ks_salttype;
                }
                (*num_kenctypes)--;
                j--;
            }
        }
    }

    /* then filter for supported */
    for (int i = 0; i < *num_kenctypes; i++) {
        int j;

        /* Check if supported */
        for (j = 0; j < krbcfg->num_supp_encsalts; j++) {
            if (kenctypes[i].ks_enctype ==
                                    krbcfg->supp_encsalts[j].ks_enctype) {
                break;
            }
        }
        if (j == krbcfg->num_supp_encsalts) {
            /* Unsupported, filter out */
            for (int k = i; k + 1 < *num_kenctypes; k++) {
                kenctypes[k].ks_enctype = kenctypes[k + 1].ks_enctype;
                kenctypes[k].ks_salttype = kenctypes[k + 1].ks_salttype;
            }
            (*num_kenctypes)--;
            i--;
        }
    }
}

static int ipapwd_to_ldap_pwpolicy_error(int ipapwderr)
{
    switch (ipapwderr) {
    case IPAPWD_POLICY_ACCOUNT_EXPIRED:
        return LDAP_PWPOLICY_PWDMODNOTALLOWED;
    case IPAPWD_POLICY_PWD_TOO_YOUNG:
        return LDAP_PWPOLICY_PWDTOOYOUNG;
    case IPAPWD_POLICY_PWD_TOO_SHORT:
        return LDAP_PWPOLICY_PWDTOOSHORT;
    case IPAPWD_POLICY_PWD_IN_HISTORY:
        return LDAP_PWPOLICY_PWDINHISTORY;
    case IPAPWD_POLICY_PWD_COMPLEXITY:
        return LDAP_PWPOLICY_INVALIDPWDSYNTAX;
    }
    /* in case of unhandled error return access denied */
    return LDAP_PWPOLICY_PWDMODNOTALLOWED;
}


static int ipapwd_chpwop(Slapi_PBlock *pb, struct ipapwd_krbcfg *krbcfg)
{
	char 		*bindDN = NULL;
	char		*authmethod = NULL;
	char		*dn = NULL;
	char		*oldPasswd = NULL;
	char		*newPasswd = NULL;
	char		*errMesg = NULL;
	int             ret=0, rc=0, is_root=0;
	ber_tag_t	tag=0;
	ber_len_t	len=-1;
	struct berval	*extop_value = NULL;
	BerElement	*ber = NULL;
	Slapi_Entry *targetEntry=NULL;
	Slapi_Value *objectclass=NULL;
	char *attrlist[] = {"*", "passwordHistory", NULL };
	struct ipapwd_data pwdata;
	int is_krb, is_smb, is_ipant;
    char *principal = NULL;
	Slapi_PBlock *chpwop_pb = NULL;

	/* Get the ber value of the extended operation */
	slapi_pblock_get(pb, SLAPI_EXT_OP_REQ_VALUE, &extop_value);

    if (extop_value == NULL ||
        (extop_value->bv_len == 0 || extop_value->bv_val == NULL)) {
        errMesg = "PasswdModify Request empty.\n";
        rc = LDAP_UNWILLING_TO_PERFORM;
        goto free_and_return;
    }

	if ((ber = ber_init(extop_value)) == NULL)
	{
		errMesg = "PasswdModify Request decode failed.\n";
		rc = LDAP_PROTOCOL_ERROR;
		goto free_and_return;
	}

	/* Format of request to parse
	 *
	 * PasswdModifyRequestValue ::= SEQUENCE {
	 * userIdentity    [0]  OCTET STRING OPTIONAL
	 * oldPasswd       [1]  OCTET STRING OPTIONAL
	 * newPasswd       [2]  OCTET STRING OPTIONAL }
	 *
	 * The request value field is optional. If it is
	 * provided, at least one field must be filled in.
	 */

	/* ber parse code */
	if ( ber_scanf( ber, "{") == LBER_ERROR )
	{
		/* The request field wasn't provided.  We'll
		 * now try to determine the userid and verify
		 * knowledge of the old password via other
		 * means.
		 */
		goto parse_req_done;
	} else {
		tag = ber_peek_tag( ber, &len);
	}

	/* identify userID field by tags */
	if (tag == LDAP_EXTOP_PASSMOD_TAG_USERID )
	{
		if (ber_scanf(ber, "a", &dn) == LBER_ERROR) {
			slapi_ch_free_string(&dn);
			errMesg = "ber_scanf failed at userID parse.\n";
			LOG_FATAL("%s", errMesg);
			rc = LDAP_PROTOCOL_ERROR;
			goto free_and_return;
		}

		tag = ber_peek_tag(ber, &len);
	}

	/* identify oldPasswd field by tags */
	if (tag == LDAP_EXTOP_PASSMOD_TAG_OLDPWD )
	{
		if (ber_scanf(ber, "a", &oldPasswd) == LBER_ERROR) {
			errMesg = "ber_scanf failed at oldPasswd parse.\n";
			LOG_FATAL("%s", errMesg);
			rc = LDAP_PROTOCOL_ERROR;
			goto free_and_return;
		}
		tag = ber_peek_tag(ber, &len);
	}

	/* identify newPasswd field by tags */
	if (tag == LDAP_EXTOP_PASSMOD_TAG_NEWPWD )
	{
		if (ber_scanf(ber, "a", &newPasswd) == LBER_ERROR) {
			errMesg = "ber_scanf failed at newPasswd parse.\n";
			LOG_FATAL("%s", errMesg);
			rc = LDAP_PROTOCOL_ERROR;
			goto free_and_return;
		}
	}

parse_req_done:
	/* Uncomment for debugging, otherwise we don't want to leak the
	 * password values into the log... */
	/* LDAPDebug( LDAP_DEBUG_ARGS, "passwd: dn (%s), oldPasswd (%s),
	 * 		newPasswd (%s)\n", dn, oldPasswd, newPasswd); */


	 /* Get Bind DN */
	 slapi_pblock_get(pb, SLAPI_CONN_DN, &bindDN);

	 /* If the connection is bound anonymously, we must refuse
	  * to process this operation. */
	if (bindDN == NULL || *bindDN == '\0') {
	 	/* Refuse the operation because they're bound anonymously */
		errMesg = "Anonymous Binds are not allowed.\n";
		rc = LDAP_INSUFFICIENT_ACCESS;
		goto free_and_return;
	}

	/* A new password was not supplied in the request, and we do not support
	 * password generation yet.
	 */
	if (newPasswd == NULL || *newPasswd == '\0') {
		errMesg = "Password generation not implemented.\n";
		rc = LDAP_UNWILLING_TO_PERFORM;
		goto free_and_return;
	}

	if (oldPasswd == NULL || *oldPasswd == '\0') {
		/* If user is authenticated, they already gave their password during
		the bind operation (or used sasl or client cert auth or OS creds) */
		slapi_pblock_get(pb, SLAPI_CONN_AUTHMETHOD, &authmethod);
		if (!authmethod || !strcmp(authmethod, SLAPD_AUTH_NONE)) {
			errMesg = "User must be authenticated to the directory server.\n";
			rc = LDAP_INSUFFICIENT_ACCESS;
			goto free_and_return;
		}
	}

	 /* Determine the target DN for this operation */
	 /* Did they give us a DN ? */
	if (dn == NULL || *dn == '\0') {
	 	/* Get the DN from the bind identity on this connection */
		dn = slapi_ch_strdup(bindDN);
		LOG_TRACE("Missing userIdentity in request, "
                          "using the bind DN instead.\n");
	}

	 if (slapi_pblock_set( pb, SLAPI_ORIGINAL_TARGET, dn )) {
		LOG_FATAL("slapi_pblock_set failed!\n");
		rc = LDAP_OPERATIONS_ERROR;
		goto free_and_return;
	 }

	if (usetxn) {
                Slapi_DN *sdn = slapi_sdn_new_dn_byref(dn);
                Slapi_Backend *be = slapi_be_select(sdn);
                slapi_sdn_free(&sdn);
                if (be) {
			chpwop_pb = slapi_pblock_new();
			if (slapi_pblock_set(chpwop_pb, SLAPI_BACKEND, be)) {
				LOG_FATAL("slapi_pblock_set failed!\n");
				rc = LDAP_OPERATIONS_ERROR;
				goto free_and_return;
			}
			rc = slapi_back_transaction_begin(chpwop_pb);
			if (rc) {
				LOG_FATAL("failed to start transaction\n");
			}
		} else {
			LOG_FATAL("failed to get be backend from %s\n", dn);
		}
	}

	 /* Now we have the DN, look for the entry */
	 ret = ipapwd_getEntry(dn, &targetEntry, attrlist);
	 /* If we can't find the entry, then that's an error */
	 if (ret) {
	 	/* Couldn't find the entry, fail */
		errMesg = "No such Entry exists.\n" ;
		rc = LDAP_NO_SUCH_OBJECT;
		goto free_and_return;
	 }

    if (dn) {
        Slapi_DN *bind_sdn;
        Slapi_DN *target_sdn;

        /* if the user changing the password is self, we must request the
         * old password and verify it matches the current one before
         * proceeding with the password change */
        bind_sdn = slapi_sdn_new_dn_byref(bindDN);
        target_sdn = slapi_sdn_new_dn_byref(dn);
        if (!bind_sdn || !target_sdn) {
            LOG_OOM();
            rc = LDAP_OPERATIONS_ERROR;
            goto free_and_return;
        }
        /* this one will normalize and compare, so difference in case will be
         * correctly handled */
        ret = slapi_sdn_compare(bind_sdn, target_sdn);
        if (ret == 0) {
            Slapi_Value *cpw[2] = { NULL, NULL };
            Slapi_Value *pw;
            char *cur_pw;

            if (oldPasswd == NULL || *oldPasswd == '\0') {
                LOG_FATAL("Old password was not provided!\n");
                rc = LDAP_INVALID_CREDENTIALS;
                goto free_and_return;
            }

            /* if the user is changing his own password we need to check that
             * oldPasswd matches the current password */
            cur_pw = slapi_entry_attr_get_charptr(targetEntry,
                                                  "userPassword");
            if (!cur_pw) {
                LOG_FATAL("User has no current password?\n");
                rc = LDAP_UNWILLING_TO_PERFORM;
                goto free_and_return;
            }

            cpw[0] = slapi_value_new_string(cur_pw);
            pw = slapi_value_new_string(oldPasswd);
            if (!cpw[0] || !pw) {
                LOG_OOM();
                rc = LDAP_OPERATIONS_ERROR;
                goto free_and_return;
            }

            ret = slapi_pw_find_sv(cpw, pw);

            slapi_value_free(&cpw[0]);
            slapi_value_free(&pw);

            if (ret != 0) {
                LOG_TRACE("Invalid password!\n");
                rc = LDAP_INVALID_CREDENTIALS;
                goto free_and_return;
            }
        }
    } else {
        LOG_TRACE("Undefined target DN!\n");
        rc = LDAP_OPERATIONS_ERROR;
        goto free_and_return;
    }

	 rc = ipapwd_entry_checks(pb, targetEntry,
				&is_root, &is_krb, &is_smb, &is_ipant,
				SLAPI_USERPWD_ATTR, SLAPI_ACL_WRITE);
	 if (rc) {
		goto free_and_return;
	 }

	/* When setting the password for host principals do not set kerberos
	 * keys */
	objectclass = slapi_value_new_string("ipaHost");
	if ((slapi_entry_attr_has_syntax_value(targetEntry, SLAPI_ATTR_OBJECTCLASS, objectclass)) == 1) {
		is_krb = 0;
	}
	slapi_value_free(&objectclass);

	 /* First thing to do is to ask access control if the bound identity has
	  * rights to modify the userpassword attribute on this entry. If not,
	  * then we fail immediately with insufficient access. This means that
	  * we don't leak any useful information to the client such as current
	  * password wrong, etc.
	  */

	is_root = slapi_dn_isroot(bindDN);
	if (slapi_pblock_set(pb, SLAPI_REQUESTOR_ISROOT, &is_root)) {
		LOG_FATAL("slapi_pblock_set failed!\n");
		rc = LDAP_OPERATIONS_ERROR;
		goto free_and_return;
	}

	/* In order to perform the access control check, we need to select a
	 * backend (even though we don't actually need it otherwise).
	 */
	{
		Slapi_Backend *be = NULL;

		be = slapi_be_select(slapi_entry_get_sdn(targetEntry));
		if (NULL == be) {
			errMesg = "Failed to find backend for target entry";
			rc = LDAP_OPERATIONS_ERROR;
			goto free_and_return;
		}
		if (slapi_pblock_set(pb, SLAPI_BACKEND, be)) {
			LOG_FATAL("slapi_pblock_set failed!\n");
			rc = LDAP_OPERATIONS_ERROR;
			goto free_and_return;
		}
	}

	ret = slapi_access_allowed( pb, targetEntry, "krbPrincipalKey", NULL, SLAPI_ACL_WRITE );
	if ( ret != LDAP_SUCCESS ) {
		errMesg = "Insufficient access rights\n";
		rc = LDAP_INSUFFICIENT_ACCESS;
		goto free_and_return;
	}

	/* Now we have the entry which we want to modify
 	 * They gave us a password (old), check it against the target entry
	 * Is the old password valid ?
	 */
	if (oldPasswd && *oldPasswd) {
		/* If user is authenticated, they already gave their password
		 * during the bind operation (or used sasl or client cert auth
		 * or OS creds) */
		LOG_TRACE("oldPasswd provided, but we will ignore it");
	}

	memset(&pwdata, 0, sizeof(pwdata));
	pwdata.target = targetEntry;
	pwdata.dn = dn;
	pwdata.password = newPasswd;
	pwdata.timeNow = time(NULL);
	pwdata.changetype = IPA_CHANGETYPE_NORMAL;

    /*
     *  (technically strcasecmp to compare DNs is not absolutely correct,
     *  but it should work for the cases we care about here)
     */

	/* determine type of password change */
    /* special cases */
    if ((strcasecmp(dn, bindDN) != 0) &&
        (strcasecmp(ipa_changepw_principal_dn, bindDN) != 0)) {
        int i;

        pwdata.changetype = IPA_CHANGETYPE_ADMIN;

        for (i = 0; i < krbcfg->num_passsync_mgrs; i++) {
            if (strcasecmp(krbcfg->passsync_mgrs[i], bindDN) == 0) {
                pwdata.changetype = IPA_CHANGETYPE_DSMGR;
                break;
            }
        }
    }

	/* check the policy */
	ret = ipapwd_CheckPolicy(&pwdata);
	if (ret) {
		errMesg = ipapwd_error2string(ret);
		if (ret == IPAPWD_POLICY_ERROR) {
			errMesg = "Internal error";
			rc = ret;
		} else {
			ret = ipapwd_to_ldap_pwpolicy_error(ret);
			slapi_pwpolicy_make_response_control(pb, -1, -1, ret);
			rc = LDAP_CONSTRAINT_VIOLATION;
		}
		goto free_and_return;
	}

	/* Now we're ready to set the kerberos key material */
	ret = ipapwd_SetPassword(krbcfg, &pwdata, is_krb);
	if (ret != LDAP_SUCCESS) {
		/* Failed to modify the password,
		 * e.g. because insufficient access allowed */
		errMesg = "Failed to update password";
		if (ret > 0) {
			rc = ret;
		} else {
			rc = LDAP_OPERATIONS_ERROR;
		}
		goto free_and_return;
	}

	LOG_TRACE("<= result: %d\n", rc);

    if (pwdata.changetype == IPA_CHANGETYPE_NORMAL) {
        principal = slapi_entry_attr_get_charptr(pwdata.target,
                                                 "krbPrincipalName");
    } else {
        principal = slapi_ch_smprintf("root/admin@%s", krbcfg->realm);
    }
    ipapwd_set_extradata(pwdata.dn, principal, pwdata.timeNow);

	/* Free anything that we allocated above */
free_and_return:
	if (usetxn && chpwop_pb) {
		if (rc) { /* fails */
			slapi_back_transaction_abort(chpwop_pb);
		} else {
			slapi_back_transaction_commit(chpwop_pb);
		}
		slapi_pblock_destroy(chpwop_pb);
	}
	slapi_ch_free_string(&oldPasswd);
	slapi_ch_free_string(&newPasswd);
	/* Either this is the same pointer that we allocated and set above,
	 * or whoever used it should have freed it and allocated a new
	 * value that we need to free here */
    ret = slapi_pblock_get(pb, SLAPI_ORIGINAL_TARGET, &dn);
    if (ret) {
        LOG_TRACE("Failed to get SLAPI_ORIGINAL_TARGET\n");
    }
	slapi_ch_free_string(&dn);
    ret = slapi_pblock_set(pb, SLAPI_ORIGINAL_TARGET, NULL);
    if (ret) {
        LOG_TRACE("Failed to clear SLAPI_ORIGINAL_TARGET\n");
    }
	slapi_ch_free_string(&authmethod);
    slapi_ch_free_string(&principal);

	if (targetEntry) slapi_entry_free(targetEntry);
	if (ber) ber_free(ber, 1);

	LOG("%s", errMesg ? errMesg : "success");
	slapi_send_ldap_result(pb, rc, NULL, errMesg, 0, NULL);

	return SLAPI_PLUGIN_EXTENDED_SENT_RESULT;

}

static char *check_service_name(krb5_context krbctx, char *svc)
{
    krb5_principal krbname = NULL;
    krb5_error_code krberr;
    char *name = NULL;

    krberr = krb5_parse_name(krbctx, svc, &krbname);
    if (krberr) {
        LOG_FATAL("krb5_parse_name failed\n");
    } else {
        /* invert so that we get the canonical form (add REALM if not present
         * for example) */
        krberr = krb5_unparse_name(krbctx, krbname, &name);
        if (krberr) {
            LOG_FATAL("krb5_unparse_name failed\n");
        }
    }

    krb5_free_principal(krbctx, krbname);
    return name;
}

static Slapi_Backend *get_realm_backend(void)
{
    Slapi_Backend *be;
    Slapi_DN *sdn;

    sdn = slapi_sdn_new_dn_byval(ipa_realm_dn);
    if (!sdn) return NULL;
    be = slapi_be_select(sdn);
    slapi_sdn_free(&sdn);
    return be;
}

static const char *get_realm_base_dn(void)
{
    const Slapi_DN *bsdn;
    Slapi_Backend *be;

    /* Find ancestor base DN */
    be = get_realm_backend();
    if (!be) return NULL;

    bsdn = slapi_be_getsuffix(be, 0);
    if (!bsdn) return NULL;

    return slapi_sdn_get_dn(bsdn);
}

static Slapi_Entry *get_entry_by_principal(const char *principal)
{
    const char *bdn;
    char *filter = NULL;
    Slapi_PBlock *pb = NULL;
    char *attrlist[] = { "krbPrincipalKey", "krbLastPwdChange",
                         "userPassword", "krbPrincipalName",
                         "enrolledBy", NULL };
    Slapi_Entry **es = NULL;
    int res, ret, i;
    Slapi_Entry *entry = NULL;

    /* Find ancestor base DN */
    bdn = get_realm_base_dn();
    if (!bdn) {
        LOG_TRACE("Search for Base DN failed\n");
        goto free_and_return;
    }

    filter = slapi_ch_smprintf("(krbPrincipalName=%s)", principal);
    if (!filter) {
        LOG_TRACE("Building filter failed\n");
        goto free_and_return;
    }

    pb = slapi_pblock_new();
    slapi_search_internal_set_pb(pb, bdn, LDAP_SCOPE_SUBTREE, filter,
                                 attrlist, 0,
                                 NULL, /* Controls */ NULL, /* UniqueID */
                                 ipapwd_plugin_id, 0); /* Flags */

    /* do search the tree */
    ret = slapi_search_internal_pb(pb);
    slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &res);
    if (ret == -1 || res != LDAP_SUCCESS) {
        LOG_TRACE("Search for Principal failed, err (%d)\n", res ? res : ret);
        goto free_and_return;
    }

    /* get entries */
    slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &es);
    if (!es) {
        LOG_TRACE("No entries ?!");
        goto free_and_return;
    }

    /* count entries */
    for (i = 0; es[i]; i++) /* count */ ;

    /* if there is none or more than one, freak out */
    if (i != 1) {
        LOG_TRACE("Too many entries, or entry no found (%d)", i);
        goto free_and_return;
    }
    entry = slapi_entry_dup(es[0]);

free_and_return:
    if (pb) {
        slapi_free_search_results_internal(pb);
        slapi_pblock_destroy(pb);
    }
    if (filter) slapi_ch_free_string(&filter);
    return entry;
}

static bool is_allowed_to_access_attr(Slapi_PBlock *pb, char *bindDN,
                                      Slapi_Entry *targetEntry,
                                      const char *attrname,
                                      struct berval *value,
                                      int access)
{
    Slapi_Backend *be;
    int is_root = 0;
    int ret;

    is_root = slapi_dn_isroot(bindDN);
    if (slapi_pblock_set(pb, SLAPI_REQUESTOR_ISROOT, &is_root)) {
        LOG_FATAL("slapi_pblock_set failed!\n");
        return false;
    }

    /* In order to perform the access control check, we need to select a
     * backend (even though we don't actually need it otherwise).
     */
    be = get_realm_backend();
    if (!be) {
        LOG_FATAL("Could not fetch REALM backend!");
        return false;
    }
    if (slapi_pblock_set(pb, SLAPI_BACKEND, be)) {
        LOG_FATAL("slapi_pblock_set failed!\n");
        return false;
    }

    ret = slapi_access_allowed(pb, targetEntry, discard_const(attrname),
                               value, access);
    if (ret != LDAP_SUCCESS) {
        LOG_FATAL("slapi_access_allowed does not allow %s to %s%s!\n",
                  (access == SLAPI_ACL_WRITE)?"WRITE":"READ",
                  attrname, value?"(value specified)":"");
        return false;
    }

    return true;
}

static int set_krbLastPwdChange(Slapi_Mods *smods, time_t now)
{
    char tstr[GENERALIZED_TIME_LENGTH + 1];
    struct tm utctime;

    /* change Last Password Change field with the current date */
    if (!gmtime_r(&now, &utctime)) {
        LOG_FATAL("failed to retrieve current date (buggy gmtime_r ?)\n");
        return LDAP_OPERATIONS_ERROR;
    }
    strftime(tstr, GENERALIZED_TIME_LENGTH + 1, "%Y%m%d%H%M%SZ", &utctime);
    slapi_mods_add_string(smods, LDAP_MOD_REPLACE, "krbLastPwdChange", tstr);
    return LDAP_SUCCESS;
}

static void remove_user_password(Slapi_Mods *smods,
                                 Slapi_Entry *targetEntry, char *bindDN)
{
    Slapi_Value *objectclass = NULL;
    char *krbLastPwdChange = NULL;
    char *enrolledBy = NULL;
    char *pw = NULL;
    int ret;

    objectclass = slapi_value_new_string("ipaHost");
    pw = slapi_entry_attr_get_charptr(targetEntry, "userPassword");
    ret = slapi_entry_attr_has_syntax_value(targetEntry,
                                            SLAPI_ATTR_OBJECTCLASS,
                                            objectclass);
    if (ret == 1) {
        krbLastPwdChange = slapi_entry_attr_get_charptr(targetEntry,
                                                        "krbLastPwdChange");
        enrolledBy = slapi_entry_attr_get_charptr(targetEntry, "enrolledBy");
        if (!enrolledBy) {
            slapi_mods_add_string(smods, LDAP_MOD_ADD, "enrolledBy", bindDN);
        }
        if ((NULL != pw) && (NULL == krbLastPwdChange)) {
            slapi_mods_add_mod_values(smods, LDAP_MOD_DELETE,
                                      "userPassword", NULL);
            LOG_TRACE("Removing userPassword from host entry\n");
        }
    }
    if (krbLastPwdChange) slapi_ch_free_string(&krbLastPwdChange);
    if (enrolledBy) slapi_ch_free_string(&enrolledBy);
    if (pw) slapi_ch_free_string(&pw);
    if (objectclass) slapi_value_free(&objectclass);
}

static int store_new_keys(Slapi_Entry *target, char *svcname, char *bind_dn,
                          Slapi_Value **svals, char **_err_msg)
{
    int rc = LDAP_OPERATIONS_ERROR;
    char *err_msg = NULL;
    Slapi_Mods *smods = NULL;
    time_t time_now = time(NULL);

    smods = slapi_mods_new();
    slapi_mods_add_mod_values(smods, LDAP_MOD_REPLACE,
                              "krbPrincipalKey", svals);
    rc = set_krbLastPwdChange(smods, time_now);
    if (rc) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_FATAL("Failed to set krbLastPwdChange");
        err_msg = "Internal error while storing keytab data\n";
        goto done;
    }

    /* If we are creating a keytab for a host service, attempt to remove
     * the userPassword attribute if it exists
     */
    remove_user_password(smods, target, bind_dn);

    /* commit changes */
    rc = ipapwd_apply_mods(slapi_entry_get_dn_const(target), smods);
    if (rc != LDAP_SUCCESS) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_FATAL("Failed to apply mods");
        err_msg = "Internal error while saving keys\n";
        goto done;
    }

    rc = ipapwd_set_extradata(slapi_entry_get_dn_const(target),
                              svcname, time_now);
    if (rc != LDAP_SUCCESS) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_FATAL("Failed to set extradata");
        err_msg = "Internal error while saving keytab extradata\n";
        goto done;
    }

    rc = LDAP_SUCCESS;

done:
    if (smods) slapi_mods_free(&smods);
    *_err_msg = err_msg;
    return rc;
}

/* Format of request to parse
 *
 * KeytabSetRequest ::= SEQUENCE {
 *     serviceIdentity OCTET STRING
 *     keys            SEQUENCE OF KrbKey,
 *     ...
 * }
 *
 * KrbKey ::= SEQUENCE {
 *     key       [0] EncryptionKey,
 *     salt      [1] KrbSalt OPTIONAL,
 *     s2kparams [2] OCTET STRING OPTIONAL,
 *     ...
 * }
 *
 * EncryptionKey ::= SEQUENCE {
 *     keytype   [0] Int32,
 *     keyvalue  [1] OCTET STRING
 * }
 *
 * KrbSalt ::= SEQUENCE {
 *     type      [0] Int32,
 *     salt      [1] OCTET STRING OPTIONAL
 * }
 */

#define SKREQ_SALT_TAG (LBER_CLASS_CONTEXT | LBER_CONSTRUCTED | 1)
#define SKREQ_SALTVALUE_TAG (LBER_CLASS_CONTEXT | LBER_CONSTRUCTED | 1)
#define SKREQ_S2KPARAMS_TAG (LBER_CLASS_CONTEXT | LBER_CONSTRUCTED | 2)

/* The returned krb5_key_data kvno is set to 0 for all keys, the caller,
 * is responsible for fixing it up if necessary before using the data */
static int decode_setkeytab_request(krb5_context krbctx,
                                    krb5_keyblock *kmkey, int mkvno,
                                    struct berval *extop, char **_svcname,
                                    struct ipapwd_keyset **_kset,
                                    char **_err_msg) {
    int rc = LDAP_OPERATIONS_ERROR;
    char *err_msg = NULL;
    BerElement *ber = NULL;
    char *svcname = NULL;
    ber_tag_t rtag;
    ber_len_t tlen;
    struct ipapwd_keyset *kset = NULL;

    ber = ber_init(extop);
    if (ber == NULL) {
        rc = LDAP_PROTOCOL_ERROR;
        err_msg = "KeytabSet Request decode failed.\n";
        goto done;
    }

    /* ber parse code */
    rtag = ber_scanf(ber, "{a{", &svcname);
    if (rtag == LBER_ERROR) {
        rc = LDAP_PROTOCOL_ERROR;
        LOG_FATAL("ber_scanf failed to fecth service name\n");
        err_msg = "Invalid payload.\n";
        goto done;
    }

    kset = calloc(1, sizeof(struct ipapwd_keyset));
    if (!kset) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_OOM();
        err_msg = "Internal error.\n";
        goto done;
    }

    /* this encoding assumes all keys have the same kvno */
    /* major-vno = 1 and minor-vno = 1 */
    kset->major_vno = 1;
    kset->minor_vno = 1;
    kset->mkvno = mkvno;

    rtag = ber_peek_tag(ber, &tlen);
    for (int i = 0; rtag == LBER_SEQUENCE; i++) {
        krb5_key_data *newset;
        ber_tag_t ctag;
        ber_int_t type;
        krb5_data plain;
        krb5_enc_data cipher;
        struct berval tval;
        krb5_octet *kdata;
        krb5_int16 le_len;
        size_t klen;

        newset = realloc(kset->keys, sizeof(krb5_key_data) * (i + 1));
        if (!newset) {
            rc = LDAP_OPERATIONS_ERROR;
            LOG_OOM();
            err_msg = "Internal error.\n";
            goto done;
        }
        kset->keys = newset;
        kset->num_keys = i + 1;

        memset(&kset->keys[i], 0, sizeof(krb5_key_data));
        kset->keys[i].key_data_ver = 1;
        kset->keys[i].key_data_kvno = 0;

        /* EncryptionKey */
        rtag = ber_scanf(ber, "{t[{t[i]t[o]}]",
                         &ctag, &ctag, &type, &ctag, &tval);
        if (rtag == LBER_ERROR) {
            rc = LDAP_PROTOCOL_ERROR;
            LOG_FATAL("ber_scanf failed fetching key\n");
            err_msg = "Invalid payload.\n";
            goto done;
        }

        kset->keys[i].key_data_type[0] = type;
        plain.length = tval.bv_len;
        plain.data = tval.bv_val;

        rc = krb5_c_encrypt_length(krbctx, kmkey->enctype,
                                   plain.length, &klen);
        if (rc) {
            ber_memfree(tval.bv_val);
            rc = LDAP_OPERATIONS_ERROR;
            LOG_FATAL("krb5_c_encrypt_length failed!\n");
            err_msg = "Internal error.\n";
            goto done;
        }
        kdata = malloc(2 + klen);
        if (!kdata) {
            ber_memfree(tval.bv_val);
            rc = LDAP_OPERATIONS_ERROR;
            LOG_OOM();
            err_msg = "Internal error.\n";
            goto done;
        }
        le_len = htole16(plain.length);
        memcpy(kdata, &le_len, 2);

        kset->keys[i].key_data_length[0] = 2 + klen;
        kset->keys[i].key_data_contents[0] = kdata;

        cipher.ciphertext.length = klen;
        cipher.ciphertext.data = (char *)kdata + 2;

        rc = krb5_c_encrypt(krbctx, kmkey, 0, 0, &plain, &cipher);
        if (rc) {
            ber_memfree(tval.bv_val);
            rc = LDAP_OPERATIONS_ERROR;
            LOG_FATAL("krb5_c_encrypt failed!\n");
            err_msg = "Internal error.\n";
            goto done;
        }

        ber_memfree(tval.bv_val);

        rtag = ber_peek_tag(ber, &tlen);
        /* KrbSalt */
        if (rtag == SKREQ_SALT_TAG) {
            rtag = ber_scanf(ber, "t[{t[i]", &ctag, &ctag, &type);
            if (rtag == LBER_ERROR) {
                rc = LDAP_PROTOCOL_ERROR;
                LOG_FATAL("ber_scanf failed fetching salt\n");
                err_msg = "Invalid payload.\n";
                goto done;
            }

            kset->keys[i].key_data_ver = 2; /* we have a salt */
            kset->keys[i].key_data_type[1] = type;

            rtag = ber_peek_tag(ber, &tlen);
            if (rtag == SKREQ_SALTVALUE_TAG) {
                rtag = ber_scanf(ber, "t[o]}]", &ctag, &tval);
                if (rtag == LBER_ERROR) {
                    rc = LDAP_PROTOCOL_ERROR;
                    LOG_FATAL("ber_scanf failed fetching salt value\n");
                    err_msg = "Invalid payload.\n";
                    goto done;
                }

                kset->keys[i].key_data_length[1] = tval.bv_len;
                kset->keys[i].key_data_contents[1] = malloc(tval.bv_len);
                if (!kset->keys[i].key_data_contents[1]) {
                    ber_memfree(tval.bv_val);
                    rc = LDAP_OPERATIONS_ERROR;
                    LOG_OOM();
                    err_msg = "Internal error.\n";
                    goto done;
                }
                memcpy(kset->keys[i].key_data_contents[1],
                       tval.bv_val, tval.bv_len);
                ber_memfree(tval.bv_val);

                rtag = ber_peek_tag(ber, &tlen);
            }
        }

        /* FIXME: s2kparams - NOT implemented yet */
        if (rtag == SKREQ_S2KPARAMS_TAG) {
            rtag = ber_scanf(ber, "t[x]}", &ctag);
        } else {
            rtag = ber_scanf(ber, "}", &ctag);
        }
        if (rtag == LBER_ERROR) {
            rc = LDAP_PROTOCOL_ERROR;
            LOG_FATAL("ber_scanf failed to read key data termination\n");
            err_msg = "Invalid payload.\n";
            goto done;
        }

        rtag = ber_peek_tag(ber, &tlen);
    }

    rc = LDAP_SUCCESS;

done:
    if (rc != LDAP_SUCCESS) {
        if (kset) ipapwd_keyset_free(&kset);
        free(svcname);
        *_err_msg = err_msg;
    } else {
        *_svcname = svcname;
        *_kset = kset;
    }
    if (ber) ber_free(ber, 1);
    return rc;
}

/* Format of response
 *
 * KeytabGetRequest ::= SEQUENCE {
 * 	new_kvno	Int32
 * 	SEQUENCE OF	KeyTypes
 * }
 *
 * * List of accepted enctypes *
 * KeyTypes ::= SEQUENCE {
 * 	enctype		Int32
 * }
 */

static int encode_setkeytab_reply(struct ipapwd_keyset *kset,
                                  struct berval **_bvp)
{
    int rc = LDAP_OPERATIONS_ERROR;
    struct berval *bvp = NULL;
    BerElement *ber = NULL;

    ber = ber_alloc();
    if (!ber) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_OOM();
        goto done;
    }

    rc = ber_printf(ber, "{i{", (ber_int_t)kset->keys[0].key_data_kvno);
    if (rc == -1) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_FATAL("Failed to ber_printf the kvno");
        goto done;
    }

    for (int i = 0; i < kset->num_keys; i++) {
        rc = ber_printf(ber, "{i}", (ber_int_t)kset->keys[i].key_data_type[0]);
        if (rc == -1) {
            rc = LDAP_OPERATIONS_ERROR;
            LOG_FATAL("Failed to ber_printf the enctype");
            goto done;
        }
    }
    rc = ber_printf(ber, "}}");
    if (rc == -1) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_FATAL("Failed to ber_printf the termination");
        goto done;
    }

    rc = ber_flatten(ber, &bvp);
    if (rc == -1) {
        rc = LDAP_OPERATIONS_ERROR;
        LOG_FATAL("Failed to ber_flatten the buffer");
        goto done;
    }

    rc = LDAP_SUCCESS;

done:
    if (rc != LDAP_SUCCESS) {
        if (bvp) ber_bvfree(bvp);
    } else {
        *_bvp = bvp;
    }
    if (ber) ber_free(ber, 1);
    return rc;
}

/* Password Modify Extended operation plugin function */
static int ipapwd_setkeytab(Slapi_PBlock *pb, struct ipapwd_krbcfg *krbcfg)
{
	char *bindDN = NULL;
	char *serviceName = NULL;
	char *errMesg = NULL;
	struct berval *extop_value = NULL;
	Slapi_Entry *targetEntry=NULL;
	struct berval *bval = NULL;
	Slapi_Value **svals = NULL;
	krb5_context krbctx = NULL;
	krb5_error_code krberr;
	struct ipapwd_keyset *kset = NULL;
    int rc;
    int kvno;
    char *svcname;
    bool allowed_access = false;
    struct berval *bvp = NULL;
    LDAPControl new_ctrl;

	krberr = krb5_init_context(&krbctx);
	if (krberr) {
		LOG_FATAL("krb5_init_context failed\n");
		rc = LDAP_OPERATIONS_ERROR;
		goto free_and_return;
	}

	/* Get Bind DN */
	slapi_pblock_get(pb, SLAPI_CONN_DN, &bindDN);

	 /* If the connection is bound anonymously, we must refuse to process
	 * this operation. */
	if (bindDN == NULL || *bindDN == '\0') {
	 	/* Refuse the operation because they're bound anonymously */
		errMesg = "Anonymous Binds are not allowed.\n";
		rc = LDAP_INSUFFICIENT_ACCESS;
		goto free_and_return;
	}

	/* Get the ber value of the extended operation */
	slapi_pblock_get(pb, SLAPI_EXT_OP_REQ_VALUE, &extop_value);

    rc = decode_setkeytab_request(krbctx, krbcfg->kmkey, krbcfg->mkvno,
                                  extop_value, &serviceName, &kset, &errMesg);
    if (rc) {
        goto free_and_return;
    }

    /* make sure it is a valid name */
    svcname = check_service_name(krbctx, serviceName);
    if (!svcname) {
        rc = LDAP_OPERATIONS_ERROR;
        goto free_and_return;
    }
    slapi_ch_free_string(&serviceName);
    serviceName = svcname;

	/* check entry before doing any other decoding */

	/* get Entry by krbPrincipalName */
    targetEntry = get_entry_by_principal(serviceName);
    if (!targetEntry) {
        errMesg = "PrincipalName not found.\n";
        rc = LDAP_NO_SUCH_OBJECT;
        goto free_and_return;
    }

    /* Accesseck strategy:
     * If the user has WRITE access, a new keytab can be set on the entry.
     * If not, then we fail immediately with insufficient access. This
     * means that we don't leak any useful information to the client such
     * as current password wrong, etc.
     */
    allowed_access = is_allowed_to_access_attr(pb, bindDN, targetEntry,
                                               "krbPrincipalKey", NULL,
                                               SLAPI_ACL_WRITE);
    if (!allowed_access) {
        LOG_FATAL("Access not allowed to set keytab on [%s]!\n",
                  serviceName);
        errMesg = "Insufficient access rights\n";
        rc = LDAP_INSUFFICIENT_ACCESS;
        goto free_and_return;
    }

    /* get next kvno for entry (will be 1 if this is new) and fix keyset */
    kvno = ipapwd_get_cur_kvno(targetEntry) + 1;
    for (int i = 0; i < kset->num_keys; i++) {
        kset->keys[i].key_data_kvno = kvno;
    }
    filter_keys(krbcfg, kset);

	/* check if we have any left */
	if (kset->num_keys == 0) {
		LOG_FATAL("keyset filtering rejected all proposed keys\n");
		errMesg = "All enctypes provided are unsupported";
		rc = LDAP_UNWILLING_TO_PERFORM;
		goto free_and_return;
	}

	rc = ber_encode_krb5_key_data(kset->keys, kset->num_keys,
                                       kset->mkvno, &bval);
	if (rc != 0) {
		LOG_FATAL("encoding krb5_key_data failed\n");
		rc = LDAP_OPERATIONS_ERROR;
		goto free_and_return;
	}

	svals = (Slapi_Value **)calloc(2, sizeof(Slapi_Value *));
	if (!svals) {
		LOG_OOM();
		rc = LDAP_OPERATIONS_ERROR;
		goto free_and_return;
	}

	svals[0] = slapi_value_new_berval(bval);
	if (!svals[0]) {
		LOG_FATAL("Converting berval to Slapi_Value\n");
		goto free_and_return;
	}

    rc = store_new_keys(targetEntry, serviceName, bindDN, svals, &errMesg);
    if (rc) {
        goto free_and_return;
    }

    rc = encode_setkeytab_reply(kset, &bvp);
    if (rc) {
        errMesg = "Internal Error.\n";
        goto free_and_return;
    }

    new_ctrl.ldctl_oid = KEYTAB_RET_OID;
    new_ctrl.ldctl_value = *bvp;
    new_ctrl.ldctl_iscritical = 0;
    rc = slapi_pblock_set(pb, SLAPI_ADD_RESCONTROL, &new_ctrl);

	/* Free anything that we allocated above */
free_and_return:
	free(serviceName);
	if (kset) ipapwd_keyset_free(&kset);

	if (bval) ber_bvfree(bval);
	if (bvp) ber_bvfree(bvp);

    if (targetEntry) slapi_entry_free(targetEntry);

	if (svals) {
		for (int i = 0; svals[i]; i++) {
			slapi_value_free(&svals[i]);
		}
		free(svals);
	}

	if (krbctx) krb5_free_context(krbctx);

        if (rc == LDAP_SUCCESS)
            errMesg = NULL;
	LOG("%s", errMesg ? errMesg : "success");
	slapi_send_ldap_result(pb, rc, NULL, errMesg, 0, NULL);

	return SLAPI_PLUGIN_EXTENDED_SENT_RESULT;
}

/* decode a getkeytab control request using libipaasn1 helpers */
static int decode_getkeytab_request(struct berval *extop, bool *wantold,
                                    char **_svcname, char **_password,
                                    krb5_key_salt_tuple **kenctypes,
                                    int *num_kenctypes, char **_err_msg)
{
    int rc = LDAP_OPERATIONS_ERROR;
    char *err_msg = NULL;
    char *svcname = NULL;
    char *password = NULL;
    long *etypes = NULL;
    int numtypes = 0;
    krb5_key_salt_tuple *enctypes = NULL;
    bool newkt;
    bool ret;
    int i;

    ret = ipaasn1_dec_getkt(extop->bv_val, extop->bv_len, &newkt,
                            &svcname, &password, &etypes, &numtypes);
    if (!ret) {
        err_msg = "Failed to decode GetKeytab Control.\n";
        rc = LDAP_PROTOCOL_ERROR;
        goto done;
    }

    if (newkt) {
        if (numtypes) {
            enctypes = malloc(numtypes * sizeof(krb5_key_salt_tuple));
            if (!enctypes) {
                LOG_FATAL("allocation failed\n");
                err_msg = "Internal error\n";
                rc = LDAP_OPERATIONS_ERROR;
                goto done;
            }

            for (i = 0; i < numtypes; i++) {
                enctypes[i].ks_enctype = etypes[i];
                enctypes[i].ks_salttype = KRB5_KDB_SALTTYPE_NORMAL;
            }
        }
    }

    rc = LDAP_SUCCESS;

done:
    free(etypes);
    if (rc != LDAP_SUCCESS) {
        free(password);
        free(svcname);
        free(enctypes);
        *_err_msg = err_msg;
    } else {
        *_password = password;
        *_svcname = svcname;
        *wantold = (newkt == false);
        *kenctypes = enctypes;
        *num_kenctypes = numtypes;
    }
    return rc;
}

static int encode_getkeytab_reply(krb5_context krbctx,
                                  krb5_keyblock *kmkey, int mkvno,
                                  krb5_key_data *keys, int num_keys,
                                  struct berval **_bvp)
{
    int rc = LDAP_OPERATIONS_ERROR;
    struct krb_key_salt ksdata[num_keys];
    struct keys_container ksc = { num_keys, ksdata };
    struct berval *bvp = NULL;
    int kvno;
    bool ret;

    memset(ksdata, '\0', num_keys * sizeof(struct krb_key_salt));

    /* uses last key kvno */
    kvno = keys[num_keys-1].key_data_kvno;

    for (int i = 0; i < num_keys; i++) {
        krb5_enc_data cipher = { 0 };
        krb5_data plain = { 0 };
        krb5_int16 plen;

        /* retrieve plain key */
        memcpy(&plen, keys[i].key_data_contents[0], 2);
        cipher.ciphertext.data = (char *)keys[i].key_data_contents[0] + 2;
        cipher.ciphertext.length = keys[i].key_data_length[0] - 2;
        cipher.enctype = kmkey->enctype;
        cipher.kvno = mkvno;

        plain.length = le16toh(plen);
        plain.data = malloc(plain.length);
        if (!plain.data) {
            LOG_FATAL("Failed to allocate plain buffer\n");
            rc = LDAP_OPERATIONS_ERROR;
            goto done;
        }

        rc = krb5_c_decrypt(krbctx, kmkey, 0, 0, &cipher, &plain);
        if (rc) {
            LOG_FATAL("Failed to decrypt keys\n");
            rc = LDAP_OPERATIONS_ERROR;
            goto done;
        }

        ksc.ksdata[i].enctype = keys[i].key_data_type[0];
        ksc.ksdata[i].key.enctype = keys[i].key_data_type[0];
        ksc.ksdata[i].key.contents = (void *)plain.data;
        ksc.ksdata[i].key.length = plain.length;

        /* if salt available, add it */
        if (keys[i].key_data_length[1] != 0) {
            ksc.ksdata[i].salttype = keys[i].key_data_type[1];
            ksc.ksdata[i].salt.data = (void *)keys[i].key_data_contents[1];
            ksc.ksdata[i].salt.length = keys[i].key_data_length[1];
        }
    }

    bvp = calloc(1, sizeof(struct berval));
    if (!bvp) goto done;

    ret = ipaasn1_enc_getktreply(kvno, &ksc,
                                 (void **)&bvp->bv_val, &bvp->bv_len);
    if (!ret) goto done;

    rc = LDAP_SUCCESS;

done:
    for (int i = 0; i < ksc.nkeys; i ++) {
        free(ksc.ksdata[i].key.contents);
    }
    if (rc != LDAP_SUCCESS) {
        if (bvp) ber_bvfree(bvp);
    } else {
        *_bvp = bvp;
    }
    return rc;
}

static int get_decoded_key_data(char *svcname,
                                krb5_key_data **_keys, int *_num_keys,
                                int *_mkvno, char **_err_msg)
{
    int rc = LDAP_OPERATIONS_ERROR;
    char *err_msg = NULL;
    krb5_key_data *keys = NULL;
    int num_keys = 0;
    int mkvno = 0;
    Slapi_Entry *target = NULL;
    Slapi_Attr *attr;
    Slapi_Value *keys_value;
    const struct berval *encoded_keys;

    target = get_entry_by_principal(svcname);
    if (!target) {
        err_msg = "PrincipalName disappeared while processing.\n";
        rc = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    rc = slapi_entry_attr_find(target, "krbPrincipalKey", &attr);
    if (rc) {
        err_msg = "krbPrincipalKey not found\n";
        rc = LDAP_NO_SUCH_ATTRIBUTE;
        goto done;
    }
    rc = slapi_attr_first_value(attr, &keys_value);
    if (rc) {
        err_msg = "Error retrieving krbPrincipalKey\n";
        rc = LDAP_OPERATIONS_ERROR;
        goto done;
    }
    encoded_keys = slapi_value_get_berval(keys_value);
    if (!encoded_keys) {
        err_msg = "Error retrieving encoded krbPrincipalKey\n";
        rc = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    rc = ber_decode_krb5_key_data(discard_const(encoded_keys),
                                  &mkvno, &num_keys, &keys);
    if (rc) {
        err_msg = "Error retrieving decoded krbPrincipalKey\n";
        rc = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    if (num_keys <= 0) {
        err_msg = "No krbPrincipalKeys available\n";
        rc = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    rc = LDAP_SUCCESS;

done:
    if (rc != LDAP_SUCCESS) {
        if (keys) ipa_krb5_free_key_data(keys, num_keys);
        *_err_msg = err_msg;
    } else {
        *_mkvno = mkvno;
        *_keys = keys;
        *_num_keys = num_keys;
    }
    if (target) slapi_entry_free(target);
    return rc;
}

#define WRITEKEYS_OP_CHECK "ipaProtectedOperation;write_keys"
#define READKEYS_OP_CHECK "ipaProtectedOperation;read_keys"

/* Password Modify Extended operation plugin function */
static int ipapwd_getkeytab(Slapi_PBlock *pb, struct ipapwd_krbcfg *krbcfg)
{
    char *bind_dn = NULL;
    char *err_msg = NULL;
    int rc = 0;
    krb5_context krbctx = NULL;
    krb5_error_code krberr;
    struct berval *extop_value = NULL;
    char *service_name = NULL;
    char *svcname;
    Slapi_Entry *target_entry = NULL;
    bool acl_ok = false;
    char *password = NULL;
    int num_kenctypes = 0;
    krb5_key_salt_tuple *kenctypes = NULL;
    int mkvno = 0;
    int num_keys = 0;
    krb5_key_data *keys = NULL;
    struct ipapwd_data data = { 0 };
    Slapi_Value **svals = NULL;
    struct berval *bvp = NULL;
    LDAPControl new_ctrl;
    bool wantold = false;

    /* Get Bind DN */
    slapi_pblock_get(pb, SLAPI_CONN_DN, &bind_dn);

    /* If the connection is bound anonymously, we must refuse to process
    * this operation. */
    if (bind_dn == NULL || *bind_dn == '\0') {
        /* Refuse the operation because they're bound anonymously */
        err_msg = "Anonymous Binds are not allowed.\n";
        rc = LDAP_INSUFFICIENT_ACCESS;
        goto free_and_return;
    }

    krberr = krb5_init_context(&krbctx);
    if (krberr) {
        LOG_FATAL("krb5_init_context failed\n");
        rc = LDAP_OPERATIONS_ERROR;
        goto free_and_return;
    }

    /* Get the ber value of the extended operation */
    slapi_pblock_get(pb, SLAPI_EXT_OP_REQ_VALUE, &extop_value);
    if (!extop_value) {
        LOG_FATAL("Failed to retrieve extended op value from pblock\n");
        err_msg = "Failed to retrieve extended operation value\n";
        rc = LDAP_OPERATIONS_ERROR;
        goto free_and_return;
    }

    rc = decode_getkeytab_request(extop_value, &wantold, &service_name,
                                  &password, &kenctypes, &num_kenctypes,
                                  &err_msg);
    if (rc != LDAP_SUCCESS) {
        goto free_and_return;
    }

    /* make sure it is a valid name */
    svcname = check_service_name(krbctx, service_name);
    if (!svcname) {
        rc = LDAP_OPERATIONS_ERROR;
        goto free_and_return;
    }
    slapi_ch_free_string(&service_name);
    service_name = svcname;

    /* check entry */

    /* get Entry by krbPrincipalName */
    target_entry = get_entry_by_principal(service_name);
    if (!target_entry) {
        err_msg = "PrincipalName not found.\n";
        rc = LDAP_NO_SUCH_OBJECT;
        goto free_and_return;
    }

    /* ok access allowed */
    /* do we need to create new keys ? */
    if (wantold) { /* requesting to retrieve existing ones */

        /* check if we are allowed to *read* keys */
        acl_ok = is_allowed_to_access_attr(pb, bind_dn, target_entry,
                                           READKEYS_OP_CHECK, NULL,
                                           SLAPI_ACL_READ);
        if (!acl_ok) {
            LOG_FATAL("Not allowed to retrieve keytab on [%s]!\n",
                      service_name);
            err_msg = "Insufficient access rights\n";
            rc = LDAP_INSUFFICIENT_ACCESS;
            goto free_and_return;
        }

    } else {

        /* check if we are allowed to *write* keys */
        acl_ok = is_allowed_to_access_attr(pb, bind_dn, target_entry,
                                           WRITEKEYS_OP_CHECK, NULL,
                                           SLAPI_ACL_WRITE);
        if (!acl_ok) {
            LOG_FATAL("Not allowed to set keytab on [%s]!\n",
                      service_name);
            err_msg = "Insufficient access rights\n";
            rc = LDAP_INSUFFICIENT_ACCESS;
            goto free_and_return;
        }

        filter_enctypes(krbcfg, kenctypes, &num_kenctypes);

        /* check if we have any left */
        if (num_kenctypes == 0 && kenctypes != NULL) {
            LOG_FATAL("keyset filtering rejected all proposed keys\n");
            err_msg = "All enctypes provided are unsupported";
            rc = LDAP_UNWILLING_TO_PERFORM;
            goto free_and_return;
        }

        /* only target is used, leave everything else NULL,
         * if password is not provided we want to generate a random key */
        data.target = target_entry;
        data.password = password;

        svals = ipapwd_encrypt_encode_key(krbcfg, &data,
                                          kenctypes ? num_kenctypes :
                                                krbcfg->num_pref_encsalts,
                                          kenctypes ? kenctypes :
                                                krbcfg->pref_encsalts,
                                          &err_msg);
        if (!svals) {
            rc = LDAP_OPERATIONS_ERROR;
            LOG_FATAL("encrypt_encode_keys failed!\n");
            err_msg = "Internal error while encrypting keys\n";
            goto free_and_return;
        }

        rc = store_new_keys(target_entry, service_name, bind_dn, svals,
                            &err_msg);
        if (rc != LDAP_SUCCESS) {
            goto free_and_return;
        }
    }

    rc = get_decoded_key_data(service_name,
                              &keys, &num_keys, &mkvno, &err_msg);
    if (rc != LDAP_SUCCESS) {
        goto free_and_return;
    }

    rc = encode_getkeytab_reply(krbctx, krbcfg->kmkey, mkvno,
                                keys, num_keys, &bvp);
    if (rc != LDAP_SUCCESS) {
        err_msg = "Internal Error.\n";
        goto free_and_return;
    }

    new_ctrl.ldctl_oid = KEYTAB_GET_OID;
    new_ctrl.ldctl_value = *bvp;
    new_ctrl.ldctl_iscritical = 0;
    rc = slapi_pblock_set(pb, SLAPI_ADD_RESCONTROL, &new_ctrl);

free_and_return:
    if (rc == LDAP_SUCCESS) err_msg = NULL;
    LOG("%s", err_msg ? err_msg : "success");
    slapi_send_ldap_result(pb, rc, NULL, err_msg, 0, NULL);

    /* Free anything that we allocated above */
    if (krbctx) krb5_free_context(krbctx);
    free(kenctypes);
    free(service_name);
    free(password);
    if (target_entry) slapi_entry_free(target_entry);
    if (keys) ipa_krb5_free_key_data(keys, num_keys);
    if (svals) {
        for (int i = 0; svals[i]; i++) {
            slapi_value_free(&svals[i]);
        }
        free(svals);
    }
    if (bvp) ber_bvfree(bvp);

    return SLAPI_PLUGIN_EXTENDED_SENT_RESULT;
}

static int ipapwd_extop(Slapi_PBlock *pb)
{
	struct ipapwd_krbcfg *krbcfg = NULL;
	char *errMesg = NULL;
	char *oid = NULL;
	int rc, ret;

	LOG_TRACE("=>\n");

	rc = ipapwd_gen_checks(pb, &errMesg, &krbcfg, IPAPWD_CHECK_CONN_SECURE);
	if (rc) {
		goto free_and_return;
	}

	/* Before going any further, we'll make sure that the right extended
	 * operation plugin has been called: i.e., the OID shipped whithin the
	 * extended operation request must match this very plugin's OIDs:
	 * EXOP_PASSWD_OID or KEYTAB_SET_OID. */
	if (slapi_pblock_get(pb, SLAPI_EXT_OP_REQ_OID, &oid) != 0) {
		errMesg = "Could not get OID value from request.\n";
		rc = LDAP_OPERATIONS_ERROR;
		LOG("%s", errMesg);
		goto free_and_return;
	} else {
	        LOG("Received extended operation request with OID %s\n", oid);
	}

	if (strcasecmp(oid, EXOP_PASSWD_OID) == 0) {
		ret = ipapwd_chpwop(pb, krbcfg);
		free_ipapwd_krbcfg(&krbcfg);
		return ret;
	}
	if (strcasecmp(oid, KEYTAB_SET_OID) == 0) {
		ret = ipapwd_setkeytab(pb, krbcfg);
		free_ipapwd_krbcfg(&krbcfg);
		return ret;
	}
	if (strcasecmp(oid, KEYTAB_GET_OID) == 0) {
		ret = ipapwd_getkeytab(pb, krbcfg);
		free_ipapwd_krbcfg(&krbcfg);
		return ret;
	}

	errMesg = "Request OID does not match supported OIDs.\n";
	rc = LDAP_OPERATIONS_ERROR;

free_and_return:
	if (krbcfg) free_ipapwd_krbcfg(&krbcfg);

	LOG("%s", errMesg);
	slapi_send_ldap_result(pb, rc, NULL, errMesg, 0, NULL);

	return SLAPI_PLUGIN_EXTENDED_SENT_RESULT;
}

/* Copied from ipamo_string2filter()
 *
 * ipapwd_string2filter()
 *
 * For some reason slapi_str2filter writes to its input
 * which means you cannot pass in a string constant
 * so this is a fix up function for that
 */
Slapi_Filter *ipapwd_string2filter(char *strfilter)
{
	Slapi_Filter *ret = NULL;
	char *idontbelieveit = slapi_ch_strdup(strfilter);

	ret = slapi_str2filter(idontbelieveit);

	slapi_ch_free_string(&idontbelieveit);

	return ret;
}

/* Init data structs */
static int ipapwd_start( Slapi_PBlock *pb )
{
    krb5_context krbctx = NULL;
    krb5_error_code krberr;
    char *realm = NULL;
    char *config_dn;
    Slapi_Entry *config_entry = NULL;
    int ret;

    krberr = krb5_init_context(&krbctx);
    if (krberr) {
        LOG_FATAL("krb5_init_context failed\n");
        /* Yes, we failed, but it is because /etc/krb5.conf doesn't exist
         * or is misconfigured. Start up in a degraded mode.
         */
        return LDAP_SUCCESS;
    }

    if (slapi_pblock_get(pb, SLAPI_TARGET_DN, &config_dn) != 0) {
        LOG_FATAL("No config DN?\n");
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    if (ipapwd_getEntry(config_dn, &config_entry, NULL) != LDAP_SUCCESS) {
        LOG_FATAL("No config Entry extop?\n");
        ret = LDAP_SUCCESS;
        goto done;
    }

    ipa_realm_tree = slapi_entry_attr_get_charptr(config_entry,
                                                  "nsslapd-realmtree");
    if (!ipa_realm_tree) {
        LOG_FATAL("Missing partition configuration entry "
                  "(nsslapd-realmTree)!\n");
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    ret = krb5_get_default_realm(krbctx, &realm);
    if (ret) {
        LOG_FATAL("Failed to get default realm?!\n");
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }
    ipa_realm_dn = slapi_ch_smprintf("cn=%s,cn=kerberos,%s",
                                     realm, ipa_realm_tree);
    if (!ipa_realm_dn) {
        LOG_OOM();
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    ipa_pwd_config_dn = slapi_ch_strdup(config_dn);
    if (!ipa_pwd_config_dn) {
        LOG_OOM();
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }
    ipa_changepw_principal_dn = slapi_ch_smprintf("krbprincipalname="
                                                  "kadmin/changepw@%s,%s",
                                                  realm, ipa_realm_dn);
    if (!ipa_changepw_principal_dn) {
        LOG_OOM();
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    ipa_etc_config_dn = slapi_ch_smprintf("cn=ipaConfig,cn=etc,%s",
                                          ipa_realm_tree);
    if (!ipa_etc_config_dn) {
        LOG_OOM();
        ret = LDAP_OPERATIONS_ERROR;
        goto done;
    }

    ret = LDAP_SUCCESS;

    /* NOTE: We never call otp_config_fini() from a destructor. This is because
     *       it may race with threaded requests at shutdown. This leak should
     *       only occur when the DS is exiting, so it isn't a big deal.
     */
    otp_config = otp_config_init(ipapwd_plugin_id);

done:
    free(realm);
    krb5_free_context(krbctx);
    if (config_entry) slapi_entry_free(config_entry);
    return ret;
}

static char *ipapwd_oid_list[] = {
	EXOP_PASSWD_OID,
	KEYTAB_SET_OID,
	KEYTAB_GET_OID,
	NULL
};


static char *ipapwd_name_list[] = {
	"Password Change Extended Operation",
	"Keytab Retrieval Extended Operation",
	NULL
};

/* Initialization function */
int ipapwd_init( Slapi_PBlock *pb )
{
    int ret;
    Slapi_Entry *plugin_entry = NULL;

    /* get args */
    if ((slapi_pblock_get(pb, SLAPI_PLUGIN_CONFIG_ENTRY, &plugin_entry) == 0) &&
        plugin_entry) {
            usetxn = slapi_entry_attr_get_bool(plugin_entry,
                                                 "nsslapd-pluginbetxn");
    }

    /* Get the arguments appended to the plugin extendedop directive. The first argument
     * (after the standard arguments for the directive) should contain the OID of the
     * extended operation. */

    ret = slapi_pblock_get(pb, SLAPI_PLUGIN_IDENTITY, &ipapwd_plugin_id);
    if ((ret != 0) || (NULL == ipapwd_plugin_id)) {
        LOG("Could not get identity or identity was NULL\n");
        return -1;
    }

    if (ipapwd_ext_init() != 0) {
        LOG("Object Extension Operation failed\n");
        return -1;
    }

    /* Register the plug-in function as an extended operation
     * plug-in function that handles the operation identified by
     * OID 1.3.6.1.4.1.4203.1.11.1 .  Also specify the version of the server
     * plug-in */
    ret = slapi_pblock_set(pb, SLAPI_PLUGIN_VERSION, SLAPI_PLUGIN_VERSION_03);
    if (!ret) ret = slapi_pblock_set(pb, SLAPI_PLUGIN_START_FN, (void *)ipapwd_start);
    if (!ret) ret = slapi_pblock_set(pb, SLAPI_PLUGIN_DESCRIPTION, (void *)&ipapwd_plugin_desc);
    if (!ret) ret = slapi_pblock_set(pb, SLAPI_PLUGIN_EXT_OP_OIDLIST, ipapwd_oid_list);
    if (!ret) ret = slapi_pblock_set(pb, SLAPI_PLUGIN_EXT_OP_NAMELIST, ipapwd_name_list);
    if (!ret) ret = slapi_pblock_set(pb, SLAPI_PLUGIN_EXT_OP_FN, (void *)ipapwd_extop);
    if (ret) {
        LOG("Failed to set plug-in version, function, and OID.\n" );
        return -1;
    }

    if (usetxn) {
        slapi_register_plugin("betxnpreoperation", 1,
                              "ipapwd_pre_init_betxn", ipapwd_pre_init_betxn,
                              "IPA pwd pre ops betxn", NULL,
                              ipapwd_plugin_id);

        slapi_register_plugin("betxnpostoperation", 1,
                              "ipapwd_post_init_betxn", ipapwd_post_init_betxn,
                              "IPA pwd post ops betxn", NULL,
                              ipapwd_plugin_id);
    } 

    slapi_register_plugin("preoperation", 1,
                          "ipapwd_pre_init", ipapwd_pre_init,
                          "IPA pwd pre ops", NULL,
                          ipapwd_plugin_id);

    slapi_register_plugin("postoperation", 1,
                          "ipapwd_post_init", ipapwd_post_init,
                          "IPA pwd post ops", NULL,
                          ipapwd_plugin_id);

    slapi_register_plugin("internalpostoperation", 1,
                          "ipapwd_intpost_init", ipapwd_intpost_init,
                          "IPA pwd internal post ops", NULL,
                          ipapwd_plugin_id);

    return 0;
}