summaryrefslogtreecommitdiffstats
path: root/ipalib/plugins/user.py
blob: 2b792af6289bae3644e627afff8e8ddc662068b2 (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
# Authors:
#   Jason Gerard DeRose <jderose@redhat.com>
#   Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2008  Red Hat
# see file 'COPYING' for use and warranty information
#
# 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/>.

from time import gmtime, strftime
import string
import posixpath
import os

import six

from ipalib import api, errors, util
from ipalib import Flag, Int, Password, Str, Bool, StrEnum, DateTime
from ipalib.plugins.baseuser import (
    baseuser, baseuser_add, baseuser_del, baseuser_mod, baseuser_find,
    baseuser_show, NO_UPG_MAGIC, UPG_DEFINITION_DN, baseuser_output_params,
    status_baseuser_output_params, baseuser_pwdchars, validate_nsaccountlock,
    radius_dn2pk, convert_nsaccountlock, split_principal, validate_principal,
    normalize_principal, fix_addressbook_permission_bindrule,
    baseuser_add_manager, baseuser_remove_manager)
from ipalib.plugins.idviews import remove_ipaobject_overrides
from ipalib.plugable import Registry
from ipalib.plugins.baseldap import *
from ipalib.plugins import baseldap
from ipalib.request import context
from ipalib import _, ngettext
from ipalib import output
from ipalib import x509
from ipaplatform.paths import paths
from ipapython.ipautil import ipa_generate_password
from ipapython.ipavalidate import Email
from ipalib.capabilities import client_has_capability
from ipalib.util import (normalize_sshpubkey, validate_sshpubkey,
    convert_sshpubkey_post)
if api.env.in_server:
    from ipaserver.plugins.ldap2 import ldap2

if six.PY3:
    unicode = str

__doc__ = _("""
Users

Manage user entries. All users are POSIX users.

IPA supports a wide range of username formats, but you need to be aware of any
restrictions that may apply to your particular environment. For example,
usernames that start with a digit or usernames that exceed a certain length
may cause problems for some UNIX systems.
Use 'ipa config-mod' to change the username format allowed by IPA tools.

Disabling a user account prevents that user from obtaining new Kerberos
credentials. It does not invalidate any credentials that have already
been issued.

Password management is not a part of this module. For more information
about this topic please see: ipa help passwd

Account lockout on password failure happens per IPA master. The user-status
command can be used to identify which master the user is locked out on.
It is on that master the administrator must unlock the user.

EXAMPLES:

 Add a new user:
   ipa user-add --first=Tim --last=User --password tuser1

 Find all users whose entries include the string "Tim":
   ipa user-find Tim

 Find all users with "Tim" as the first name:
   ipa user-find --first=Tim

 Disable a user account:
   ipa user-disable tuser1

 Enable a user account:
   ipa user-enable tuser1

 Delete a user:
   ipa user-del tuser1
""")

register = Registry()


user_output_params = baseuser_output_params

status_output_params = status_baseuser_output_params


def check_protected_member(user, protected_group_name=u'admins'):
    '''
    Ensure the last enabled member of a protected group cannot be deleted or
    disabled by raising LastMemberError.
    '''

    # Get all users in the protected group
    result = api.Command.user_find(in_group=protected_group_name)

    # Build list of users in the protected group who are enabled
    result = result['result']
    enabled_users = [entry['uid'][0] for entry in result if not entry['nsaccountlock']]

    # If the user is the last enabled user raise LastMemberError exception
    if enabled_users == [user]:
        raise errors.LastMemberError(key=user, label=_(u'group'),
            container=protected_group_name)

@register()
class user(baseuser):
    """
    User object.
    """

    container_dn              = baseuser.active_container_dn
    label                     = _('Users')
    label_singular            = _('User')
    object_name               = _('user')
    object_name_plural        = _('users')
    managed_permissions = {
        'System: Read User Standard Attributes': {
            'replaces_global_anonymous_aci': True,
            'ipapermbindruletype': 'anonymous',
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'objectclass', 'cn', 'sn', 'description', 'title', 'uid',
                'displayname', 'givenname', 'initials', 'manager', 'gecos',
                'gidnumber', 'homedirectory', 'loginshell', 'uidnumber',
                'ipantsecurityidentifier'
            },
        },
        'System: Read User Addressbook Attributes': {
            'replaces_global_anonymous_aci': True,
            'ipapermbindruletype': 'all',
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'seealso', 'telephonenumber',
                'facsimiletelephonenumber', 'l', 'ou', 'st', 'postalcode', 'street',
                'destinationindicator', 'internationalisdnnumber',
                'physicaldeliveryofficename', 'postaladdress', 'postofficebox',
                'preferreddeliverymethod', 'registeredaddress',
                'teletexterminalidentifier', 'telexnumber', 'x121address',
                'carlicense', 'departmentnumber', 'employeenumber',
                'employeetype', 'preferredlanguage', 'mail', 'mobile', 'pager',
                'audio', 'businesscategory', 'homephone', 'homepostaladdress',
                'jpegphoto', 'labeleduri', 'o', 'photo', 'roomnumber',
                'secretary', 'usercertificate',
                'usersmimecertificate', 'x500uniqueidentifier',
                'inetuserhttpurl', 'inetuserstatus',
            },
            'fixup_function': fix_addressbook_permission_bindrule,
        },
        'System: Read User IPA Attributes': {
            'replaces_global_anonymous_aci': True,
            'ipapermbindruletype': 'all',
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'ipauniqueid', 'ipasshpubkey', 'ipauserauthtype', 'userclass',
            },
            'fixup_function': fix_addressbook_permission_bindrule,
        },
        'System: Read User Kerberos Attributes': {
            'replaces_global_anonymous_aci': True,
            'ipapermbindruletype': 'all',
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'krbprincipalname', 'krbcanonicalname', 'krbprincipalaliases',
                'krbprincipalexpiration', 'krbpasswordexpiration',
                'krblastpwdchange', 'nsaccountlock', 'krbprincipaltype',
            },
        },
        'System: Read User Kerberos Login Attributes': {
            'replaces_global_anonymous_aci': True,
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'krblastsuccessfulauth', 'krblastfailedauth',
                'krblastpwdchange', 'krblastadminunlock',
                'krbloginfailedcount', 'krbpwdpolicyreference',
                'krbticketpolicyreference', 'krbupenabled',
            },
            'default_privileges': {'User Administrators'},
        },
        'System: Read User Membership': {
            'replaces_global_anonymous_aci': True,
            'ipapermbindruletype': 'all',
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'memberof',
            },
        },
        'System: Read UPG Definition': {
            # Required for adding users
            'replaces_global_anonymous_aci': True,
            'non_object': True,
            'ipapermlocation': UPG_DEFINITION_DN,
            'ipapermtarget': UPG_DEFINITION_DN,
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {'*'},
            'default_privileges': {'User Administrators'},
        },
        'System: Add Users': {
            'ipapermright': {'add'},
            'replaces': [
                '(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Users";allow (add) groupdn = "ldap:///cn=Add Users,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'User Administrators'},
        },
        'System: Add User to default group': {
            'non_object': True,
            'ipapermright': {'write'},
            'ipapermlocation': DN(api.env.container_group, api.env.basedn),
            'ipapermtarget': DN('cn=ipausers', api.env.container_group,
                                api.env.basedn),
            'ipapermdefaultattr': {'member'},
            'replaces': [
                '(targetattr = "member")(target = "ldap:///cn=ipausers,cn=groups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add user to default group";allow (write) groupdn = "ldap:///cn=Add user to default group,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'User Administrators'},
        },
        'System: Change User password': {
            'ipapermright': {'write'},
            'ipapermtargetfilter': [
                '(objectclass=posixaccount)',
                '(!(memberOf=%s))' % DN('cn=admins',
                                        api.env.container_group,
                                        api.env.basedn),
            ],
            'ipapermdefaultattr': {
                'krbprincipalkey', 'passwordhistory', 'sambalmpassword',
                'sambantpassword', 'userpassword'
            },
            'replaces': [
                '(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(targetattr = "userpassword || krbprincipalkey || sambalmpassword || sambantpassword || passwordhistory")(version 3.0;acl "permission:Change a user password";allow (write) groupdn = "ldap:///cn=Change a user password,cn=permissions,cn=pbac,$SUFFIX";)',
                '(targetfilter = "(!(memberOf=cn=admins,cn=groups,cn=accounts,$SUFFIX))")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(targetattr = "userpassword || krbprincipalkey || sambalmpassword || sambantpassword || passwordhistory")(version 3.0;acl "permission:Change a user password";allow (write) groupdn = "ldap:///cn=Change a user password,cn=permissions,cn=pbac,$SUFFIX";)',
                '(targetattr = "userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory")(version 3.0; acl "Windows PassSync service can write passwords"; allow (write) userdn="ldap:///uid=passsync,cn=sysaccounts,cn=etc,$SUFFIX";)',
            ],
            'default_privileges': {
                'User Administrators',
                'Modify Users and Reset passwords',
                'PassSync Service',
            },
        },
        'System: Manage User SSH Public Keys': {
            'ipapermright': {'write'},
            'ipapermdefaultattr': {'ipasshpubkey'},
            'replaces': [
                '(targetattr = "ipasshpubkey")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Manage User SSH Public Keys";allow (write) groupdn = "ldap:///cn=Manage User SSH Public Keys,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'User Administrators'},
        },
        'System: Manage User Certificates': {
            'ipapermright': {'write'},
            'ipapermdefaultattr': {'usercertificate'},
            'default_privileges': {
                'User Administrators',
                'Modify Users and Reset passwords',
            },
        },
        'System: Modify Users': {
            'ipapermright': {'write'},
            'ipapermdefaultattr': {
                'businesscategory', 'carlicense', 'cn', 'description',
                'displayname', 'employeetype', 'facsimiletelephonenumber',
                'gecos', 'givenname', 'homephone', 'inetuserhttpurl',
                'initials', 'l', 'labeleduri', 'loginshell', 'manager',
                'mepmanagedentry', 'mobile', 'objectclass', 'ou', 'pager',
                'postalcode', 'roomnumber', 'secretary', 'seealso', 'sn', 'st',
                'street', 'telephonenumber', 'title', 'userclass',
                'preferredlanguage',
            },
            'replaces': [
                '(targetattr = "givenname || sn || cn || displayname || title || initials || loginshell || gecos || homephone || mobile || pager || facsimiletelephonenumber || telephonenumber || street || roomnumber || l || st || postalcode || manager || secretary || description || carlicense || labeleduri || inetuserhttpurl || seealso || employeetype || businesscategory || ou || mepmanagedentry || objectclass")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Users";allow (write) groupdn = "ldap:///cn=Modify Users,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {
                'User Administrators',
                'Modify Users and Reset passwords',
            },
        },
        'System: Remove Users': {
            'ipapermright': {'delete'},
            'replaces': [
                '(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Remove Users";allow (delete) groupdn = "ldap:///cn=Remove Users,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'User Administrators'},
        },
        'System: Unlock User': {
            'ipapermright': {'write'},
            'ipapermdefaultattr': {
                'krblastadminunlock', 'krbloginfailedcount', 'nsaccountlock',
            },
            'replaces': [
                '(targetattr = "krbLastAdminUnlock || krbLoginFailedCount")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Unlock user accounts";allow (write) groupdn = "ldap:///cn=Unlock user accounts,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'User Administrators'},
        },
        'System: Read User Compat Tree': {
            'non_object': True,
            'ipapermbindruletype': 'anonymous',
            'ipapermlocation': api.env.basedn,
            'ipapermtarget': DN('cn=users', 'cn=compat', api.env.basedn),
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'objectclass', 'uid', 'cn', 'gecos', 'gidnumber', 'uidnumber',
                'homedirectory', 'loginshell',
            },
        },
        'System: Read User Views Compat Tree': {
            'non_object': True,
            'ipapermbindruletype': 'anonymous',
            'ipapermlocation': api.env.basedn,
            'ipapermtarget': DN('cn=users', 'cn=*', 'cn=views', 'cn=compat', api.env.basedn),
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'objectclass', 'uid', 'cn', 'gecos', 'gidnumber', 'uidnumber',
                'homedirectory', 'loginshell',
            },
        },
        'System: Read User NT Attributes': {
            'ipapermbindruletype': 'permission',
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'ntuserdomainid', 'ntuniqueid', 'ntuseracctexpires',
                'ntusercodepage', 'ntuserdeleteaccount', 'ntuserlastlogoff',
                'ntuserlastlogon',
            },
            'default_privileges': {'PassSync Service'},
        },
    }

    takes_params = baseuser.takes_params + (
        Bool('nsaccountlock?',
            label=_('Account disabled'),
            flags=['no_option'],
        ),
        Bool('preserved?',
            label=_('Preserved user'),
            default=False,
            flags=['virtual_attribute', 'no_create', 'no_update'],
        ),
    )

    def get_either_dn(self, *keys, **options):
        '''
        Returns the DN of a user
        The user can be active (active container) or delete (delete container)
        If the user does not exist, returns the Active user DN
        '''
        ldap = self.backend
        # Check that this value is a Active user
        try:
            active_dn = self.get_dn(*keys, **options)
            ldap.get_entry(active_dn, ['dn'])

            # The Active user exists
            dn = active_dn
        except errors.NotFound:
            # Check that this value is a Delete user
            delete_dn = DN(active_dn[0], self.delete_container_dn, api.env.basedn)
            try:
                ldap.get_entry(delete_dn, ['dn'])

                # The Delete user exists
                dn = delete_dn
            except errors.NotFound:
                # The user is neither Active/Delete -> returns that Active DN
                dn = active_dn

        return dn

    def _normalize_manager(self, manager):
        """
        Given a userid verify the user's existence and return the dn.
        """
        return super(user, self).normalize_manager(manager, self.active_container_dn)

    def get_preserved_attribute(self, entry, options):
        if options.get('raw', False):
            return
        delete_container_dn = DN(self.delete_container_dn, api.env.basedn)
        if entry.dn.endswith(delete_container_dn):
            entry['preserved'] = True
        elif options.get('all', False):
            entry['preserved'] = False


@register()
class user_add(baseuser_add):
    __doc__ = _('Add a new user.')

    msg_summary = _('Added user "%(value)s"')

    has_output_params = baseuser_add.has_output_params + user_output_params

    takes_options = LDAPCreate.takes_options + (
        Flag('noprivate',
            cli_name='noprivate',
            doc=_('Don\'t create user private group'),
        ),
    )

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        dn = self.obj.get_either_dn(*keys, **options)
        if not options.get('noprivate', False):
            try:
                # The Managed Entries plugin will allow a user to be created
                # even if a group has a duplicate name. This would leave a user
                # without a private group. Check for both the group and the user.
                self.api.Object['group'].get_dn_if_exists(keys[-1])
                try:
                    self.api.Command['user_show'](keys[-1])
                    self.obj.handle_duplicate_entry(*keys)
                except errors.NotFound:
                    raise errors.ManagedGroupExistsError(group=keys[-1])
            except errors.NotFound:
                pass
        else:
            # we don't want an user private group to be created for this user
            # add NO_UPG_MAGIC description attribute to let the DS plugin know
            entry_attrs.setdefault('description', [])
            entry_attrs['description'].append(NO_UPG_MAGIC)

        entry_attrs.setdefault('uidnumber', baseldap.DNA_MAGIC)

        if not client_has_capability(
                options['version'], 'optional_uid_params'):
            # https://fedorahosted.org/freeipa/ticket/2886
            # Old clients say 999 (OLD_DNA_MAGIC) when they really mean
            # "assign a value dynamically".
            OLD_DNA_MAGIC = 999
            if entry_attrs.get('uidnumber') == OLD_DNA_MAGIC:
                entry_attrs['uidnumber'] = baseldap.DNA_MAGIC
            if entry_attrs.get('gidnumber') == OLD_DNA_MAGIC:
                entry_attrs['gidnumber'] = baseldap.DNA_MAGIC

        validate_nsaccountlock(entry_attrs)
        config = ldap.get_ipa_config()
        if 'ipamaxusernamelength' in config:
            if len(keys[-1]) > int(config.get('ipamaxusernamelength')[0]):
                raise errors.ValidationError(
                    name=self.obj.primary_key.cli_name,
                    error=_('can be at most %(len)d characters') % dict(
                        len = int(config.get('ipamaxusernamelength')[0])
                    )
                )
        default_shell = config.get('ipadefaultloginshell', [paths.SH])[0]
        entry_attrs.setdefault('loginshell', default_shell)
        # hack so we can request separate first and last name in CLI
        full_name = '%s %s' % (entry_attrs['givenname'], entry_attrs['sn'])
        entry_attrs.setdefault('cn', full_name)
        if 'homedirectory' not in entry_attrs:
            # get home's root directory from config
            homes_root = config.get('ipahomesrootdir', [paths.HOME_DIR])[0]
            # build user's home directory based on his uid
            entry_attrs['homedirectory'] = posixpath.join(homes_root, keys[-1])
        entry_attrs.setdefault('krbprincipalname', '%s@%s' % (entry_attrs['uid'], api.env.realm))

        if entry_attrs.get('gidnumber') is None:
            # gidNumber wasn't specified explicity, find out what it should be
            if not options.get('noprivate', False) and ldap.has_upg():
                # User Private Groups - uidNumber == gidNumber
                entry_attrs['gidnumber'] = entry_attrs['uidnumber']
            else:
                # we're adding new users to a default group, get its gidNumber
                # get default group name from config
                def_primary_group = config.get('ipadefaultprimarygroup')
                group_dn = self.api.Object['group'].get_dn(def_primary_group)
                try:
                    group_attrs = ldap.get_entry(group_dn, ['gidnumber'])
                except errors.NotFound:
                    error_msg = _('Default group for new users not found')
                    raise errors.NotFound(reason=error_msg)
                if 'gidnumber' not in group_attrs:
                    error_msg = _('Default group for new users is not POSIX')
                    raise errors.NotFound(reason=error_msg)
                entry_attrs['gidnumber'] = group_attrs['gidnumber']

        if 'userpassword' not in entry_attrs and options.get('random'):
            entry_attrs['userpassword'] = ipa_generate_password(baseuser_pwdchars)
            # save the password so it can be displayed in post_callback
            setattr(context, 'randompassword', entry_attrs['userpassword'])

        if 'mail' in entry_attrs:
            entry_attrs['mail'] = self.obj.normalize_and_validate_email(entry_attrs['mail'], config)
        else:
            # No e-mail passed in. If we have a default e-mail domain set
            # then we'll add it automatically.
            defaultdomain = config.get('ipadefaultemaildomain', [None])[0]
            if defaultdomain:
                entry_attrs['mail'] = self.obj.normalize_and_validate_email(keys[-1], config)

        if 'manager' in entry_attrs:
            entry_attrs['manager'] = self.obj.normalize_manager(entry_attrs['manager'], self.obj.active_container_dn)

        if 'userclass' in entry_attrs and \
           'ipauser' not in entry_attrs['objectclass']:
            entry_attrs['objectclass'].append('ipauser')

        if 'ipauserauthtype' in entry_attrs and \
           'ipauserauthtypeclass' not in entry_attrs['objectclass']:
            entry_attrs['objectclass'].append('ipauserauthtypeclass')

        rcl = entry_attrs.get('ipatokenradiusconfiglink', None)
        if rcl:
            if 'ipatokenradiusproxyuser' not in entry_attrs['objectclass']:
                entry_attrs['objectclass'].append('ipatokenradiusproxyuser')

            answer = self.api.Object['radiusproxy'].get_dn_if_exists(rcl)
            entry_attrs['ipatokenradiusconfiglink'] = answer

        self.pre_common_callback(ldap, dn, entry_attrs, **options)

        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)
        config = ldap.get_ipa_config()
        # add the user we just created into the default primary group
        def_primary_group = config.get('ipadefaultprimarygroup')
        group_dn = self.api.Object['group'].get_dn(def_primary_group)

        # if the user is already a member of default primary group,
        # do not raise error
        # this can happen if automember rule or default group is set
        try:
            ldap.add_entry_to_group(dn, group_dn)
        except errors.AlreadyGroupMember:
            pass

        # delete description attribute NO_UPG_MAGIC if present
        if options.get('noprivate', False):
            if not options.get('all', False):
                desc_attr = ldap.get_entry(dn, ['description'])
                entry_attrs.update(desc_attr)
            if 'description' in entry_attrs and NO_UPG_MAGIC in entry_attrs['description']:
                entry_attrs['description'].remove(NO_UPG_MAGIC)
                kw = {'setattr': unicode('description=%s' % ','.join(entry_attrs['description']))}
                try:
                    self.api.Command['user_mod'](keys[-1], **kw)
                except (errors.EmptyModlist, errors.NotFound):
                    pass

        # Fetch the entry again to update memberof, mep data, etc updated
        # at the end of the transaction.
        newentry = ldap.get_entry(dn, ['*'])
        entry_attrs.update(newentry)

        if options.get('random', False):
            try:
                entry_attrs['randompassword'] = unicode(getattr(context, 'randompassword'))
            except AttributeError:
                # if both randompassword and userpassword options were used
                pass

        self.obj.get_preserved_attribute(entry_attrs, options)

        self.post_common_callback(ldap, dn, entry_attrs, **options)

        return dn


@register()
class user_del(baseuser_del):
    __doc__ = _('Delete a user.')

    msg_summary = _('Deleted user "%(value)s"')

    takes_options = baseuser_del.takes_options + (
        Bool('preserve?',
            exclude='cli',
        ),
        Flag('preserve?',
            include='cli',
            doc=_('Delete a user, keeping the entry available for future use'),
        ),
        Flag('no_preserve?',
            include='cli',
            doc=_('Delete a user'),
        ),
    )

    def _preserve_user(self, pkey, delete_container, **options):
        assert isinstance(delete_container, DN)

        dn = self.obj.get_either_dn(pkey, **options)
        delete_dn = DN(dn[0], delete_container)
        ldap = self.obj.backend
        self.log.debug("preserve move %s -> %s" % (dn, delete_dn))

        if dn.endswith(delete_container):
            raise errors.ExecutionError(
                _('%s: user is already preserved' % pkey)
            )
        # Check that this value is a Active user
        try:
            original_entry_attrs = self._exc_wrapper(
                pkey, options, ldap.get_entry)(dn, ['dn'])
        except errors.NotFound:
            self.obj.handle_not_found(pkey)

        for callback in self.get_callbacks('pre'):
            dn = callback(self, ldap, dn, pkey, **options)
            assert isinstance(dn, DN)

        # start to move the entry to Delete container
        self._exc_wrapper(pkey, options, ldap.move_entry)(dn, delete_dn,
                                                          del_old=True)

        # Then clear the credential attributes
        attrs_to_clear = ['krbPrincipalKey', 'krbLastPwdChange',
                          'krbPasswordExpiration', 'userPassword']

        entry_attrs = self._exc_wrapper(pkey, options, ldap.get_entry)(
            delete_dn, attrs_to_clear)

        clearedCredential = False
        for attr in attrs_to_clear:
            if attr.lower() in entry_attrs:
                del entry_attrs[attr]
                clearedCredential = True
        if clearedCredential:
            self._exc_wrapper(pkey, options, ldap.update_entry)(entry_attrs)

        # Then restore some original entry attributes
        attrs_to_restore = ['secretary', 'managedby', 'manager', 'ipauniqueid',
                            'uidnumber', 'gidnumber', 'passwordHistory']

        entry_attrs = self._exc_wrapper(
            pkey, options, ldap.get_entry)(delete_dn, attrs_to_restore)

        restoreAttr = False
        for attr in attrs_to_restore:
            if ((attr.lower() in original_entry_attrs) and
                    not (attr.lower() in entry_attrs)):
                restoreAttr = True
                entry_attrs[attr.lower()] = original_entry_attrs[attr.lower()]
        if restoreAttr:
            self._exc_wrapper(pkey, options, ldap.update_entry)(entry_attrs)

    def forward(self, *keys, **options):
        if self.api.env.context == 'cli':
            if options['no_preserve'] and options['preserve']:
                raise errors.MutuallyExclusiveError(
                    reason=_("preserve and no-preserve cannot be both set"))
            elif options['no_preserve']:
                options['preserve'] = False
            elif not options['preserve']:
                del options['preserve']
            del options['no_preserve']

        return super(user_del, self).forward(*keys, **options)

    def pre_callback(self, ldap, dn, *keys, **options):
        dn = self.obj.get_either_dn(*keys, **options)

        # For User life Cycle: user-del is a common plugin
        # command to delete active user (active container) and
        # delete user (delete container).
        # If the target entry is a Delete entry, skip the orphaning/removal
        # of OTP tokens.
        check_protected_member(keys[-1])

        if not options.get('preserve', False):
            # Remove any ID overrides tied with this user
            try:
                remove_ipaobject_overrides(self.obj.backend, self.obj.api, dn)
            except errors.NotFound:
                self.obj.handle_not_found(*keys)

        if dn.endswith(DN(self.obj.delete_container_dn, api.env.basedn)):
            return dn

        # Delete all tokens owned and managed by this user.
        # Orphan all tokens owned but not managed by this user.
        owner = self.api.Object.user.get_primary_key_from_dn(dn)
        results = self.api.Command.otptoken_find(ipatokenowner=owner)['result']
        for token in results:
            orphan = not [x for x in token.get('managedby_user', []) if x == owner]
            token = self.api.Object.otptoken.get_primary_key_from_dn(token['dn'])
            if orphan:
                self.api.Command.otptoken_mod(token, ipatokenowner=None)
            else:
                self.api.Command.otptoken_del(token)

        return dn

    def execute(self, *keys, **options):

        # We are going to permanent delete or the user is already in the delete container.
        delete_container = DN(self.obj.delete_container_dn, self.api.env.basedn)

        # The user to delete is active and there is no 'no_preserve' option
        if options.get('preserve', False):
            failed = []
            preserved = []
            for pkey in keys[-1]:
                try:
                    self._preserve_user(pkey, delete_container, **options)
                    preserved.append(pkey_to_value(pkey, options))
                except:
                    if not options.get('continue', False):
                        raise
                    failed.append(pkey_to_value(pkey, options))

            val = dict(result=dict(failed=failed), value=preserved)
            return val
        else:
            return super(user_del, self).execute(*keys, **options)


@register()
class user_mod(baseuser_mod):
    __doc__ = _('Modify a user.')

    msg_summary = _('Modified user "%(value)s"')

    has_output_params = baseuser_mod.has_output_params + user_output_params

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        dn = self.obj.get_either_dn(*keys, **options)
        self.pre_common_callback(ldap, dn, entry_attrs, **options)
        validate_nsaccountlock(entry_attrs)
        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        self.post_common_callback(ldap, dn, entry_attrs, **options)
        self.obj.get_preserved_attribute(entry_attrs, options)
        return dn


@register()
class user_find(baseuser_find):
    __doc__ = _('Search for users.')

    member_attributes = ['memberof']
    has_output_params = baseuser_find.has_output_params + user_output_params

    msg_summary = ngettext(
        '%(count)d user matched', '%(count)d users matched', 0
    )

    takes_options = LDAPSearch.takes_options + (
        Flag('whoami',
            label=_('Self'),
            doc=_('Display user record for current Kerberos principal'),
        ),
    )

    def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *keys, **options):
        assert isinstance(base_dn, DN)

        if options.get('whoami'):
            return ("(&(objectclass=posixaccount)(krbprincipalname=%s))"%\
                        getattr(context, 'principal'), base_dn, scope)

        preserved = options.get('preserved', False)
        if preserved is None:
            base_dn = self.api.env.basedn
            scope = ldap.SCOPE_SUBTREE
        elif preserved:
            base_dn = DN(self.obj.delete_container_dn, self.api.env.basedn)
        else:
            base_dn = DN(self.obj.active_container_dn, self.api.env.basedn)

        return (filter, base_dn, scope)

    def post_callback(self, ldap, entries, truncated, *args, **options):
        if options.get('pkey_only', False):
            return truncated

        if options.get('preserved', False) is None:
            base_dns = (
                DN(self.obj.active_container_dn, self.api.env.basedn),
                DN(self.obj.delete_container_dn, self.api.env.basedn),
            )
            entries[:] = [e for e in entries
                          if any(e.dn.endswith(bd) for bd in base_dns)]

        self.post_common_callback(ldap, entries, lockout=False, **options)
        for entry in entries:
            self.obj.get_preserved_attribute(entry, options)

        return truncated


@register()
class user_show(baseuser_show):
    __doc__ = _('Display information about a user.')

    has_output_params = baseuser_show.has_output_params + user_output_params
    takes_options = baseuser_show.takes_options + (
        Str('out?',
            doc=_('file to store certificate in'),
        ),
    )

    def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
        dn = self.obj.get_either_dn(*keys, **options)
        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        convert_nsaccountlock(entry_attrs)
        self.post_common_callback(ldap, dn, entry_attrs, **options)
        self.obj.get_preserved_attribute(entry_attrs, options)
        return dn

    def forward(self, *keys, **options):
        if 'out' in options:
            util.check_writable_file(options['out'])
            result = super(user_show, self).forward(*keys, **options)
            if 'usercertificate' in result['result']:
                x509.write_certificate_list(
                    result['result']['usercertificate'],
                    options['out']
                )
                result['summary'] = (
                    _('Certificate(s) stored in file \'%(file)s\'')
                    % dict(file=options['out'])
                )
                return result
            else:
                raise errors.NoCertificateError(entry=keys[-1])
        else:
            return super(user_show, self).forward(*keys, **options)

@register()
class user_undel(LDAPQuery):
    __doc__ = _('Undelete a delete user account.')

    has_output = output.standard_value
    msg_summary = _('Undeleted user account "%(value)s"')

    def execute(self, *keys, **options):
        ldap = self.obj.backend

        # First check that the user exists and is a delete one
        delete_dn = self.obj.get_either_dn(*keys, **options)
        try:
            entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(delete_dn)
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if delete_dn.endswith(DN(self.obj.active_container_dn,
                                 api.env.basedn)):
            raise errors.InvocationError(
                message=_('user "%s" is already active') % keys[-1])

        active_dn = DN(delete_dn[0], self.obj.active_container_dn, api.env.basedn)

        # start to move the entry to the Active container
        self._exc_wrapper(keys, options, ldap.move_entry)(delete_dn, active_dn, del_old=True)

        # add the user we just undelete into the default primary group
        config = ldap.get_ipa_config()
        def_primary_group = config.get('ipadefaultprimarygroup')
        group_dn = self.api.Object['group'].get_dn(def_primary_group)

        # if the user is already a member of default primary group,
        # do not raise error
        # this can happen if automember rule or default group is set
        try:
            ldap.add_entry_to_group(active_dn, group_dn)
        except errors.AlreadyGroupMember:
            pass

        return dict(
            result=True,
            value=pkey_to_value(keys[0], options),
        )


@register()
class user_stage(LDAPMultiQuery):
    __doc__ = _('Move deleted user into staged area')

    has_output = output.standard_multi_delete
    msg_summary = _('Staged user account "%(value)s"')

    def execute(self, *keys, **options):
        staged = []
        failed = []

        for key in keys[-1]:
            single_keys = keys[:-1] + (key,)
            multi_keys = keys[:-1] + ((key,),)

            user = self.api.Command.user_show(*single_keys, all=True)['result']
            new_options = {}
            for param in self.api.Command.stageuser_add.options():
                try:
                    value = user[param.name]
                except KeyError:
                    continue
                if param.multivalue and not isinstance(value, (list, tuple)):
                    value = [value]
                elif not param.multivalue and isinstance(value, (list, tuple)):
                    value = value[0]
                new_options[param.name] = value

            try:
                self.api.Command.stageuser_add(*single_keys, **new_options)
                try:
                    self.api.Command.user_del(*multi_keys, preserve=False)
                except errors.ExecutionError:
                    self.api.Command.stageuser_del(*multi_keys)
                    raise
            except errors.ExecutionError:
                if not options['continue']:
                    raise
                failed.append(key)
            else:
                staged.append(key)

        return dict(
            result=dict(
                failed=pkey_to_value(failed, options),
            ),
            value=pkey_to_value(staged, options),
        )


@register()
class user_disable(LDAPQuery):
    __doc__ = _('Disable a user account.')

    has_output = output.standard_value
    msg_summary = _('Disabled user account "%(value)s"')

    def execute(self, *keys, **options):
        ldap = self.obj.backend

        check_protected_member(keys[-1])

        dn = self.obj.get_either_dn(*keys, **options)
        ldap.deactivate_entry(dn)

        return dict(
            result=True,
            value=pkey_to_value(keys[0], options),
        )


@register()
class user_enable(LDAPQuery):
    __doc__ = _('Enable a user account.')

    has_output = output.standard_value
    has_output_params = LDAPQuery.has_output_params + user_output_params
    msg_summary = _('Enabled user account "%(value)s"')

    def execute(self, *keys, **options):
        ldap = self.obj.backend

        dn = self.obj.get_either_dn(*keys, **options)

        ldap.activate_entry(dn)

        return dict(
            result=True,
            value=pkey_to_value(keys[0], options),
        )


@register()
class user_unlock(LDAPQuery):
    __doc__ = _("""
    Unlock a user account

    An account may become locked if the password is entered incorrectly too
    many times within a specific time period as controlled by password
    policy. A locked account is a temporary condition and may be unlocked by
    an administrator.""")

    has_output = output.standard_value
    msg_summary = _('Unlocked account "%(value)s"')

    def execute(self, *keys, **options):
        dn = self.obj.get_either_dn(*keys, **options)
        entry = self.obj.backend.get_entry(
            dn, ['krbLastAdminUnlock', 'krbLoginFailedCount'])

        entry['krbLastAdminUnlock'] = [strftime("%Y%m%d%H%M%SZ", gmtime())]
        entry['krbLoginFailedCount'] = ['0']

        self.obj.backend.update_entry(entry)

        return dict(
            result=True,
            value=pkey_to_value(keys[0], options),
        )


@register()
class user_status(LDAPQuery):
    __doc__ = _("""
    Lockout status of a user account

    An account may become locked if the password is entered incorrectly too
    many times within a specific time period as controlled by password
    policy. A locked account is a temporary condition and may be unlocked by
    an administrator.

    This connects to each IPA master and displays the lockout status on
    each one.

    To determine whether an account is locked on a given server you need
    to compare the number of failed logins and the time of the last failure.
    For an account to be locked it must exceed the maxfail failures within
    the failinterval duration as specified in the password policy associated
    with the user.

    The failed login counter is modified only when a user attempts a log in
    so it is possible that an account may appear locked but the last failed
    login attempt is older than the lockouttime of the password policy. This
    means that the user may attempt a login again. """)

    has_output = output.standard_list_of_entries
    has_output_params = LDAPSearch.has_output_params + status_output_params

    def execute(self, *keys, **options):
        ldap = self.obj.backend
        dn = self.obj.get_either_dn(*keys, **options)
        attr_list = ['krbloginfailedcount', 'krblastsuccessfulauth', 'krblastfailedauth', 'nsaccountlock']

        disabled = False
        masters = []
        # Get list of masters
        try:
            (masters, truncated) = ldap.find_entries(
                None, ['*'], DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn),
                ldap.SCOPE_ONELEVEL
            )
        except errors.NotFound:
            # If this happens we have some pretty serious problems
            self.error('No IPA masters found!')
            pass

        entries = []
        count = 0
        for master in masters:
            host = master['cn'][0]
            if host == api.env.host:
                other_ldap = self.obj.backend
            else:
                other_ldap = ldap2(self.api, ldap_uri='ldap://%s' % host)
                try:
                    other_ldap.connect(ccache=os.environ['KRB5CCNAME'])
                except Exception as e:
                    self.error("user_status: Connecting to %s failed with %s" % (host, str(e)))
                    newresult = {'dn': dn}
                    newresult['server'] = _("%(host)s failed: %(error)s") % dict(host=host, error=str(e))
                    entries.append(newresult)
                    count += 1
                    continue
            try:
                entry = other_ldap.get_entry(dn, attr_list)
                newresult = {'dn': dn}
                for attr in ['krblastsuccessfulauth', 'krblastfailedauth']:
                    newresult[attr] = entry.get(attr, [u'N/A'])
                newresult['krbloginfailedcount'] = entry.get('krbloginfailedcount', u'0')
                if not options.get('raw', False):
                    for attr in ['krblastsuccessfulauth', 'krblastfailedauth']:
                        try:
                            if newresult[attr][0] == u'N/A':
                                continue
                            newtime = time.strptime(newresult[attr][0], '%Y%m%d%H%M%SZ')
                            newresult[attr][0] = unicode(time.strftime('%Y-%m-%dT%H:%M:%SZ', newtime))
                        except Exception as e:
                            self.debug("time conversion failed with %s" % str(e))
                            pass
                newresult['server'] = host
                if options.get('raw', False):
                    time_format = '%Y%m%d%H%M%SZ'
                else:
                    time_format = '%Y-%m-%dT%H:%M:%SZ'
                newresult['now'] = unicode(strftime(time_format, gmtime()))
                convert_nsaccountlock(entry)
                if 'nsaccountlock' in entry:
                    disabled = entry['nsaccountlock']
                self.obj.get_preserved_attribute(entry, options)
                entries.append(newresult)
                count += 1
            except errors.NotFound:
                self.obj.handle_not_found(*keys)
            except Exception as e:
                self.error("user_status: Retrieving status for %s failed with %s" % (dn, str(e)))
                newresult = {'dn': dn}
                newresult['server'] = _("%(host)s failed") % dict(host=host)
                entries.append(newresult)
                count += 1

            if host != api.env.host:
                other_ldap.disconnect()

        return dict(result=entries,
                    count=count,
                    truncated=False,
                    summary=unicode(_('Account disabled: %(disabled)s' %
                        dict(disabled=disabled))),
        )


@register()
class user_add_cert(LDAPAddAttribute):
    __doc__ = _('Add one or more certificates to the user entry')
    msg_summary = _('Added certificates to user "%(value)s"')
    attribute = 'usercertificate'

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
                     **options):
        dn = self.obj.get_either_dn(*keys, **options)

        self.obj.convert_usercertificate_pre(entry_attrs)

        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)

        self.obj.convert_usercertificate_post(entry_attrs, **options)

        return dn


@register()
class user_remove_cert(LDAPRemoveAttribute):
    __doc__ = _('Remove one or more certificates to the user entry')
    msg_summary = _('Removed certificates from user "%(value)s"')
    attribute = 'usercertificate'

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
                     **options):
        dn = self.obj.get_either_dn(*keys, **options)

        self.obj.convert_usercertificate_pre(entry_attrs)

        return dn

    def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
        assert isinstance(dn, DN)

        self.obj.convert_usercertificate_post(entry_attrs, **options)

        return dn


@register()
class user_add_manager(baseuser_add_manager):
    __doc__ = _("Add a manager to the user entry")


@register()
class user_remove_manager(baseuser_remove_manager):
    __doc__ = _("Remove a manager to the user entry")