a
     {a                     @   s   d Z ddlZddlZddlZddlZddlZddlZddlmZmZ ddl	m
Z
mZ ddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlZdZdd ZG dd dejZG dd deZdS )z(Convenience functions for using the SAM.    N)dsdbdsdb_dns)
ndr_unpackndr_pack)drsblobsmisc)normalise_int32)	text_type)binary_type)	get_bytes)cmp)securityZrestructuredTextc                   C   s   dS )NZtdb r   r   r   -/usr/lib/python3/dist-packages/samba/samdb.pyget_default_backend_store-   s    r   c                       s  e Zd ZdZi Zi Zdddddejddddf
 fdd	Zd fdd	Z	d	d
 Z
dd Zdd Zdd Zdd Zdd ZdddZdd ZdddZdd Zdd Zdg d dfd!d"Zdd#d$Zdd%d&Zdd'd(Zd)d* Zdd+d,Zdd-d.Zd/d0 Zd1d2 Zeeed3d4Zd5d6 Z d7d8 Z!ee!e d9d4Z"d:d; Z#dd<d=Z$d>d? Z%d@dA Z&dBdC Z'dDdE Z(dFdG Z)dHdI Z*dJdK Z+dLdM Z,dNdO Z-dPdQ Z.dRdS Z/dTdU Z0dVdW Z1ddXdYZ2ddZd[Z3d\d] Z4d^d_ Z5d`da Z6dbdc Z7ddde Z8dfdg Z9ddhdiZ:djdk Z;dldm Z<dndo Z=dpdq Z>drds Z?dtdu Z@dvdw ZAdxdy ZBdzd{ ZCd|d} ZDd~d ZEdd ZFdd ZGdd ZHdddZI fddZJdd ZKdd ZLdddZMdd ZNdd ZOdd ZPdddZQdd ZRdd ZSdd ZTdd ZUdd ZV  ZWS )SamDBzThe SAM database.NTc              	      sr   || _ |	sd }n|d u r(|d ur(| }|| _tt| j|||||||d |rZt|  |
d urnt| |
 d S )N)urllpmodules_dirsession_infocredentialsflagsoptions)	r   Z	samdb_urlr   superr   __init__r   Z_dsdb_set_global_schemaZ_dsdb_set_am_rodc)selfr   r   r   r   r   r   r   Zglobal_schemaZauto_connectam_rodc	__class__r   r   r   7   s    
zSamDB.__init__r   c                    sB   | j dur"tj|s"| j |}|| _tt| j|||d dS )zconnect to the databaseN)r   r   r   )	r   ospathexistsZprivate_pathr   r   r   connect)r   r   r   r   r   r   r   r"   M   s    zSamDB.connectc                 C   s
   t | S )zreturn True if we are an RODC)r   Z_am_rodcr   r   r   r   r   V   s    zSamDB.am_rodcc                 C   s
   t | S )z%return True if we are an PDC emulator)r   Z_am_pdcr#   r   r   r   am_pdcZ   s    zSamDB.am_pdcc                 C   s   t |  S )zreturn the domain DN)strget_default_basednr#   r   r   r   	domain_dn^   s    zSamDB.domain_dnc                 C   s   t |  S )zreturn the schema partition dn)r%   Zget_schema_basednr#   r   r   r   	schema_dnb   s    zSamDB.schema_dnc                 C   s   t jj}| j||dd dS )z|Disables an account

        :param search_filter: LDAP filter to find the user (eg
            samccountname=name)
        TonN)sambar   UF_ACCOUNTDISABLEtoggle_userAccountFlagsr   search_filterr   r   r   r   disable_accountf   s    zSamDB.disable_accountc                 C   s$   t jjt jjB }| j||dd dS )z{Enables an account

        :param search_filter: LDAP filter to find the user (eg
            samccountname=name)
        Fr)   N)r+   r   r,   ZUF_PASSWD_NOTREQDr-   r.   r   r   r   enable_accountp   s    zSamDB.enable_accountFc                 C   s   | j |  tj|dgd}t|dkr2td| t|dksBJ |d j}t|d d d }|r|r||@ rd| }	t|	||B }
n&|r||@ sd| }	t|	|| @ }
||
krdS d	|||
f }| | dS )
an  Toggle_userAccountFlags

        :param search_filter: LDAP filter to find the user (eg
            samccountname=name)
        :param flags: samba.dsdb.UF_* flags
        :param on: on=True (default) => set, on=False => unset
        :param strict: strict=False (default) ignore if no action is needed
                 strict=True raises an Exception if...
        userAccountControlbasescope
expressionattrsr   z!Unable to find account where '%s'   z Account flag(s) '%s' already setz"Account flag(s) '%s' already unsetNz|
dn: %s
changetype: modify
delete: userAccountControl
userAccountControl: %u
add: userAccountControl
userAccountControl: %u
)	searchr'   ldbSCOPE_SUBTREElen	Exceptiondnintmodify_ldif)r   r/   r   Z	flags_strr*   strictresZ
account_dnZold_uacerrorZnew_uacmodr   r   r   r-   z   s.    


zSamDB.toggle_userAccountFlagsc                 C   s`   | j |  tj|g d}t|dkr0td| t|dks@J |d j}d| }| | dS )zForces a password change at next login

        :param search_filter: LDAP filter to find the user (eg
            samccountname=name)
        r3   r   Unable to find user "%s"r8   z=
dn: %s
changetype: modify
replace: pwdLastSet
pwdLastSet: 0
N)r9   r'   r:   r;   r<   r=   r>   r@   )r   r/   rB   user_dnrD   r   r   r   #force_password_change_at_next_login   s    
z)SamDB.force_password_change_at_next_loginc
                 C   s   d||p
d|   f }
|
|dd}|dur6t||d< |durF||d< |durV||d< |durf||d	< |durzt||d
< |	dur||d< |	|d< |durt||d< | | dS )a  Adds a new group with additional parameters

        :param groupname: Name of the new group
        :param grouptype: Type of the new group
        :param description: Description of the new group
        :param mailaddress: Email address of the new group
        :param notes: Notes of the new group
        :param gidnumber: GID Number of the new group
        :param nisdomain: NIS Domain Name of the new group
        :param sd: security descriptor of the object
        CN=%s,%s,%sCN=Usersgroupr>   sAMAccountNameobjectClassNZ	groupTypedescriptionmailinfo	gidNumbermsSFU30NamemsSFU30NisDomainnTSecurityDescriptor)r'   r   r   add)r   	groupnameZgroupouZ	grouptyperN   mailaddressZnotessd	gidnumber	nisdomainZgroup_dn
ldbmessager   r   r   newgroup   s*    zSamDB.newgroupc                 C   s   dt |d|  f }|   zT| j|  t j|g d}t|dkrRtd| t|dksbJ | |d j	 W n   | 
   Y n
0 |   dS )zLDeletes a group

        :param groupname: Name of the target group
        ,(&(sAMAccountName=%s)(objectCategory=%s,%s))#CN=Group,CN=Schema,CN=Configurationr3   r   Unable to find group "%s"r8   Nr:   binary_encoder'   transaction_startr9   r;   r<   r=   deleter>   transaction_canceltransaction_commit)r   rV   groupfiltertargetgroupr   r   r   deletegroup   s    zSamDB.deletegroupc                 C   s  d}g d}d|v r|}|D ]"}||vrt d|d|f qd|v r`|dt|tjf 7 }d|v rz|d	t| 7 }d
|v r|}|d dkrd| }|dtjt|f 7 }d|v r|}|d dkrd| }|dtjt|f 7 }d|v r|dt| 7 }d| }|S )N )userrJ   computerserviceaccountcontactallz;Invalid group member type "%s". Valid types are %s and all.z, rj   z)(&(sAMAccountName=%s)(samAccountType=%d))rJ   zQ(&(sAMAccountName=%s)(objectClass=group)(!(groupType:1.2.840.113556.1.4.803:=1)))rk   $%s$zW(&(samAccountType=%d)(!(objectCategory=msDS-ManagedServiceAccount))(sAMAccountName=%s))rl   zT(&(samAccountType=%d)(objectCategory=msDS-ManagedServiceAccount)(sAMAccountName=%s))rm   z3(&(objectCategory=Person)(!(objectSid=*))(name=%s))z(|%s))r=   joinr:   ra   r   ZATYPE_NORMAL_ACCOUNTZATYPE_WORKSTATION_TRUST)r   membermember_typesfilterZall_member_typesmember_typesamaccountnamer   r   r   group_member_filter   sR    
zSamDB.group_member_filter)rj   rJ   rk   c                 C   s  dt |d|  f }|   zj| j|  t j|dgd}t|dkrVtd| t|dksfJ d}d	t|d j	 }	|D ]}
d
}|d
u r|  }zt
|
}dt| }W n$ ty } zW Y d
}~n
d
}~0 0 |d
u rJz>t | |
}| |dkr| |}n|}|d}W n& tyH } zW Y d
}~n
d
}~0 0 |d
u r| |
|}| j|t j|g d}t|dkrd}|D ]}|d|d 7 }qtd|
|f t|dkrtd|
 |d j	d}|du r2|d dd
u st|dd |d d D vr2d}|	dt| 7 }	q|du r|d dd
urt||d d v rd}|	dt| 7 }	q|du r| |	 W n   |    Y n
0 |   d
S )zAdds or removes group members

        :param groupname: Name of the target group
        :param members: list of group members
        :param add_members_operation: Defines if its an add or remove
            operation
        r]   r^   rs   r3   r   r_   r8   Fz
dn: %s
changetype: modify
Nz<SID=%s>ri   z%s
r>   z#Found multiple results for "%s":
%sz)Unable to find "%s". Operation cancelled.Tc                 S   s   g | ]}t |qS r   )r%   ).0xr   r   r   
<listcomp>z      z2SamDB.add_remove_group_members.<locals>.<listcomp>zadd: member
member: %s
zdelete: member
member: %s
)r:   ra   r'   rb   r9   r;   r<   r=   r%   r>   r   Zdom_sid	TypeErrorDnget_linearizedextended_strnormalize_dn_in_domain
ValueErrorrx   getr   r@   rd   re   )r   rV   membersZadd_members_operationrt   Zmember_base_dnrf   rg   ZmodifiedZaddtargettogrouprs   Ztargetmember_dnZ	membersideZ	member_dnZfull_member_dnru   ZtargetmemberZtargetmemberlist_strmsgr   r   r   add_remove_group_members5  s    



>.
zSamDB.add_remove_group_membersc           &   
   C   s  d}|dur||7 }|dur(|d| 7 }|dur<|d| 7 }|} |du rT|dkrT|} d| |p^d|   f }!t| |    dd}"d||"f }#|!||#d	d
}$|rttjtjB |$d< d}|dur||$d< |dur||$d< |dkr||$d< ||$d< |dur
d| |$d< |	dur|	|$d< |
dur.|
|$d< |dur@||$d< |durR||$d< |durd||$d< |durv||$d< |dur||$d< |dur||$d< |dur||$d< |dur||$d< |dur||$d< |dur||$d< |durt	||$d< d}%t
td d! |||||||frNt }%t| |!|%_|durVtt|tjd"|%d"< |durxtt|tjd#|%d#< |durtt|tjd$|%d$< |durtt|tjd%|%d%< |durtt|tjd&|%d&< |dur tt|tjd'|%d'< |durNtt|tjd(|%d(< tt|tjd)|%d)< td*tjd+|%d+< |   z<| |$ |%rr| |% |r| d,t|! || W n   |    Y n
0 |   dS )-al  Adds a new user with additional parameters

        :param username: Name of the new user
        :param password: Password for the new user
        :param force_password_change_at_next_login_req: Force password change
        :param useusernameascn: Use username as cn rather that firstname +
            initials + lastname
        :param userou: Object container (without domainDN postfix) for new user
        :param surname: Surname of the new user
        :param givenname: First name of the new user
        :param initials: Initials of the new user
        :param profilepath: Profile path of the new user
        :param scriptpath: Logon script path of the new user
        :param homedrive: Home drive of the new user
        :param homedirectory: Home directory of the new user
        :param jobtitle: Job title of the new user
        :param department: Department of the new user
        :param company: Company of the new user
        :param description: of the new user
        :param mailaddress: Email address of the new user
        :param internetaddress: Home page of the new user
        :param telephonenumber: Phone number of the new user
        :param physicaldeliveryoffice: Office location of the new user
        :param sd: security descriptor of the object
        :param setpassword: optionally disable password reset
        :param uidnumber: RFC2307 Unix numeric UID of the new user
        :param gidnumber: RFC2307 Unix primary GID of the new user
        :param gecos: RFC2307 Unix GECOS field of the new user
        :param loginshell: RFC2307 Unix login shell of the new user
        :param uid: RFC2307 Unix username of the new user
        :param nisdomain: RFC2307 Unix NIS domain of the new user
        :param unixhome: RFC2307 Unix home directory of the new user
        :param smartcard_required: set the UF_SMARTCARD_REQUIRED bit of the new user
        ri   N %s. %srH   rI   /z%s@%srj   )r>   rL   ZuserPrincipalNamerM   r2   Fsn	givenNamedisplayNamename%s.initialsZprofilePathZ
scriptPathZ	homeDriveZhomeDirectorytitle
departmentcompanyrN   rO   wWWHomePagetelephoneNumberphysicalDeliveryOfficeNamerT   c                 S   s   | d uS Nr   )br   r   r   <lambda>  r|   zSamDB.newuser.<locals>.<lambda>uidZ	uidNumberrQ   gecosZ
loginShellZunixHomeDirectoryrS   rR   zABCD!efgh12345$67890ZunixUserPassword(distinguishedName=%s))r'   r:   r~   canonical_strreplacer%   r   ZUF_NORMAL_ACCOUNTZUF_SMARTCARD_REQUIREDr   anymapMessager>   MessageElementFLAG_MOD_REPLACErb   rU   modifysetpasswordra   rd   re   )&r   usernamepasswordZ'force_password_change_at_next_login_reqZuseusernameascnZuserousurname	givennamer   ZprofilepathZ
scriptpathZ	homedriveZhomedirectoryjobtitler   r   rN   rW   internetaddresstelephonenumberphysicaldeliveryofficerX   r   Z	uidnumberrY   r   Z
loginshellr   rZ   ZunixhomeZsmartcard_requireddisplaynamecnrF   Z	dnsdomainZuser_principal_namer[   Zldbmessage2r   r   r   newuser  s    -
























zSamDB.newuserc                 C   s|  d}|dur||7 }|dur(|d| 7 }|dur<|d| 7 }|durH|}|du r`|dkr`t d|  }|rv| |}d||f }|dd}|dur||d	< |dur||d
< |dur||d< |durd| |d< |dur||d< |dur||d< |	dur|	|d< |
dur|
|d< |dur&||d< |dur8||d< |durJ||d< |dur\||d< |durn||d< | | |S )a  Adds a new contact with additional parameters

        :param fullcontactname: Optional full name of the new contact
        :param ou: Object container for new contact
        :param surname: Surname of the new contact
        :param givenname: First name of the new contact
        :param initials: Initials of the new contact
        :param displayname: displayName of the new contact
        :param jobtitle: Job title of the new contact
        :param department: Department of the new contact
        :param company: Company of the new contact
        :param description: Description of the new contact
        :param mailaddress: Email address of the new contact
        :param internetaddress: Home page of the new contact
        :param telephonenumber: Phone number of the new contact
        :param mobilenumber: Primary mobile number of the new contact
        :param physicaldeliveryoffice: Office location of the new contact
        ri   Nr   r   zNo name for contact specifiedCN=%s,%srm   r>   rM   r   r   r   r   r   r   r   r   rN   rO   r   r   Zmobiler   )r=   r'   r   rU   )r   ZfullcontactnameZour   r   r   r   r   r   r   rN   rW   r   r   Zmobilenumberr   r   Zcontactcontainer_dnZ
contact_dnr[   r   r   r   
newcontact;  s\    $








zSamDB.newcontactc                 C   s  t dd|}|dr$td| d| }d|   }	|rF| |}	d||	f }
|
|dd	}|d
urn||d< |rz||d< ttjtj	B }|rttj}||d< |rd
||  |d< |   z2| | |r| }| dt|
 |d W n   |    Y n
0 |   d
S )a  Adds a new user with additional parameters

        :param computername: Name of the new computer
        :param computerou: Object container for new computer
        :param description: Description of the new computer
        :param prepare_oldjoin: Preset computer password for oldjoin mechanism
        :param ip_address_list: ip address list for DNS A or AAAA record
        :param service_principal_name_list: string list of servicePincipalName
        z\$$ri   rp   zIllegal computername "%s"rq   zCN=Computers,%sr   rk   rK   NrN   ZservicePrincipalNamer2   z{}.{}dNSHostNamer   F)resubcountr=   r'   r   r%   r   ZUF_WORKSTATION_TRUST_ACCOUNTr,   formatdomain_dns_namerb   rU   lowerr   r:   ra   rd   re   )r   ZcomputernameZ
computerourN   Zprepare_oldjoinZip_address_listZservice_principal_name_listr   rw   Zcomputercontainer_dnZcomputer_dnr[   Zaccountcontrolr   r   r   r   newcomputer  sP    



zSamDB.newcomputerc                 C   s   dt |d|  f }|   zT| j|  t j|g d}t|dkrRtd| t|dksbJ | |d j	 W n   | 
   Y n
0 |   dS )zIDeletes a user

        :param username: Name of the target user
        r]   z$CN=Person,CN=Schema,CN=Configurationr3   r   rE   r8   Nr`   )r   r   ru   targetr   r   r   
deleteuser  s    zSamDB.deleteuserc           	      C   s   |    z| j|  tj|g d}t|dkr>td|p8| t|dkr^tdt||f |d j}t|t	s~|
d}n|}d| d d}d	|t|
df }| | |r| d
t| d  | | W n   |    Y n
0 |   dS )zSets the password for a user

        :param search_filter: LDAP filter to find the user (eg
            samccountname=name)
        :param password: Password for the user
        :param force_change_at_next_login: Force password change
        r3   r   rE   r8   z*Matched %u multiple users with filter "%s"utf-8"z	utf-16-lez?
dn: %s
changetype: modify
replace: unicodePwd
unicodePwd:: %s
z(distinguishedName=)N)rb   r9   r'   r:   r;   r<   r=   r>   
isinstancer	   decodeencodebase64Z	b64encoder@   rG   r%   r1   rd   re   )	r   r/   r   Zforce_change_at_next_loginr   rB   rF   ZpwZsetpwr   r   r   r     s6    	


zSamDB.setpasswordc           	      C   s   |    z| j|  tj|ddgd}t|dkr>td| t|dksNJ |d j}t|d d d }t|d d d }|r|dB }d}n|d@ }t	
|tt  }d	|||f }| | W n   |    Y n
0 |   d
S )a  Sets the account expiry for a user

        :param search_filter: LDAP filter to find the user (eg
            samaccountname=name)
        :param expiry_seconds: expiry time from now in seconds
        :param no_expiry_req: if set, then don't expire password
        r2   accountExpiresr3   r   rE   r8   i   izy
dn: %s
changetype: modify
replace: userAccountControl
userAccountControl: %u
replace: accountExpires
accountExpires: %u
N)rb   r9   r'   r:   r;   r<   r=   r>   r?   r+   unix2nttimetimer@   rd   re   )	r   r/   Zexpiry_secondsZno_expiry_reqrB   rF   r2   r   Zsetexpr   r   r   	setexpiry$  s2    
	zSamDB.setexpiryc                 C   s   t | | dS )z`Change the domain SID used by this LDB.

        :param sid: The new domain sid to use.
        N)r   Z_samdb_set_domain_sid)r   Zsidr   r   r   set_domain_sidO  s    zSamDB.set_domain_sidc                 C   s
   t | S )z&Read the domain SID used by this LDB. )r   Z_samdb_get_domain_sidr#   r   r   r   get_domain_sidV  s    zSamDB.get_domain_sidzSID for the domain)docc                 C   s   t | | dS )zoSet the invocation id for this SamDB handle.

        :param invocation_id: GUID of the invocation id.
        N)r   Z_dsdb_set_ntds_invocation_id)r   invocation_idr   r   r   set_invocation_id]  s    zSamDB.set_invocation_idc                 C   s
   t | S )zGet the invocation_id id)r   Z_samdb_ntds_invocation_idr#   r   r   r   get_invocation_idd  s    zSamDB.get_invocation_idzInvocation ID GUIDc                 C   s   t | |S r   )r   Z_dsdb_get_oid_from_attidr   attidr   r   r   get_oid_from_attidk  s    zSamDB.get_oid_from_attidc                 C   s   t | ||S )zNreturn the attribute ID for a LDAP attribute as an integer as found in DRSUAPI)r   Z$_dsdb_get_attid_from_lDAPDisplayName)r   ldap_display_nameZis_schema_ncr   r   r   get_attid_from_lDAPDisplayNamen  s    z$SamDB.get_attid_from_lDAPDisplayNamec                 C   s   t | |S )z6return the syntax OID for a LDAP attribute as a string)r   Z)_dsdb_get_syntax_oid_from_lDAPDisplayNamer   r   r   r   r   #get_syntax_oid_from_lDAPDisplayNamet  s    z)SamDB.get_syntax_oid_from_lDAPDisplayNamec                 C   s   t | |S )z8return the systemFlags for a LDAP attribute as a integer)r   Z*_dsdb_get_systemFlags_from_lDAPDisplayNamer   r   r   r   $get_systemFlags_from_lDAPDisplayNamex  s    z*SamDB.get_systemFlags_from_lDAPDisplayNamec                 C   s   t | |S )z3return the linkID for a LDAP attribute as a integer)r   Z%_dsdb_get_linkId_from_lDAPDisplayNamer   r   r   r   get_linkId_from_lDAPDisplayName|  s    z%SamDB.get_linkId_from_lDAPDisplayNamec                 C   s   t | |S )z;return the lDAPDisplayName from an integer DRS attribute ID)r   Z"_dsdb_get_lDAPDisplayName_by_attidr   r   r   r   get_lDAPDisplayName_by_attid  s    z"SamDB.get_lDAPDisplayName_by_attidc                 C   s   t | |S )zreturn the attribute name of the corresponding backlink from the name
        of a forward link attribute. If there is no backlink return None)r   Z'_dsdb_get_backlink_from_lDAPDisplayNamer   r   r   r   !get_backlink_from_lDAPDisplayName  s    z'SamDB.get_backlink_from_lDAPDisplayNamec                 C   s   t | | dS )zSet the NTDS Settings DN, as would be returned on the dsServiceName
        rootDSE attribute.

        This allows the DN to be set before the database fully exists

        :param ntds_settings_dn: The new DN to use
        N)r   Z_samdb_set_ntds_settings_dn)r   Zntds_settings_dnr   r   r   set_ntds_settings_dn  s    zSamDB.set_ntds_settings_dnc                 C   s
   t | S )zGet the NTDS objectGUID)r   Z_samdb_ntds_objectGUIDr#   r   r   r   get_ntds_GUID  s    zSamDB.get_ntds_GUIDc                 C   s
   t | S )zGet the server site name)r   Z_samdb_server_site_namer#   r   r   r   server_site_name  s    zSamDB.server_site_namec                 C   s(   | j dtjdgd}t|d d d S )z return the DNS name of this hostri   r   r4   r5   r7   r   r9   r:   
SCOPE_BASEr%   r   rB   r   r   r   host_dns_name  s    zSamDB.host_dns_namec                 C   s   |   }| dd S )z&return the DNS name of the domain rootr   r   )r&   r   split)r   r'   r   r   r   r     s    zSamDB.domain_dns_namec                 C   sh   |   }|  }d||f }|  }| j|tj|d}z|d d d  }W n tyb   Y dS 0 |S )z*return the NetBIOS name of the domain rootz?(&(objectClass=crossRef)(nETBIOSName=*)(ncName=%s)(dnsroot=%s)))r5   r6   r   ZnETBIOSNameN)r&   r   get_partitions_dnr9   r:   ZSCOPE_ONELEVELr   
IndexError)r   r'   dns_nameru   Zpartitions_dnrB   Znetbios_domainr   r   r   domain_netbios_name  s    zSamDB.domain_netbios_namec                 C   s   |   }| dd S )z&return the DNS name of the forest rootr   r   )Zget_root_basednr   r   )r   Z	forest_dnr   r   r   forest_dns_name  s    zSamDB.forest_dns_namec                 C   s   t | |S r   )r   Z_dsdb_load_partition_usn)r   Zbase_dnr   r   r   load_partition_usn  s    zSamDB.load_partition_usnc                 C   s   | j |j|d d S )N)write_indices_and_attributes)set_schema_from_ldbr:   )r   Zschemar   r   r   r   
set_schema  s    zSamDB.set_schemac                 C   s   t | || d S r   )r   Z_dsdb_set_schema_from_ldb)r   Zldb_connr   r   r   r   r     s    zSamDB.set_schema_from_ldbc                 C   s   d}|  | d S )Nz@
dn:
changetype: modify
add: schemaUpdateNow
schemaUpdateNow: 1
)r@   )r   Zldifr   r   r   set_schema_update_now  s    zSamDB.set_schema_update_nowc                 C   s   t |||S )zBconvert a list of attribute values to a DRSUAPI DsReplicaAttribute)r   Z_dsdb_DsReplicaAttributer   r:   r   Zldif_elementsr   r   r   dsdb_DsReplicaAttribute  s    zSamDB.dsdb_DsReplicaAttributec                 C   s   t |||S )z$normalise a list of attribute values)r   Z_dsdb_normalise_attributesr   r   r   r   dsdb_normalise_attributes  s    zSamDB.dsdb_normalise_attributesc                 C   sB   t | j dkr|   | || jv r:| j| | S dS dS )z Get from an attid the associated attribute

        :param attid: The attribute id for searched attribute
        :return: The name of the attribute associated with this id
        r   N)r<   hash_oid_namekeys_populate_oid_attidr   r   r   r   r   get_attribute_from_attid  s
    zSamDB.get_attribute_from_attidc                 C   sX   i | _ | jddgddgd}t|dkrT|D ]&}t|d}|| j t|d< q,dS )zPopulate the hash hash_oid_name.

        This hash contains the oid of the attribute as a key and
        its display name as a value
        zobjectClass=attributeSchemasearch_options:1:2ZattributeIDZlDAPDisplayName)r6   controlsr7   r   N)r   r9   r<   r%   r   )r   rB   r   Z
strDisplayr   r   r   r     s    zSamDB._populate_oid_attidc                 C   s   | j d| tjdgdgd}t|dkr,dS ttj|d d d }|j}t| j	 dkrd| 
  |jD ]:}| |j}|| jv rj| | j|  krj|j  S qjdS )a[  Get the version field trom the replPropertyMetaData for
        the given field

        :param dn: The on which we want to get the version
        :param att: The name of the attribute
        :return: The value of the version field in the replPropertyMetaData
            for the given attribute. None if the attribute is not replicated
        distinguishedName=%sr   replPropertyMetaDatar6   r5   r   r7   r   N)r9   r:   r;   r<   r   r   replPropertyMetaDataBlobctrr   r   r   arrayr   r   r   version)r   r>   attrB   replr   oatt_oidr   r   r   "get_attribute_replmetadata_version  s(    



z(SamDB.get_attribute_replmetadata_versionc                 C   s  | j d| tjdgdgd}t|dkr,d S ttj|d d d }|j}t	t
t }d}	t| j dkrz|   |jD ]h}
| |
j}|| jv r| | j|  krd}	| tj}||
_||
_t|  |
_||
_||
_q|	sz|rzt|jdkrzt }d|_| |j}| tj}||_||_t|  |_||_||_d}	|j}|| |jd	 |_||_|	rt |}t! }|d j"|_"t#|tj$d|d< | %|d
g d S )Nr   r   r   r   r   FTiZ 	 r8   z#local_oid:1.3.6.1.4.1.7165.4.3.14:0)&r9   r:   r;   r<   r   r   r   r   r+   r   r?   r   r   r   r   r   r   r   r   sequence_numberZSEQ_NEXTr   Zoriginating_change_timer   GUIDr   Zoriginating_invocation_idZoriginating_usnZ	local_usnZreplPropertyMetaData1appendr   r   r   r>   r   r   r   )r   r>   r   valueZaddifnotexistrB   r   r   Znowfoundr   r   seqZo2ZtabZreplBlobr   r   r   r   "set_attribute_replmetadata_version  sh    



z(SamDB.set_attribute_replmetadata_versionc                 C   s   t |  d S r   )r   Z'_dsdb_write_prefixes_from_schema_to_ldbr#   r   r   r   write_prefixes_from_schemaE  s    z SamDB.write_prefixes_from_schemac                 C   s
   t | S r   )r   Z_dsdb_get_partitions_dnr#   r   r   r   r   H  s    zSamDB.get_partitions_dnc                 C   s   t | |S r   )r   Z_dsdb_get_nc_root)r   r>   r   r   r   get_nc_rootK  s    zSamDB.get_nc_rootc                 C   sx   | j t|}d }|d ur&||}|d u rtt| ||}|d u rH|S |d u rli | j t|< | j t| }|||< |S r   )hash_well_knownr   r%   r   Z_dsdb_get_wellknown_dn)r   Znc_rootZwkguidZh_ncr>   r   r   r   get_wellknown_dnN  s    
zSamDB.get_wellknown_dnc                 C   sT   t |tst|d}t }t| |  |_t	|tj
d|d< | | d S )Nutf8	minPwdAger   r
   r%   r   r:   r   r~   r'   r>   r   r   r   r   r  mr   r   r   set_minPwdAge]  s    
zSamDB.set_minPwdAgec                 C   sP   | j |  tjdgd}t|dkr(d S d|d vr8d S t|d d d S d S )Nr  r5   r7   r   r9   r'   r:   r   r<   r?   r   r   r   r   get_minPwdAgee  s    zSamDB.get_minPwdAgec                 C   sT   t |tst|d}t }t| |  |_t	|tj
d|d< | | d S )Nr  	maxPwdAger  r  r   r   r   set_maxPwdAgen  s    
zSamDB.set_maxPwdAgec                 C   sP   | j |  tjdgd}t|dkr(d S d|d vr8d S t|d d d S d S )Nr  r  r   r  r   r   r   r   get_maxPwdAgev  s    zSamDB.get_maxPwdAgec                 C   sT   t |tst|d}t }t| |  |_t	|tj
d|d< | | d S )Nr  minPwdLengthr  r  r   r   r   set_minPwdLength  s    
zSamDB.set_minPwdLengthc                 C   sP   | j |  tjdgd}t|dkr(d S d|d vr8d S t|d d d S d S )Nr  r  r   r  r   r   r   r   get_minPwdLength  s    zSamDB.get_minPwdLengthc                 C   sT   t |tst|d}t }t| |  |_t	|tj
d|d< | | d S )Nr  pwdPropertiesr  r  r   r   r   set_pwdProperties  s    
zSamDB.set_pwdPropertiesc                 C   sP   | j |  tjdgd}t|dkr(d S d|d vr8d S t|d d d S d S )Nr  r  r   r  r   r   r   r   get_pwdProperties  s    zSamDB.get_pwdPropertiesc                 C   sb   t  }t | d|    |_|d ur@t |t jd|d< nt g t jd|d< | 	| d S )N1CN=Directory Service,CN=Windows NT,CN=Services,%sdSHeuristics)
r:   r   r~   get_config_basednr   r>   r   r   ZFLAG_MOD_DELETEr   )r   dsheuristicsr  r   r   r   set_dsheuristics  s    

zSamDB.set_dsheuristicsc                 C   sX   | j d|    tjdgd}t|dkr2d }n"d|d v rP|d d d }nd }|S )Nr  r   r  r   )r9   r!  r   r:   r   r<   )r   rB   r"  r   r   r   get_dsheuristics  s    
zSamDB.get_dsheuristicsc                 C   s@   |dd}|r||d< |r"||d< |r2t ||d< | | dS )a  Creates an organizationalUnit object
        :param ou_dn: dn of the new object
        :param description: description attribute
        :param name: name atttribute
        :param sd: security descriptor of the object, can be
        an SDDL string or security.descriptor type
        ZorganizationalUnitr   rN   r   rT   N)r   rU   )r   Zou_dnrN   r   rX   r  r   r   r   	create_ou  s    zSamDB.create_ouc                    s@   |    ztt| |}W n   |    Y n
0 |   |S )zReturns the value of the sequence number according to the requested type
        :param seq_type: type of sequence number
         )rb   r   r   r  rd   re   )r   Zseq_typer  r   r   r   r    s    zSamDB.sequence_numberc                 C   s(   | j dtjdgd}t|d d d S )z get the NTDS DN from the rootDSEri   ZdsServiceNamer   r   r   r   r   r   r   get_dsServiceName  s    zSamDB.get_dsServiceNamec                 C   s(   | j dtjdgd}t|d d d S )z"get the server DN from the rootDSEri   Z
serverNamer   r   r   r   r   r   r   get_serverName  s    zSamDB.get_serverNamec                 C   s(   |du rt | |S t j| ||dS dS )zDDo a DNS lookup in the database, returns the NDR database structuresN)dns_partition)r   lookup)r   r   r(  r   r   r   
dns_lookup  s
    zSamDB.dns_lookupc                 C   s   t | |S )z;Return the NDR database structures from a dnsRecord element)r   extract)r   Zelr   r   r   dns_extract  s    zSamDB.dns_extractc                 C   s   t | ||S )zfDo a DNS modification on the database, sets the NDR database
        structures on a DNS name
        )r   r   )r   r   new_recordsr   r   r   dns_replace  s    zSamDB.dns_replacec                 C   s   t | ||S )zDo a DNS modification on the database, sets the NDR database
        structures on a LDB DN

        This routine is important because if the last record on the DN
        is removed, this routine will put a tombstone in the record.
        )r   Zreplace_by_dn)r   r>   r-  r   r   r   dns_replace_by_dn  s    zSamDB.dns_replace_by_dnc                 C   s*   |du rt | ||S t | |||S dS )zgarbage_collect_tombstones(lp, samdb, [dn], current_time, tombstone_lifetime)
        -> (num_objects_expunged, num_links_expunged)N)r   Z _dsdb_garbage_collect_tombstones)r   r>   Zcurrent_timeZtombstone_lifetimer   r   r   garbage_collect_tombstones  s    z SamDB.garbage_collect_tombstonesc                 C   s
   t | S )zcreate a RID set for this DSA)r   Z_dsdb_create_own_rid_setr#   r   r   r   create_own_rid_set  s    zSamDB.create_own_rid_setc                 C   s
   t | S )z.return a new RID from the RID Pool on this DSA)r   Z_dsdb_allocate_ridr#   r   r   r   allocate_rid  s    zSamDB.allocate_ridc                 C   s   |   \}}|S )aE  return the next free RID from the RID Pool on this DSA.

        :note: This function is not intended for general use, and care must be
            taken if it is used to generate objectSIDs. The returned RID is not
            formally reserved for use, creating the possibility of duplicate
            objectSIDs.
        )free_rid_bounds)r   Zrid_r   r   r   next_free_rid  s    zSamDB.next_free_ridc                 C   sJ  t | |  }| j|t jdgd}z|d d }W n& tyZ   t t jd| dY n0 t | |d d}| j|t jdgd}z|d d }W n& ty   t t jd| dY n0 t | |d d}| j|t jg d	d}d
}d}zt	|d d d }	W n ty"   |}	Y n0 |	|kr@t t j
d| zt	|d d d }
W n typ   |}
Y n0 zt	|d d d }W n ty   |}Y n0 |
|ks||kr|	}
|
|@ }|d7 }|
|@ }|
d? }||kr|	|
krt t j
d|	}
|
|@ }|
d? }|}||k s*||krBt t j
d|||f ||fS )a  return the low and high bounds (inclusive) of RIDs that are
            available for use in this DSA's current RID pool.

        :note: This function is not intended for general use, and care must be
            taken if it is used to generate objectSIDs. The returned range of
            RIDs is not formally reserved for use, creating the possibility of
            duplicate objectSIDs.
        ZserverReferencer   r   zUNo RID Set DN - Cannot find attribute serverReference of %s to calculate reference dnNr   ZrIDSetReferenceszVNo RID Set DN - Cannot find attribute rIDSetReferences of %s to calculate reference dn)rIDAllocationPoolrIDPreviousAllocationPool
rIDNextRIDl    l    r6  zBad RID Set %sr7  r8  r8       zRID pools out of RIDsz"Bad RID chosen %d from range %d-%d)r:   r~   r'  r9   r   KeyErrorZLdbErrorZERR_NO_SUCH_ATTRIBUTEr   r?   ZERR_OPERATIONS_ERROR)r   Zserver_name_dnrB   Z
server_refZserver_ref_dnZrid_set_refsZ
rid_set_dnZ
uint32_maxZ
uint64_maxZ
alloc_poolZ	prev_poolZnext_ridZprev_pool_loZprev_pool_hir   r   r   r3  $  s    






zSamDB.free_rid_boundsc                 C   sH   t | |  }t|t jr$t|}t | |}||sD|| |S )zreturn a new DN expanded by adding the domain DN

        If the dn is already a child of the domain DN, just
        return it as-is.

        :param dn: relative dn
        )r:   r~   r'   r   r%   Zis_child_ofZadd_base)r   r>   r'   Zfull_dnr   r   r   r     s    

zSamDB.normalize_dn_in_domain)Nr   N)NTF)NNNNNNNN)FFNNNNNNNNNNNNNNNNNTNNNNNNNF)NNNNNNNNNNNNNNN)NNFNN)FN)F)F)T)T)F)NNN)N)N)X__name__
__module____qualname____doc__r   r  r:   ZFLG_DONT_CREATE_DBr   r"   r   r$   r'   r(   r0   r1   r-   rG   r\   rh   rx   r   r   r   r   r   r   r   r   r   propertyZ
domain_sidr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r	  r   r
  r  r  r  r  r  r  r  r  r  r#  r$  r%  r  r&  r'  r*  r,  r.  r/  r0  r1  r2  r5  r3  r   __classcell__r   r   r   r   r   1   s  	

  
-   
/6
[         
 .               
l   
< 
,
+ 



	 
7				


 
^r   c                   @   sj   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )dsdb_Dnza class for binary DNNc                 C   s   |du r2| drtj}n| dr,tj}ntj}|tjtjfv r|d}t|dk rdtd| dt|d  t|d  }|d| | _	| j	d	t|d  d
 | _
||d | _n|| _d| _	d| _
t|| j| _dS )zcreate a dsdb_DnNzB:zS::   zInvalid DN %sr8   r      ro   ri   )
startswithr   ZDSDB_SYNTAX_BINARY_DNZDSDB_SYNTAX_STRING_DNZDSDB_SYNTAX_OR_NAMEr   r<   RuntimeErrorr?   prefixbinarydnstringr:   r~   r>   )r   ZsamdbrI  Z
syntax_oidZcolons
prefix_lenr   r   r   r     s$    


zdsdb_Dn.__init__c                 C   s   | j t| jjdd S )Nr8   )mode)rG  r%   r>   r   r#   r   r   r   __str__  s    zdsdb_Dn.__str__c                 C   sH   | }|}|j d}|j d}t||}|dkr6|S t|j|j}|S )z6 compare dsdb_Dn values similar to parsed_dn_compare()r  r   )r>   Zget_extended_componentr   rH  )r   otherZdn1Zdn2Zguid1Zguid2vr   r   r   __cmp__  s    
zdsdb_Dn.__cmp__c                 C   s   |  |dkS Nr   rO  r   rM  r   r   r   __eq__  s    zdsdb_Dn.__eq__c                 C   s   |  |dkS rP  rQ  rR  r   r   r   __ne__  s    zdsdb_Dn.__ne__c                 C   s   |  |dk S rP  rQ  rR  r   r   r   __lt__  s    zdsdb_Dn.__lt__c                 C   s   |  |dkS rP  rQ  rR  r   r   r   __le__  s    zdsdb_Dn.__le__c                 C   s   |  |dkS rP  rQ  rR  r   r   r   __gt__  s    zdsdb_Dn.__gt__c                 C   s   |  |dkS rP  rQ  rR  r   r   r   __ge__  s    zdsdb_Dn.__ge__c                 C   s   | j dkrdS t| jdS )z6return binary part of a dsdb_Dn as an integer, or Noneri   N   )rG  r?   rH  r#   r   r   r   get_binary_integer  s    
zdsdb_Dn.get_binary_integerc                 C   s   t | jS )zreturn binary as a byte string)binasciiZ	unhexlifyrH  r#   r   r   r   r     s    zdsdb_Dn.get_bytes)N)r;  r<  r=  r>  r   rL  rO  rS  rT  rU  rV  rW  rX  rZ  r   r   r   r   r   rA    s   
rA  )r>  r+   r:   r   r   r   r   r   r   Z	samba.ndrr   r   Zsamba.dcerpcr   r   Zsamba.commonr   Zsamba.compatr	   r
   r   r   r   r[  Z__docformat__r   ZLdbr   objectrA  r   r   r   r   <module>   s<             m