diff options
Diffstat (limited to 'ipa-server')
32 files changed, 4131 insertions, 0 deletions
diff --git a/ipa-server/Makefile b/ipa-server/Makefile new file mode 100644 index 000000000..dd3fa71ef --- /dev/null +++ b/ipa-server/Makefile @@ -0,0 +1,23 @@ +SUBDIRS=ipa-install xmlrpc-server +PYTHONDIR=$(DESTDIR)/usr/share/ipa/ipaserver + +all: + @for subdir in $(SUBDIRS); do \ + (cd $$subdir && $(MAKE) $@) || exit 1; \ + done + +install-ipaserver: + -mkdir -p $(PYTHONDIR) + install -m 644 ipaserver/*.py $(PYTHONDIR) + +install: install-ipaserver + @for subdir in $(SUBDIRS); do \ + (cd $$subdir && $(MAKE) $@) || exit 1; \ + done + +clean: + @for subdir in $(SUBDIRS); do \ + (cd $$subdir && $(MAKE) $@) || exit 1; \ + done + rm -f *~ + rm -f ipaserver/*~ diff --git a/ipa-server/freeipa-server.spec b/ipa-server/freeipa-server.spec new file mode 100755 index 000000000..4801eb7fe --- /dev/null +++ b/ipa-server/freeipa-server.spec @@ -0,0 +1,50 @@ +Name: freeipa-server +Version: 0.1.0 +Release: 1%{?dist} +Summary: FreeIPA authentication server + +Group: System Environment/Base +License: GPL +URL: http://www.freeipa.org +Source0: %{name}-%{version}.tgz +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) +BuildArch: noarch + +Requires: python fedora-ds-base krb5-server krb5-server-ldap nss-tools openldap-clients httpd mod_python python-ldap freeipa-python + +%define httpd_conf /etc/httpd/conf.d + +%description +FreeIPA is a server for identity, policy, and audit. + +%prep +%setup -q + +%install +rm -rf %{buildroot} +mkdir -p %{buildroot}%{_sbindir} +mkdir -p %{buildroot}%{httpd_conf} + +make install DESTDIR=%{buildroot} + + +%clean +rm -rf %{buildroot} + + +%files +%defattr(-,root,root,-) +%{_sbindir}/ipa-server-install +%{_sbindir}/ipa-server-setupssl + +%dir %{_usr}/share/ipa +%{_usr}/share/ipa/* + +%{httpd_conf}/ipa.conf + + +%changelog +* Fri Jul 27 2007 Karl MacMillan <kmacmill@localhost.localdomain> - 0.1.0-1 +- Initial rpm version + + diff --git a/ipa-server/freeipa-server.spec.in b/ipa-server/freeipa-server.spec.in new file mode 100644 index 000000000..16aff06b7 --- /dev/null +++ b/ipa-server/freeipa-server.spec.in @@ -0,0 +1,50 @@ +Name: freeipa-server +Version: VERSION +Release: 1%{?dist} +Summary: FreeIPA authentication server + +Group: System Environment/Base +License: GPL +URL: http://www.freeipa.org +Source0: %{name}-%{version}.tgz +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) +BuildArch: noarch + +Requires: python fedora-ds-base krb5-server krb5-server-ldap nss-tools openldap-clients httpd mod_python python-ldap freeipa-python + +%define httpd_conf /etc/httpd/conf.d + +%description +FreeIPA is a server for identity, policy, and audit. + +%prep +%setup -q + +%install +rm -rf %{buildroot} +mkdir -p %{buildroot}%{_sbindir} +mkdir -p %{buildroot}%{httpd_conf} + +make install DESTDIR=%{buildroot} + + +%clean +rm -rf %{buildroot} + + +%files +%defattr(-,root,root,-) +%{_sbindir}/ipa-server-install +%{_sbindir}/ipa-server-setupssl + +%dir %{_usr}/share/ipa +%{_usr}/share/ipa/* + +%{httpd_conf}/ipa.conf + + +%changelog +* Fri Jul 27 2007 Karl MacMillan <kmacmill@localhost.localdomain> - 0.1.0-1 +- Initial rpm version + + diff --git a/ipa-server/ipa-install/Makefile b/ipa-server/ipa-install/Makefile new file mode 100644 index 000000000..0d4953976 --- /dev/null +++ b/ipa-server/ipa-install/Makefile @@ -0,0 +1,12 @@ +SBINDIR=$(DESTDIR)/usr/sbin + +all: ; + +install: + install -m 755 ipa-server-install $(SBINDIR) + install -m 755 ipa-server-setupssl $(SBINDIR) + $(MAKE) -C share $@ + +clean: + $(MAKE) -C share $@ + rm -f *~ *.pyc
\ No newline at end of file diff --git a/ipa-server/ipa-install/README b/ipa-server/ipa-install/README new file mode 100644 index 000000000..2e1dd0d46 --- /dev/null +++ b/ipa-server/ipa-install/README @@ -0,0 +1,23 @@ + +Required packages: + +krb5-server +fedora-ds-base +openldap-clients +krb5-server-ldap +cyrus-sasl-gssapi +httpd +mod_auth_kerb + + +Installation example: + +TEMPORARY: (until fedora ds scripts are fixed) +please use the fedora-ds.init.patch under share/ to patch your init scripts before +running ipa-server-install + +cd ipa-install +make install +cd .. +/usr/sbin/ipa-server-install -u fds -r FREEIPA.ORG -p freeipa -m ipafree + diff --git a/ipa-server/ipa-install/freeipa-setup-20070713.patch b/ipa-server/ipa-install/freeipa-setup-20070713.patch new file mode 100644 index 000000000..5a36eee03 --- /dev/null +++ b/ipa-server/ipa-install/freeipa-setup-20070713.patch @@ -0,0 +1,288 @@ +diff -r 5ebd8adc48b8 ipa-install/README +--- a/ipa-install/README Mon Jul 02 15:51:04 2007 -0400 ++++ b/ipa-install/README Fri Jul 13 16:25:05 2007 -0400 +@@ -5,12 +5,17 @@ fedora-ds-base + fedora-ds-base + openldap-clients + krb5-server-ldap ++cyrus-sasl-gssapi + + + Installation example: ++ ++TEMPORARY: (until fedora ds scripts are fixed) ++please use the fedora-ds.init.patch under share/ to patch your init scripts before ++running ipa-server-install + + cd ipa-install + make install + cd .. +-/usr/sbin/ipa-server-install -r FREEIPA.ORG -a rc1.freeipa.org -p freeipa -m ipafree ++/usr/sbin/ipa-server-install -u fds -r FREEIPA.ORG -p freeipa -m ipafree + +diff -r 5ebd8adc48b8 ipa-install/share/bind.zone.db.template +--- /dev/null Thu Jan 01 00:00:00 1970 +0000 ++++ b/ipa-install/share/bind.zone.db.template Fri Jul 13 16:22:12 2007 -0400 +@@ -0,0 +1,26 @@ ++$$ORIGIN $DOMAIN. ++$$TTL 86400 ++@ IN SOA $DOMAIN. root.$DOMAIN. ( ++ 01 ; serial (d. adams) ++ 3H ; refresh ++ 15M ; retry ++ 1W ; expiry ++ 1D ) ; minimum ++ ++ IN NS $HOST ++$HOST IN A $IP ++; ++; ldap servers ++_ldap._tcp IN SRV 0 100 389 $HOST ++ ++;kerberos realm ++_kerberos IN TXT $REALM ++ ++; kerberos servers ++_kerberos._tcp IN SRV 0 100 88 $HOST ++_kerberos._udp IN SRV 0 100 88 $HOST ++_kerberos-master._tcp IN SRV 0 100 88 $HOST ++_kerberos-master._udp IN SRV 0 100 88 $HOST ++_kpasswd._tcp IN SRV 0 100 88 $HOST ++_kpasswd._udp IN SRV 0 100 88 $HOST ++ +diff -r 5ebd8adc48b8 ipa-install/share/fedora-ds.init.patch +--- /dev/null Thu Jan 01 00:00:00 1970 +0000 ++++ b/ipa-install/share/fedora-ds.init.patch Fri Jul 13 14:45:53 2007 -0400 +@@ -0,0 +1,12 @@ ++--- /etc/init.d/fedora-ds.orig 2007-07-06 18:21:30.000000000 -0400 +++++ /etc/init.d/fedora-ds 2007-05-18 19:36:24.000000000 -0400 ++@@ -10,6 +10,9 @@ ++ # datadir: /var/lib/fedora-ds/slapd-<instance name> ++ # ++ +++# Get config. +++[ -r /etc/sysconfig/fedora-ds ] && . /etc/sysconfig/fedora-ds +++ ++ # Source function library. ++ if [ -f /etc/rc.d/init.d/functions ] ; then ++ . /etc/rc.d/init.d/functions +diff -r 5ebd8adc48b8 ipa-install/share/krb5.conf.template +--- a/ipa-install/share/krb5.conf.template Mon Jul 02 15:51:04 2007 -0400 ++++ b/ipa-install/share/krb5.conf.template Fri Jul 13 11:01:36 2007 -0400 +@@ -9,6 +9,13 @@ + dns_lookup_kdc = true + ticket_lifetime = 24h + forwardable = yes ++ ++[realms] ++ $REALM = { ++ kdc = $FQDN:88 ++ admin_server = $FQDN:749 ++ default_domain = $DOMAIN ++} + + [domain_realm] + .$DOMAIN = $REALM +@@ -29,7 +36,7 @@ + ldap_servers = ldap://127.0.0.1/ + ldap_kerberos_container_dn = cn=kerberos,$SUFFIX + ldap_kdc_dn = uid=kdc,cn=kerberos,$SUFFIX +-; ldap_kadmind_dn = cn=Directory Manager ++ ldap_kadmind_dn = uid=kdc,cn=kerberos,$SUFFIX + ldap_service_password_file = /var/kerberos/krb5kdc/ldappwd + } + +diff -r 5ebd8adc48b8 ipa-install/src/ipa-server-install +--- a/ipa-install/src/ipa-server-install Mon Jul 02 15:51:04 2007 -0400 ++++ b/ipa-install/src/ipa-server-install Fri Jul 13 19:43:13 2007 -0400 +@@ -26,6 +26,7 @@ + + VERSION = "%prog .1" + ++import socket + import logging + from optparse import OptionParser + import ipa.dsinstance +@@ -37,8 +38,6 @@ def parse_options(): + help="ds user") + parser.add_option("-r", "--realm", dest="realm_name", + help="realm name") +- parser.add_option("-a", "--host-address", dest="host_name", +- help="host address (name or IP address)") + parser.add_option("-p", "--password", dest="password", + help="admin password") + parser.add_option("-m", "--master-password", dest="master_password", +@@ -46,8 +45,8 @@ def parse_options(): + + options, args = parser.parse_args() + +- if not options.realm_name or not options.host_name or not options.password: +- parser.error("error: password, realm, and host name required") ++ if not options.ds_user or not options.realm_name or not options.password or not options.master_password: ++ parser.error("error: all options are required") + + return options + +@@ -56,13 +55,35 @@ def main(): + format='%(asctime)s %(levelname)s %(message)s', + filename='ipa-install.log', + filemode='w') ++ + options = parse_options() ++ ++ # check the hostname is correctly configured, it must be as the kldap ++ # utilities just use the hostname as returned by gethostbyname to set ++ # up some of the standard entries ++ ++ host_name = socket.gethostname() ++ if len(host_name.split(".")) < 2: ++ print "Invalid hostname <"+host_name+">" ++ print "Check the /etc/hosts file and make sure to have a valid FQDN" ++ return "-Fatal Error-" ++ ++ if socket.gethostbyname(host_name) == "127.0.0.1": ++ print "The hostname resolves to the localhost address (127.0.0.1)" ++ print "Please change your /etc/hosts file or your DNS so that the" ++ print "hostname resolves to the ip address of your network interface." ++ print "The KDC service does not listen on 127.0.0.1" ++ return "-Fatal Error-" ++ ++ print "The Final KDC Host Name will be: " + host_name ++ + ds = ipa.dsinstance.DsInstance() +- ds.create_instance(options.ds_user, options.realm_name, options.host_name, options.password) ++ ds.create_instance(options.ds_user, options.realm_name, host_name, options.password) + + krb = ipa.krbinstance.KrbInstance() +- krb.create_instance(options.ds_user, options.realm_name, options.host_name, options.password, options.master_password) +- #restart ds after the krb instance have add the sasl map ++ krb.create_instance(options.ds_user, options.realm_name, host_name, options.password, options.master_password) ++ ++ #restart ds after the krb instance have add the sasl map and the ldap keytab + ds.restart() + + return 0 +diff -r 5ebd8adc48b8 ipa-install/src/ipa/krbinstance.py +--- a/ipa-install/src/ipa/krbinstance.py Mon Jul 02 15:51:04 2007 -0400 ++++ b/ipa-install/src/ipa/krbinstance.py Fri Jul 13 19:20:41 2007 -0400 +@@ -25,6 +25,9 @@ import logging + import logging + from random import Random + from time import gmtime ++import os ++import pwd ++import socket + + SHARE_DIR = "/usr/share/ipa/" + +@@ -32,6 +35,10 @@ def realm_to_suffix(realm_name): + s = realm_name.split(".") + terms = ["dc=" + x.lower() for x in s] + return ",".join(terms) ++ ++def host_to_domain(fqdn): ++ s = fqdn.split(".") ++ return ".".join(s[1:]) + + def generate_kdc_password(): + rndpwd = '' +@@ -75,8 +82,10 @@ class KrbInstance: + class KrbInstance: + def __init__(self): + self.ds_user = None +- self.realm_name = None +- self.host_name = None ++ self.fqdn = None ++ self.realm = None ++ self.domain = None ++ self.host = None + self.admin_password = None + self.master_password = None + self.suffix = None +@@ -85,12 +94,15 @@ class KrbInstance: + + def create_instance(self, ds_user, realm_name, host_name, admin_password, master_password): + self.ds_user = ds_user +- self.realm_name = realm_name.upper() +- self.host_name = host_name ++ self.fqdn = host_name ++ self.ip = socket.gethostbyname(host_name) ++ self.realm = realm_name.upper() ++ self.host = host_name.split(".")[0] ++ self.domain = host_to_domain(host_name) + self.admin_password = admin_password + self.master_password = master_password + +- self.suffix = realm_to_suffix(self.realm_name) ++ self.suffix = realm_to_suffix(self.realm) + self.kdc_password = generate_kdc_password() + self.__configure_kdc_account_password() + +@@ -99,6 +111,10 @@ class KrbInstance: + self.__configure_ldap() + + self.__create_instance() ++ ++ self.__create_ds_keytab() ++ ++ self.__create_sample_bind_zone() + + self.start() + +@@ -120,12 +136,13 @@ class KrbInstance: + pwd_fd.close() + + def __setup_sub_dict(self): +- #FIXME: can DOMAIN be different than REALM ? +- self.sub_dict = dict(FQHN=self.host_name, ++ self.sub_dict = dict(FQDN=self.fqdn, ++ IP=self.ip, + PASSWORD=self.kdc_password, + SUFFIX=self.suffix, +- DOMAIN= self.realm_name.lower(), +- REALM=self.realm_name) ++ DOMAIN=self.domain, ++ HOST=self.host, ++ REALM=self.realm) + + def __configure_ldap(self): + +@@ -153,7 +170,7 @@ class KrbInstance: + krb5_fd.close() + + #populate the directory with the realm structure +- args = ["/usr/kerberos/sbin/kdb5_ldap_util", "-D", "uid=kdc,cn=kerberos,"+self.suffix, "-w", self.kdc_password, "create", "-s", "-r", self.realm_name, "-subtrees", self.suffix, "-sscope", "sub"] ++ args = ["/usr/kerberos/sbin/kdb5_ldap_util", "-D", "uid=kdc,cn=kerberos,"+self.suffix, "-w", self.kdc_password, "create", "-s", "-P", self.master_password, "-r", self.realm, "-subtrees", self.suffix, "-sscope", "sub"] + run(args) + + # TODO: NOT called yet, need to find out how to make sure the plugin is available first +@@ -165,5 +182,28 @@ class KrbInstance: + extop_fd.close() + + #add an ACL to let the DS user read the master key +- args = ["/usr/bin/setfacl", "-m", "u:"+self.ds_user+":r", "/var/kerberos/krb5kdc/.k5."+self.realm_name] ++ args = ["/usr/bin/setfacl", "-m", "u:"+self.ds_user+":r", "/var/kerberos/krb5kdc/.k5."+self.realm] + run(args) ++ ++ def __create_sample_bind_zone(self): ++ bind_txt = template_file(SHARE_DIR + "bind.zone.db.template", self.sub_dict) ++ [bind_fd, bind_name] = tempfile.mkstemp(".db","sammple.zone.") ++ os.write(bind_fd, bind_txt) ++ os.close(bind_fd) ++ print "Sample zone file for bind has been created in "+bind_name ++ ++ def __create_ds_keytab(self): ++ (kwrite, kread, kerr) = os.popen3("/usr/kerberos/sbin/kadmin.local") ++ kwrite.write("addprinc -randkey ldap/"+self.fqdn+"@"+self.realm+"\n") ++ kwrite.flush() ++ kwrite.write("ktadd -k /etc/fedora-ds/ds.keytab ldap/"+self.fqdn+"@"+self.realm+"\n") ++ kwrite.flush() ++ kwrite.close() ++ kread.close() ++ kerr.close() ++ ++ cfg_fd = open("/etc/sysconfig/fedora-ds", "a") ++ cfg_fd.write("export KRB5_KTNAME=/etc/fedora-ds/ds.keytab\n") ++ cfg_fd.close() ++ pent = pwd.getpwnam(self.ds_user) ++ os.chown("/etc/sysconfig/fedora-ds", pent.pw_uid, pent.pw_gid) diff --git a/ipa-server/ipa-install/ipa-server-install b/ipa-server/ipa-install/ipa-server-install new file mode 100644 index 000000000..7abcafd8f --- /dev/null +++ b/ipa-server/ipa-install/ipa-server-install @@ -0,0 +1,124 @@ +#! /usr/bin/python -E +# Authors: Karl MacMillan <kmacmillan@mentalrootkit.com> +# +# Copyright (C) 2007 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; version 2 only +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + + +# requires the following packages: +# fedora-ds-base +# openldap-clients +# nss-tools + +VERSION = "%prog .1" + +import sys +sys.path.append("/usr/share/ipa") + +import socket +import logging +from optparse import OptionParser +import ipaserver.dsinstance +import ipaserver.krbinstance +from ipaserver.util import run + +def parse_options(): + parser = OptionParser(version=VERSION) + parser.add_option("-u", "--user", dest="ds_user", + help="ds user") + parser.add_option("-r", "--realm", dest="realm_name", + help="realm name") + parser.add_option("-p", "--password", dest="password", + help="admin password") + parser.add_option("-m", "--master-password", dest="master_password", + help="kerberos master password") + parser.add_option("-d", "--debug", dest="debug", action="store_true", + dest="debug", default=False, help="print debugging information") + parser.add_option("--hostname", dest="host_name", help="fully qualified name of server") + + options, args = parser.parse_args() + + if not options.ds_user or not options.realm_name or not options.password or not options.master_password: + parser.error("error: all options are required") + + return options + +def logging_setup(options): + # Always log everything (i.e., DEBUG) to the log + # file. + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(levelname)s %(message)s', + filename='ipaserver-install.log', + filemode='w') + + console = logging.StreamHandler() + # If the debug option is set, also log debug messages to the console + if options.debug: + console.setLevel(logging.DEBUG) + else: + # Otherwise, log critical and error messages + console.setLevel(logging.ERROR) + formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') + console.setFormatter(formatter) + logging.getLogger('').addHandler(console) + +def main(): + options = parse_options() + logging_setup(options) + + # check the hostname is correctly configured, it must be as the kldap + # utilities just use the hostname as returned by gethostbyname to set + # up some of the standard entries + + if options.host_name: + host_name = options.host_name + else: + host_name = socket.gethostname() + if len(host_name.split(".")) < 2: + print "Invalid hostname <"+host_name+">" + print "Check the /etc/hosts file and make sure to have a valid FQDN" + return "-Fatal Error-" + + if socket.gethostbyname(host_name) == "127.0.0.1": + print "The hostname resolves to the localhost address (127.0.0.1)" + print "Please change your /etc/hosts file or your DNS so that the" + print "hostname resolves to the ip address of your network interface." + print "The KDC service does not listen on 127.0.0.1" + return "-Fatal Error-" + + print "The Final KDC Host Name will be: " + host_name + + + # Create a directory server instance + ds = ipaserver.dsinstance.DsInstance() + ds.create_instance(options.ds_user, options.realm_name, host_name, + options.password) + + # Create a kerberos instance + krb = ipaserver.krbinstance.KrbInstance() + krb.create_instance(options.ds_user, options.realm_name, host_name, + options.password, options.master_password) + + # Restart ds after the krb instance have add the sasl map + ds.restart() + + # Restart apache + run(["/sbin/service", "httpd", "restart"]) + + return 0 + +main() diff --git a/ipa-server/ipa-install/ipa-server-setupssl b/ipa-server/ipa-install/ipa-server-setupssl new file mode 100644 index 000000000..f75327907 --- /dev/null +++ b/ipa-server/ipa-install/ipa-server-setupssl @@ -0,0 +1,228 @@ +#!/bin/sh + +if [ "$1" ] ; then + password=$1 +else + echo "password required" + exit 1 +fi + +if [ "$2" -a -d "$2" ] ; then + secdir="$2" +else + secdir=/etc/fedora-ds/slapd-localhost +fi + +if [ "$3" ] ; then + myhost=$3 +else + myhost=`hostname --fqdn` +fi + + +if [ "$4" ] ; then + ldapport=$4 +else + ldapport=389 +fi + +me=`whoami` +if [ "$me" = "root" ] ; then + isroot=1 +fi + +# see if there are already certs and keys +if [ -f $secdir/cert8.db ] ; then + # look for CA cert + if certutil -L -d $secdir -n "CA certificate" 2> /dev/null ; then + echo "Using existing CA certificate" + else + echo "No CA certificate found - will create new one" + needCA=1 + fi + + # look for server cert + if certutil -L -d $secdir -n "Server-Cert" 2> /dev/null ; then + echo "Using existing directory Server-Cert" + else + echo "No Server Cert found - will create new one" + needServerCert=1 + fi + + # look for admin server cert + if certutil -L -d $secdir -n "server-cert" 2> /dev/null ; then + echo "Using existing admin server-cert" + else + echo "No Admin Server Cert found - will create new one" + needASCert=1 + fi + prefix="new-" + prefixarg="-P $prefix" +else + needCA=1 + needServerCert=1 + needASCert=1 +fi + +if test -z "$needCA" -a -z "$needServerCert" -a -z "$needASCert" ; then + echo "No certs needed - exiting" + exit 0 +fi + +# get our user and group +if test -n "$isroot" ; then + uid=`/bin/ls -ald $secdir | awk '{print $3}'` + gid=`/bin/ls -ald $secdir | awk '{print $4}'` +fi + +# 2. Create a password file for your security token password: +if [ -f $secdir/pwdfile.txt ] ; then + echo "Using existing $secdir/pwdfile.txt" +else + (ps -ef ; w ) | sha1sum | awk '{print $1}' > $secdir/pwdfile.txt + if test -n "$isroot" ; then + chown $uid:$gid $secdir/pwdfile.txt + fi + chmod 400 $secdir/pwdfile.txt +fi + +# 3. Create a "noise" file for your encryption mechanism: +if [ -f $secdir/noise.txt ] ; then + echo "Using existing $secdir/noise.txt file" +else + (w ; ps -ef ; date ) | sha1sum | awk '{print $1}' > $secdir/noise.txt + if test -n "$isroot" ; then + chown $uid:$gid $secdir/noise.txt + fi + chmod 400 $secdir/noise.txt +fi + +# 4. Create the key3.db and cert8.db databases: +certutil -N $prefixarg -d $secdir -f $secdir/pwdfile.txt +if test -n "$isroot" ; then + chown $uid:$gid $secdir/${prefix}key3.db $secdir/${prefix}cert8.db +fi +chmod 600 $secdir/${prefix}key3.db $secdir/${prefix}cert8.db + + +if test -n "$needCA" ; then +# 5. Generate the encryption key: + certutil -G $prefixarg -d $secdir -z $secdir/noise.txt -f $secdir/pwdfile.txt +# 6. Generate the self-signed certificate: + certutil -S $prefixarg -n "CA certificate" -s "cn=CAcert" -x -t "CT,," -m 1000 -v 120 -d $secdir -z $secdir/noise.txt -f $secdir/pwdfile.txt +# export the CA cert for use with other apps + certutil -L $prefixarg -d $secdir -n "CA certificate" -a > $secdir/cacert.asc + pk12util -d $secdir $prefixarg -o $secdir/cacert.p12 -n "CA certificate" -w $secdir/pwdfile.txt -k $secdir/pwdfile.txt +fi + +if test -n "$needServerCert" ; then +# 7. Generate the server certificate: + certutil -S $prefixarg -n "Server-Cert" -s "cn=$myhost,ou=Fedora Directory Server" -c "CA certificate" -t "u,u,u" -m 1001 -v 120 -d $secdir -z $secdir/noise.txt -f $secdir/pwdfile.txt +fi + +if test -n "$needASCert" ; then +# Generate the admin server certificate + certutil -S $prefixarg -n "server-cert" -s "cn=$myhost,ou=Fedora Administration Server" -c "CA certificate" -t "u,u,u" -m 1002 -v 120 -d $secdir -z $secdir/noise.txt -f $secdir/pwdfile.txt + +# export the admin server certificate/private key for import into its key/cert db + pk12util -d $secdir $prefixarg -o $secdir/adminserver.p12 -n server-cert -w $secdir/pwdfile.txt -k $secdir/pwdfile.txt + if test -n "$isroot" ; then + chown $uid:$gid $secdir/adminserver.p12 + fi + chmod 400 $secdir/adminserver.p12 +fi + +# create the pin file +if [ ! -f $secdir/pin.txt ] ; then + pinfile=$secdir/pin.txt + echo 'Internal (Software) Token:'`cat $secdir/pwdfile.txt` > $pinfile + if test -n "$isroot" ; then + chown $uid:$gid $pinfile + fi + chmod 400 $pinfile +else + echo Using existing $secdir/pin.txt +fi + +if [ -n "$prefix" ] ; then + # move the old files out of the way + mv $secdir/cert8.db $secdir/orig-cert8.db + mv $secdir/key3.db $secdir/orig-key3.db + # move in the new files - will be used after server restart + mv $secdir/${prefix}cert8.db $secdir/cert8.db + mv $secdir/${prefix}key3.db $secdir/key3.db +fi + +# create the admin server key/cert db +asprefix=admin-serv- +if [ ! -f ${asprefix}cert8.db ] ; then + certutil -N -d $secdir -P $asprefix -f $secdir/pwdfile.txt + if test -n "$isroot" ; then + chown $uid:$gid $secdir/admin-serv-*.db + fi + chmod 600 $secdir/admin-serv-*.db +fi + +if test -n "$needASCert" ; then +# import the admin server key/cert + pk12util -d $secdir -P $asprefix -n server-cert -i $secdir/adminserver.p12 -w $secdir/pwdfile.txt -k $secdir/pwdfile.txt + +# import the CA cert to the admin server cert db + certutil -A -d $secdir -P $asprefix -n "CA certificate" -t "CT,," -a -i $secdir/cacert.asc +fi + +if [ ! -f $secdir/password.conf ] ; then +# create the admin server password file + echo 'internal:'`cat $secdir/pwdfile.txt` > $secdir/password.conf + if test -n "$isroot" ; then + chown $uid:$gid $secdir/password.conf + fi + chmod 400 $secdir/password.conf +fi + +# tell admin server to use the password file +if [ -f ../admin-serv/config/nss.conf ] ; then + sed -e "s@^NSSPassPhraseDialog .*@NSSPassPhraseDialog file:`pwd`/password.conf@" ../admin-serv/config/nss.conf > /tmp/nss.conf && mv /tmp/nss.conf ../admin-serv/config/nss.conf + if test -n "$isroot" ; then + chown $uid:$gid ../admin-serv/config/nss.conf + fi + chmod 400 ../admin-serv/config/nss.conf +fi + +# enable SSL in the directory server + +ldapmodify -x -h localhost -p $ldapport -D "cn=Directory Manager" -w $password <<EOF +dn: cn=encryption,cn=config +changetype: modify +replace: nsSSL3 +nsSSL3: on +- +replace: nsSSLClientAuth +nsSSLClientAuth: allowed +- +add: nsSSL3Ciphers +nsSSL3Ciphers: -rsa_null_md5,+rsa_rc4_128_md5,+rsa_rc4_40_md5,+rsa_rc2_40_md5, + +rsa_des_sha,+rsa_fips_des_sha,+rsa_3des_sha,+rsa_fips_3des_sha,+fortezza, + +fortezza_rc4_128_sha,+fortezza_null,+tls_rsa_export1024_with_rc4_56_sha, + +tls_rsa_export1024_with_des_cbc_sha + +dn: cn=config +changetype: modify +add: nsslapd-security +nsslapd-security: on +- +replace: nsslapd-ssl-check-hostname +nsslapd-ssl-check-hostname: off + +dn: cn=RSA,cn=encryption,cn=config +changetype: add +objectclass: top +objectclass: nsEncryptionModule +cn: RSA +nsSSLPersonalitySSL: Server-Cert +nsSSLToken: internal (software) +nsSSLActivation: on + +EOF + + diff --git a/ipa-server/ipa-install/share/60kerberos.ldif b/ipa-server/ipa-install/share/60kerberos.ldif new file mode 100644 index 000000000..3431d22e3 --- /dev/null +++ b/ipa-server/ipa-install/share/60kerberos.ldif @@ -0,0 +1,283 @@ +dn: cn=schema +# Novell Kerberos Schema Definitions +# Novell Inc. +# 1800 South Novell Place +# Provo, UT 84606 +# +# VeRsIoN=1.0 +# CoPyRiGhT=(c) Copyright 2006, Novell, Inc. All rights reserved +# +# OIDs: +# joint-iso-ccitt(2) +# country(16) +# us(840) +# organization(1) +# Novell(113719) +# applications(1) +# kerberos(301) +# Kerberos Attribute Type(4) attr# version# +# specific attribute definitions +# Kerberos Attribute Syntax(5) +# specific syntax definitions +# Kerberos Object Class(6) class# version# +# specific class definitions +######################################################################## +######################################################################## +# Attribute Type Definitions # +######################################################################## +##### This is the principal name in the RFC 1964 specified format +attributetypes: ( 2.16.840.1.113719.1.301.4.1.1 NAME 'krbPrincipalName' EQUALITY caseExactIA5Match SUBSTR caseExactSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26) +##### This specifies the type of the principal, the types could be any of +##### the types mentioned in section 6.2 of RFC 4120 +attributetypes: ( 2.16.840.1.113719.1.301.4.3.1 NAME 'krbPrincipalType' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### This flag is used to find whether directory User Password has to be used +##### as kerberos password. +##### TRUE, if User Password is to be used as the kerberos password. +##### FALSE, if User Password and the kerberos password are different. +attributetypes: ( 2.16.840.1.113719.1.301.4.5.1 NAME 'krbUPEnabled' DESC 'Boolean' SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE) +##### The time at which the principal expires +attributetypes: ( 2.16.840.1.113719.1.301.4.6.1 NAME 'krbPrincipalExpiration' EQUALITY generalizedTimeMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE) +##### The krbTicketFlags attribute holds information about the kerberos flags for a principal +##### The values (0x00000001 - 0x00800000) are reserved for standards and +##### values (0x01000000 - 0x80000000) can be used for proprietary extensions. +##### The flags and values as per RFC 4120 and MIT implementation are, +##### DISALLOW_POSTDATED 0x00000001 +##### DISALLOW_FORWARDABLE 0x00000002 +##### DISALLOW_TGT_BASED 0x00000004 +##### DISALLOW_RENEWABLE 0x00000008 +##### DISALLOW_PROXIABLE 0x00000010 +##### DISALLOW_DUP_SKEY 0x00000020 +##### DISALLOW_ALL_TIX 0x00000040 +##### REQUIRES_PRE_AUTH 0x00000080 +##### REQUIRES_HW_AUTH 0x00000100 +##### REQUIRES_PWCHANGE 0x00000200 +##### DISALLOW_SVR 0x00001000 +##### PWCHANGE_SERVICE 0x00002000 +attributetypes: ( 2.16.840.1.113719.1.301.4.8.1 NAME 'krbTicketFlags' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### The maximum ticket lifetime for a principal in seconds +attributetypes: ( 2.16.840.1.113719.1.301.4.9.1 NAME 'krbMaxTicketLife' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### Maximum renewable lifetime for a principal's ticket in seconds +attributetypes: ( 2.16.840.1.113719.1.301.4.10.1 NAME 'krbMaxRenewableAge' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### Forward reference to the Realm object. +##### (FDN of the krbRealmContainer object). +##### Example: cn=ACME.COM, cn=Kerberos, cn=Security +attributetypes: ( 2.16.840.1.113719.1.301.4.14.1 NAME 'krbRealmReferences' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +##### List of LDAP servers that kerberos servers can contact. +##### The attribute holds data in the ldap uri format, +##### Example: ldaps://acme.com:636 +##### +##### The values of this attribute need to be updated, when +##### the LDAP servers listed here are renamed, moved or deleted. +attributetypes: ( 2.16.840.1.113719.1.301.4.15.1 NAME 'krbLdapServers' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15) +##### A set of forward references to the KDC Service objects. +##### (FDNs of the krbKdcService objects). +##### Example: cn=kdc - server 1, ou=uvw, o=xyz +attributetypes: ( 2.16.840.1.113719.1.301.4.17.1 NAME 'krbKdcServers' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +##### A set of forward references to the Password Service objects. +##### (FDNs of the krbPwdService objects). +##### Example: cn=kpasswdd - server 1, ou=uvw, o=xyz +attributetypes: ( 2.16.840.1.113719.1.301.4.18.1 NAME 'krbPwdServers' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +##### This attribute holds the Host Name or the ip address, +##### transport protocol and ports of the kerberos service host +##### The format is host_name-or-ip_address#protocol#port +##### Protocol can be 0 or 1. 0 is for UDP. 1 is for TCP. +attributetypes: ( 2.16.840.1.113719.1.301.4.24.1 NAME 'krbHostServer' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26) +##### This attribute holds the scope for searching the principals +##### under krbSubTree attribute of krbRealmContainer +##### The value can either be 1 (ONE) or 2 (SUB_TREE). +attributetypes: ( 2.16.840.1.113719.1.301.4.25.1 NAME 'krbSearchScope' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### FDNs pointing to Kerberos principals +attributetypes: ( 2.16.840.1.113719.1.301.4.26.1 NAME 'krbPrincipalReferences' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +##### This attribute specifies which attribute of the user objects +##### be used as the principal name component for Kerberos. +##### The allowed values are cn, sn, uid, givenname, fullname. +attributetypes: ( 2.16.840.1.113719.1.301.4.28.1 NAME 'krbPrincNamingAttr' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE) +##### A set of forward references to the Administration Service objects. +##### (FDNs of the krbAdmService objects). +##### Example: cn=kadmindd - server 1, ou=uvw, o=xyz +attributetypes: ( 2.16.840.1.113719.1.301.4.29.1 NAME 'krbAdmServers' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +##### Maximum lifetime of a principal's password +attributetypes: ( 2.16.840.1.113719.1.301.4.30.1 NAME 'krbMaxPwdLife' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### Minimum lifetime of a principal's password +attributetypes: ( 2.16.840.1.113719.1.301.4.31.1 NAME 'krbMinPwdLife' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### Minimum number of character clases allowed in a password +attributetypes: ( 2.16.840.1.113719.1.301.4.32.1 NAME 'krbPwdMinDiffChars' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### Minimum length of the password +attributetypes: ( 2.16.840.1.113719.1.301.4.33.1 NAME 'krbPwdMinLength' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### Number of previous versions of passwords that are stored +attributetypes: ( 2.16.840.1.113719.1.301.4.34.1 NAME 'krbPwdHistoryLength' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### FDN pointing to a Kerberos Password Policy object +attributetypes: ( 2.16.840.1.113719.1.301.4.36.1 NAME 'krbPwdPolicyReference' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE) +##### The time at which the principal's password expires +attributetypes: ( 2.16.840.1.113719.1.301.4.37.1 NAME 'krbPasswordExpiration' EQUALITY generalizedTimeMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE) +##### This attribute holds the principal's key (krbPrincipalKey) that is encrypted with +##### the master key (krbMKey). +##### The attribute is ASN.1 encoded. +##### +##### The format of the value for this attribute is explained below, +##### KrbKeySet ::= SEQUENCE { +##### attribute-major-vno [0] UInt16, +##### attribute-minor-vno [1] UInt16, +##### kvno [2] UInt32, +##### mkvno [3] UInt32 OPTIONAL, +##### keys [4] SEQUENCE OF KrbKey, +##### ... +##### } +##### +##### KrbKey ::= SEQUENCE { +##### salt [0] KrbSalt OPTIONAL, +##### key [1] EncryptionKey, +##### s2kparams [2] OCTET STRING OPTIONAL, +##### ... +##### } +##### +##### KrbSalt ::= SEQUENCE { +##### type [0] Int32, +##### salt [1] OCTET STRING OPTIONAL +##### } +##### +##### EncryptionKey ::= SEQUENCE { +##### keytype [0] Int32, +##### keyvalue [1] OCTET STRING +##### } +attributetypes: ( 2.16.840.1.113719.1.301.4.39.1 NAME 'krbPrincipalKey' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40) +##### FDN pointing to a Kerberos Ticket Policy object. +attributetypes: ( 2.16.840.1.113719.1.301.4.40.1 NAME 'krbTicketPolicyReference' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE) +##### Forward reference to an entry that starts sub-trees +##### where principals and other kerberos objects in the realm are configured. +##### Example: ou=acme, ou=pq, o=xyz +attributetypes: ( 2.16.840.1.113719.1.301.4.41.1 NAME 'krbSubTrees' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +##### Holds the default encryption/salt type combinations of principals for +##### the Realm. Stores in the form of key:salt strings. +##### Example: des-cbc-crc:normal +attributetypes: ( 2.16.840.1.113719.1.301.4.42.1 NAME 'krbDefaultEncSaltTypes' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15) +##### Holds the Supported encryption/salt type combinations of principals for +##### the Realm. Stores in the form of key:salt strings. +##### The supported encryption types are mentioned in RFC 3961 +##### The supported salt types are, +##### NORMAL +##### V4 +##### NOREALM +##### ONLYREALM +##### SPECIAL +##### AFS3 +##### Example: des-cbc-crc:normal +##### +##### This attribute obsoletes the krbSupportedEncTypes and krbSupportedSaltTypes +##### attributes. +attributetypes: ( 2.16.840.1.113719.1.301.4.43.1 NAME 'krbSupportedEncSaltTypes' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15) +##### This attribute holds the principal's old keys (krbPwdHistory) that is encrypted with +##### the kadmin/history key. +##### The attribute is ASN.1 encoded. +##### +##### The format of the value for this attribute is explained below, +##### KrbKeySet ::= SEQUENCE { +##### attribute-major-vno [0] UInt16, +##### attribute-minor-vno [1] UInt16, +##### kvno [2] UInt32, +##### mkvno [3] UInt32 OPTIONAL -- actually kadmin/history key, +##### keys [4] SEQUENCE OF KrbKey, +##### ... +##### } +##### +##### KrbKey ::= SEQUENCE { +##### salt [0] KrbSalt OPTIONAL, +##### key [1] EncryptionKey, +##### s2kparams [2] OCTET STRING OPTIONAL, +##### ... +##### } +##### +##### KrbSalt ::= SEQUENCE { +##### type [0] Int32, +##### salt [1] OCTET STRING OPTIONAL +##### } +##### +##### EncryptionKey ::= SEQUENCE { +##### keytype [0] Int32, +##### keyvalue [1] OCTET STRING +##### } +attributetypes: ( 2.16.840.1.113719.1.301.4.44.1 NAME 'krbPwdHistory' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40) +##### The time at which the principal's password last password change happened. +attributetypes: ( 2.16.840.1.113719.1.301.4.45.1 NAME 'krbLastPwdChange' EQUALITY generalizedTimeMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE) +##### This attribute holds the kerberos master key. +##### This can be used to encrypt principal keys. +##### This attribute has to be secured in directory. +##### +##### This attribute is ASN.1 encoded. +##### The format of the value for this attribute is explained below, +##### KrbMKey ::= SEQUENCE { +##### kvno [0] UInt32, +##### key [1] MasterKey +##### } +##### +##### MasterKey ::= SEQUENCE { +##### keytype [0] Int32, +##### keyvalue [1] OCTET STRING +##### } +attributetypes: ( 2.16.840.1.113719.1.301.4.46.1 NAME 'krbMKey' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40) +##### This stores the alternate principal names for the principal in the RFC 1961 specified format +attributetypes: ( 2.16.840.1.113719.1.301.4.47.1 NAME 'krbPrincipalAliases' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26) +##### The time at which the principal's last successful authentication happened. +attributetypes: ( 2.16.840.1.113719.1.301.4.48.1 NAME 'krbLastSuccessfulAuth' EQUALITY generalizedTimeMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE) +##### The time at which the principal's last failed authentication happened. +attributetypes: ( 2.16.840.1.113719.1.301.4.49.1 NAME 'krbLastFailedAuth' EQUALITY generalizedTimeMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE) +##### This attribute stores the number of failed authentication attempts +##### happened for the principal since the last successful authentication. +attributetypes: ( 2.16.840.1.113719.1.301.4.50.1 NAME 'krbLoginFailedCount' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE) +##### This attribute holds the application specific data. +attributetypes: ( 2.16.840.1.113719.1.301.4.51.1 NAME 'krbExtraData' EQUALITY octetStringMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.40) +##### This attributes holds references to the set of directory objects. +##### This stores the DNs of the directory objects to which the +##### principal object belongs to. +attributetypes: ( 2.16.840.1.113719.1.301.4.52.1 NAME 'krbObjectReferences' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +##### This attribute holds references to a Container object where +##### the additional principal objects and stand alone principal +##### objects (krbPrincipal) can be created. +attributetypes: ( 2.16.840.1.113719.1.301.4.53.1 NAME 'krbPrincContainerRef' EQUALITY distinguishedNameMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.12) +######################################################################## +######################################################################## +# Object Class Definitions # +######################################################################## +#### This is a kerberos container for all the realms in a tree. +objectClasses: ( 2.16.840.1.113719.1.301.6.1.1 NAME 'krbContainer' SUP top MUST ( cn ) ) +##### The krbRealmContainer is created per realm and holds realm specific data. +objectClasses: ( 2.16.840.1.113719.1.301.6.2.1 NAME 'krbRealmContainer' SUP top MUST ( cn ) MAY ( krbMKey $ krbUPEnabled $ krbSubTrees $ krbSearchScope $ krbLdapServers $ krbSupportedEncSaltTypes $ krbDefaultEncSaltTypes $ krbTicketPolicyReference $ krbKdcServers $ krbPwdServers $ krbAdmServers $ krbPrincNamingAttr $krbPwdPolicyReference $ krbPrincContainerRef ) ) +##### An instance of a class derived from krbService is created per +##### kerberos authentication or administration server in an realm and holds +##### references to the realm objects. These references is used to further read +##### realm specific data to service AS/TGS requests. Additionally this object +##### contains some server specific data like pathnames and ports that the +##### server uses. This is the identity the kerberos server logs in with. A key +##### pair for the same is created and the kerberos server logs in with the same. +##### +##### krbKdcService, krbAdmService and krbPwdService derive from this class. +objectClasses: ( 2.16.840.1.113719.1.301.6.3.1 NAME 'krbService' ABSTRACT SUP ( top ) MUST ( cn ) MAY ( krbHostServer $ krbRealmReferences ) ) +##### Representative object for the KDC server to bind into a LDAP directory +##### and have a connection to access Kerberos data with the required +##### access rights. +objectClasses: ( 2.16.840.1.113719.1.301.6.4.1 NAME 'krbKdcService' SUP ( krbService ) ) +##### Representative object for the Kerberos Password server to bind into a LDAP directory +##### and have a connection to access Kerberos data with the required +##### access rights. +objectClasses: ( 2.16.840.1.113719.1.301.6.5.1 NAME 'krbPwdService' SUP ( krbService ) ) +###### The principal data auxiliary class. Holds principal information +###### and is used to store principal information for Person, Service objects. +objectClasses: ( 2.16.840.1.113719.1.301.6.8.1 NAME 'krbPrincipalAux' AUXILIARY MAY ( krbPrincipalName $ krbUPEnabled $ krbPrincipalKey $ krbTicketPolicyReference $ krbPrincipalExpiration $ krbPasswordExpiration $ krbPwdPolicyReference $ krbPrincipalType $ krbPwdHistory $ krbLastPwdChange $ krbPrincipalAliases $ krbLastSuccessfulAuth $ krbLastFailedAuth $ krbLoginFailedCount $ krbExtraData ) ) +###### This class is used to create additional principals and stand alone principals. +objectClasses: ( 2.16.840.1.113719.1.301.6.9.1 NAME 'krbPrincipal' SUP ( top ) MUST ( krbPrincipalName ) MAY ( krbObjectReferences ) ) +###### The principal references auxiliary class. Holds all principals referred +###### from a service +objectClasses: ( 2.16.840.1.113719.1.301.6.11.1 NAME 'krbPrincRefAux' SUP top AUXILIARY MAY krbPrincipalReferences ) +##### Representative object for the Kerberos Administration server to bind into a LDAP directory +##### and have a connection Id to access Kerberos data with the required access rights. +objectClasses: ( 2.16.840.1.113719.1.301.6.13.1 NAME 'krbAdmService' SUP ( krbService ) ) +##### The krbPwdPolicy object is a template password policy that +##### can be applied to principals when they are created. +##### These policy attributes will be in effect, when the Kerberos +##### passwords are different from users' passwords (UP). +objectClasses: ( 2.16.840.1.113719.1.301.6.14.1 NAME 'krbPwdPolicy' SUP top MUST ( cn ) MAY ( krbMaxPwdLife $ krbMinPwdLife $ krbPwdMinDiffChars $ krbPwdMinLength $ krbPwdHistoryLength ) ) +##### The krbTicketPolicyAux holds Kerberos ticket policy attributes. +##### This class can be attached to a principal object or realm object. +objectClasses: ( 2.16.840.1.113719.1.301.6.16.1 NAME 'krbTicketPolicyAux' AUXILIARY MAY ( krbTicketFlags $ krbMaxTicketLife $ krbMaxRenewableAge ) ) +##### The krbTicketPolicy object is an effective ticket policy that is associated with a realm or a principal +objectClasses: ( 2.16.840.1.113719.1.301.6.17.1 NAME 'krbTicketPolicy' SUP top MUST ( cn ) ) diff --git a/ipa-server/ipa-install/share/60samba.ldif b/ipa-server/ipa-install/share/60samba.ldif new file mode 100644 index 000000000..d3a6d31b0 --- /dev/null +++ b/ipa-server/ipa-install/share/60samba.ldif @@ -0,0 +1,152 @@ +## schema file for Fedora DS +## +## Schema for storing Samba user accounts and group maps in LDAP +## OIDs are owned by the Samba Team +## +## Prerequisite schemas - uid (cosine.schema) +## - displayName (inetorgperson.schema) +## - gidNumber (nis.schema) +## +## 1.3.6.1.4.1.7165.2.1.x - attributeTypess +## 1.3.6.1.4.1.7165.2.2.x - objectClasseses +## +## Printer support +## 1.3.6.1.4.1.7165.2.3.1.x - attributeTypess +## 1.3.6.1.4.1.7165.2.3.2.x - objectClasseses +## +## Samba4 +## 1.3.6.1.4.1.7165.4.1.x - attributeTypess +## 1.3.6.1.4.1.7165.4.2.x - objectClasseses +## 1.3.6.1.4.1.7165.4.3.x - LDB/LDAP Controls +## 1.3.6.1.4.1.7165.4.4.x - LDB/LDAP Extended Operations +## 1.3.6.1.4.1.7165.4.255.x - mapped OIDs due to conflicts between AD and standards-track +## +dn: cn=schema +## +####################################################################### +## Attributes used by Samba 3.0 schema ## +####################################################################### +## +## Password hashes## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.24 NAME 'sambaLMPassword' DESC 'LanManager Password' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{32} SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.25 NAME 'sambaNTPassword' DESC 'MD4 hash of the unicode password' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{32} SINGLE-VALUE ) +## +## Account flags in string format ([UWDX ]) +## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.26 NAME 'sambaAcctFlags' DESC 'Account Flags' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{16} SINGLE-VALUE ) +## +## Password timestamps & policies +## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.27 NAME 'sambaPwdLastSet' DESC 'Timestamp of the last password update' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.28 NAME 'sambaPwdCanChange' DESC 'Timestamp of when the user is allowed to update the password' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.29 NAME 'sambaPwdMustChange' DESC 'Timestamp of when the password will expire' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.30 NAME 'sambaLogonTime' DESC 'Timestamp of last logon' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.31 NAME 'sambaLogoffTime' DESC 'Timestamp of last logoff' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.32 NAME 'sambaKickoffTime' DESC 'Timestamp of when the user will be logged off automatically' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.48 NAME 'sambaBadPasswordCount' DESC 'Bad password attempt count' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.49 NAME 'sambaBadPasswordTime' DESC 'Time of the last bad password attempt' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.55 NAME 'sambaLogonHours' DESC 'Logon Hours' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{42} SINGLE-VALUE ) +## +## string settings +## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.33 NAME 'sambaHomeDrive' DESC 'Driver letter of home directory mapping' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{4} SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.34 NAME 'sambaLogonScript' DESC 'Logon script path' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{255} SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.35 NAME 'sambaProfilePath' DESC 'Roaming profile path' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{255} SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.36 NAME 'sambaUserWorkstations' DESC 'List of user workstations the user is allowed to logon to' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{255} SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.37 NAME 'sambaHomePath' DESC 'Home directory UNC path' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.38 NAME 'sambaDomainName' DESC 'Windows NT domain to which the user belongs' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.47 NAME 'sambaMungedDial' DESC 'Base64 encoded user parameter string' EQUALITY caseExactMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1050} ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.54 NAME 'sambaPasswordHistory' DESC 'Concatenated MD5 hashes of the salted NT passwords used on this account' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{32} ) +## +## SID, of any type +## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.20 NAME 'sambaSID' DESC 'Security ID' EQUALITY caseIgnoreIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{64} SINGLE-VALUE ) +## +## Primary group SID, compatible with ntSid +## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.23 NAME 'sambaPrimaryGroupSID' DESC 'Primary Group Security ID' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{64} SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.51 NAME 'sambaSIDList' DESC 'Security ID List' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{64} ) +## +## group mapping attributes +## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.19 NAME 'sambaGroupType' DESC 'NT Group Type' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +## +## Store info on the domain +## +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.21 NAME 'sambaNextUserRid' DESC 'Next NT rid to give our for users' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.22 NAME 'sambaNextGroupRid' DESC 'Next NT rid to give out for groups' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.39 NAME 'sambaNextRid' DESC 'Next NT rid to give out for anything' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.40 NAME 'sambaAlgorithmicRidBase' DESC 'Base at which the samba RID generation algorithm should operate' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.41 NAME 'sambaShareName' DESC 'Share Name' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.42 NAME 'sambaOptionName' DESC 'Option Name' EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.43 NAME 'sambaBoolOption' DESC 'A boolean option' EQUALITY booleanMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.44 NAME 'sambaIntegerOption' DESC 'An integer option' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.45 NAME 'sambaStringOption' DESC 'A string option' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.46 NAME 'sambaStringListOption' DESC 'A string list option' EQUALITY caseIgnoreMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 ) +##attributeTypes: ( 1.3.6.1.4.1.7165.2.1.50 NAME 'sambaPrivName' +## SUP name ) +## +##attributeTypes: ( 1.3.6.1.4.1.7165.2.1.52 NAME 'sambaPrivilegeList' +## DESC 'Privileges List' +## EQUALITY caseIgnoreIA5Match +## SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{64} ) +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.53 NAME 'sambaTrustFlags' DESC 'Trust Password Flags' EQUALITY caseIgnoreIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) +# "min password length" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.58 NAME 'sambaMinPwdLength' DESC 'Minimal password length (default: 5)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "password history" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.59 NAME 'sambaPwdHistoryLength' DESC 'Length of Password History Entries (default: 0 => off)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "user must logon to change password" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.60 NAME 'sambaLogonToChgPwd' DESC 'Force Users to logon for password change (default: 0 => off, 2 => on)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "maximum password age" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.61 NAME 'sambaMaxPwdAge' DESC 'Maximum password age, in seconds (default: -1 => never expire passwords)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "minimum password age" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.62 NAME 'sambaMinPwdAge' DESC 'Minimum password age, in seconds (default: 0 => allow immediate password change)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "lockout duration" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.63 NAME 'sambaLockoutDuration' DESC 'Lockout duration in minutes (default: 30, -1 => forever)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "reset count minutes" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.64 NAME 'sambaLockoutObservationWindow' DESC 'Reset time after lockout in minutes (default: 30)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "bad lockout attempt" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.65 NAME 'sambaLockoutThreshold' DESC 'Lockout users after bad logon attempts (default: 0 => off)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "disconnect time" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.66 NAME 'sambaForceLogoff' DESC 'Disconnect Users outside logon hours (default: -1 => off, 0 => on)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +# "refuse machine password change" +attributeTypes: ( 1.3.6.1.4.1.7165.2.1.67 NAME 'sambaRefuseMachinePwdChange' DESC 'Allow Machine Password changes (default: 0 => off)' EQUALITY integerMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE ) +## +####################################################################### +## objectClasses: used by Samba 3.0 schema ## +####################################################################### +## +## The X.500 data model (and therefore LDAPv3) says that each entry can +## only have one structural objectClasses. OpenLDAP 2.0 does not enforce +## this currently but will in v2.1 +## +## added new objectClasses: (and OID) for 3.0 to help us deal with backwards +## compatibility with 2.2 installations (e.g. ldapsam_compat) --jerry +## +objectClasses: ( 1.3.6.1.4.1.7165.2.2.6 NAME 'sambaSamAccount' SUP top AUXILIARY DESC 'Samba 3.0 Auxilary SAM Account' MUST ( uid $ sambaSID ) MAY ( cn $ sambaLMPassword $ sambaNTPassword $ sambaPwdLastSet $ sambaLogonTime $ sambaLogoffTime $ sambaKickoffTime $ sambaPwdCanChange $ sambaPwdMustChange $ sambaAcctFlags $ displayName $ sambaHomePath $ sambaHomeDrive $ sambaLogonScript $ sambaProfilePath $ description $ sambaUserWorkstations $ sambaPrimaryGroupSID $ sambaDomainName $ sambaMungedDial $ sambaBadPasswordCount $ sambaBadPasswordTime $ sambaPasswordHistory $ sambaLogonHours)) +## +## Group mapping info +## +objectClasses: ( 1.3.6.1.4.1.7165.2.2.4 NAME 'sambaGroupMapping' SUP top AUXILIARY DESC 'Samba Group Mapping' MUST ( gidNumber $ sambaSID $ sambaGroupType ) MAY ( displayName $ description $ sambaSIDList )) +## +## Trust password for trust relationships (any kind) +## +objectClasses: ( 1.3.6.1.4.1.7165.2.2.14 NAME 'sambaTrustPassword' SUP top STRUCTURAL DESC 'Samba Trust Password' MUST ( sambaDomainName $ sambaNTPassword $ sambaTrustFlags ) MAY ( sambaSID $ sambaPwdLastSet )) +## +## Whole-of-domain info +## +objectClasses: ( 1.3.6.1.4.1.7165.2.2.5 NAME 'sambaDomain' SUP top STRUCTURAL DESC 'Samba Domain Information' MUST ( sambaDomainName $ sambaSID ) MAY ( sambaNextRid $ sambaNextGroupRid $ sambaNextUserRid $ sambaAlgorithmicRidBase $ sambaMinPwdLength $ sambaPwdHistoryLength $ sambaLogonToChgPwd $ sambaMaxPwdAge $ sambaMinPwdAge $ sambaLockoutDuration $ sambaLockoutObservationWindow $ sambaLockoutThreshold $ sambaForceLogoff $ sambaRefuseMachinePwdChange )) +## +## used for idmap_ldap module +## +objectClasses: ( 1.3.6.1.4.1.7165.2.2.7 NAME 'sambaUnixIdPool' SUP top AUXILIARY DESC 'Pool for allocating UNIX uids/gids' MUST ( uidNumber $ gidNumber ) ) +objectClasses: ( 1.3.6.1.4.1.7165.2.2.8 NAME 'sambaIdmapEntry' SUP top AUXILIARY DESC 'Mapping from a SID to an ID' MUST ( sambaSID ) MAY ( uidNumber $ gidNumber ) ) +objectClasses: ( 1.3.6.1.4.1.7165.2.2.9 NAME 'sambaSidEntry' SUP top STRUCTURAL DESC 'Structural Class for a SID' MUST ( sambaSID ) ) +objectClasses: ( 1.3.6.1.4.1.7165.2.2.10 NAME 'sambaConfig' SUP top AUXILIARY DESC 'Samba Configuration Section' MAY ( description ) ) +objectClasses: ( 1.3.6.1.4.1.7165.2.2.11 NAME 'sambaShare' SUP top STRUCTURAL DESC 'Samba Share Section' MUST ( sambaShareName ) MAY ( description ) ) +objectClasses: ( 1.3.6.1.4.1.7165.2.2.12 NAME 'sambaConfigOption' SUP top STRUCTURAL DESC 'Samba Configuration Option' MUST ( sambaOptionName ) MAY ( sambaBoolOption $ sambaIntegerOption $ sambaStringOption $ sambaStringListoption $ description ) ) +## retired during privilege rewrite +##objectClasses: ( 1.3.6.1.4.1.7165.2.2.13 NAME 'sambaPrivilege' SUP top AUXILIARY +## DESC 'Samba Privilege' +## MUST ( sambaSID ) +## MAY ( sambaPrivilegeList ) ) diff --git a/ipa-server/ipa-install/share/Makefile b/ipa-server/ipa-install/share/Makefile new file mode 100644 index 000000000..380480bcf --- /dev/null +++ b/ipa-server/ipa-install/share/Makefile @@ -0,0 +1,9 @@ +SHAREDIR = $(DESTDIR)/usr/share/ipa + +install: + -mkdir -p $(SHAREDIR) + install -m 644 *.ldif $(SHAREDIR) + install -m 644 *.template $(SHAREDIR) + +clean: + rm -f *~ diff --git a/ipa-server/ipa-install/share/bootstrap-template.ldif b/ipa-server/ipa-install/share/bootstrap-template.ldif new file mode 100644 index 000000000..d83f715bb --- /dev/null +++ b/ipa-server/ipa-install/share/bootstrap-template.ldif @@ -0,0 +1,33 @@ +dn: $SUFFIX +changetype: modify +add: objectClass +objectClass: pilotObject +info: IPA V1.0 + +# default, $REALM +dn: ou=default,$SUFFIX +changetype: add +objectClass: organizationalUnit +objectClass: top +ou: default + +# users, default, $REALM +dn: ou=users,ou=default,$SUFFIX +changetype: add +objectClass: organizationalUnit +objectClass: top +ou: users + +# groups, default, $REALM +dn: ou=groups,ou=default,$SUFFIX +changetype: add +objectClass: organizationalUnit +objectClass: top +ou: groups + +# computers, default, $REALM +#dn: ou=computers,ou=default,$SUFFIX +#objectClass: organizationalUnit +#objectClass: top +#ou: computers + diff --git a/ipa-server/ipa-install/share/default-aci.ldif b/ipa-server/ipa-install/share/default-aci.ldif new file mode 100644 index 000000000..8916833c8 --- /dev/null +++ b/ipa-server/ipa-install/share/default-aci.ldif @@ -0,0 +1,10 @@ +# $SUFFIX (base entry) +dn: $SUFFIX +changetype: modify +replace: aci +aci: (targetattr!="userPassword || krbPrincipalKey ||sambaLMPassword || sambaNTPassword")(version 3.0; acl "Enable anonymous access"; allow (read, search, compare) userdn="ldap:///anyone";) +aci: (targetattr="carLicense ||description ||displayName ||facsimileTelephoneNumber ||homePhone ||homePostalAddress ||initials ||jpegPhoto ||labeledURL ||mail ||mobile ||pager ||photo ||postOfficeBox ||postalAddress ||postalCode ||preferredDeliveryMethod ||preferredLanguage ||registeredAddress ||roomNumber | |secretary ||seeAlso ||st ||street ||telephoneNumber ||telexNumber ||title || userCertificate ||userPassword ||userSMIMECertificate ||x500UniqueIdentifier")(version 3.0; acl "Enable self write for common attributes"; allow (write) userdn="ldap:///self";) +aci: (targetattr="krbPrincipalKey")(version 3.0; acl "KDC System Account"; allow (read, search, compare) userdn="ldap:///uid=kdc,cn=kerberos,$SUFFIX";) +aci: (targetattr="*")(version 3.0; acl "Directory Administrators can manage all entries"; allow(all)groupdn="ldap:///cn=Directory Administrators,$SUFFIX";) +aci: (targetattr="userPassword || krbPrincipalKey ||sambaLMPassword || sambaNTPassword")(version 3.0; acl "Kpasswd access to passowrd hashes for passowrd changes"; allow (all) userdn="ldap:///krbprincipalname=kadmin/changepw@$REALM,cn=$REALM,cn=kerberos,$SUFFIX";) + diff --git a/ipa-server/ipa-install/share/kdc.conf.template b/ipa-server/ipa-install/share/kdc.conf.template new file mode 100644 index 000000000..69e769e34 --- /dev/null +++ b/ipa-server/ipa-install/share/kdc.conf.template @@ -0,0 +1,14 @@ +[kdcdefaults] + v4_mode = nopreauth + +[realms] + $REALM = { + master_key_type = des3-hmac-sha1 + supported_enctypes = des3-hmac-sha1:normal arcfour-hmac:normal des-hmac-sha1:normal des-cbc-md5:normal des-cbc-crc:normal des-cbc-crc:v4 des-cbc-crc:afs3 + max_life = 7d + max_renewable_life = 14d + acl_file = /var/kerberos/krb5kdc/kadm5.acl + dict_file = /usr/share/dict/words + default_principal_flags = +preauth +; admin_keytab = /var/kerberos/krb5kdc/kadm5.keytab + } diff --git a/ipa-server/ipa-install/share/kerberos.ldif b/ipa-server/ipa-install/share/kerberos.ldif new file mode 100644 index 000000000..ae4564f6f --- /dev/null +++ b/ipa-server/ipa-install/share/kerberos.ldif @@ -0,0 +1,26 @@ +#kerberos base object +dn: cn=kerberos,$SUFFIX +changetype: add +objectClass: krbContainer +objectClass: top +cn: kerberos +aci: (targetattr="*")(version 3.0; acl "KDC System Account"; allow(all)userdn= "ldap:///uid=kdc,cn=kerberos,$SUFFIX";) + +#kerberos user +dn: uid=kdc,cn=kerberos,$SUFFIX +changetype: add +objectclass: account +objectclass: simplesecurityobject +uid: kdc +userPassword: $PASSWORD + +#sasl mapping +dn: cn=kerberos,cn=mapping,cn=sasl,cn=config +changetype: add +objectclass: top +objectclass: nsSaslMapping +cn: kerberos +nsSaslMapRegexString: \(.*\)@\(.*\) +nsSaslMapBaseDNTemplate: $SUFFIX +nsSaslMapFilterTemplate: (krbPrincipalName=\1@\2) + diff --git a/ipa-server/ipa-install/share/krb5.conf.template b/ipa-server/ipa-install/share/krb5.conf.template new file mode 100644 index 000000000..23a247034 --- /dev/null +++ b/ipa-server/ipa-install/share/krb5.conf.template @@ -0,0 +1,42 @@ +[logging] + default = FILE:/var/log/krb5libs.log + kdc = FILE:/var/log/krb5kdc.log + admin_server = FILE:/var/log/kadmind.log + +[libdefaults] + default_realm = $REALM + dns_lookup_realm = true + dns_lookup_kdc = true + ticket_lifetime = 24h + forwardable = yes + +[realms] + $REALM = { + kdc = $FQDN:88 + admin_server = $FQDN:749 + default_domain = $DOMAIN +} + +[domain_realm] + .$DOMAIN = $REALM + $DOMAIN = $REALM + +[appdefaults] + pam = { + debug = false + ticket_lifetime = 36000 + renew_lifetime = 36000 + forwardable = true + krb4_convert = false + } + +[dbmodules] + $REALM = { + db_library = kldap + ldap_servers = ldap://127.0.0.1/ + ldap_kerberos_container_dn = cn=kerberos,$SUFFIX + ldap_kdc_dn = uid=kdc,cn=kerberos,$SUFFIX + ldap_kadmind_dn = uid=kdc,cn=kerberos,$SUFFIX + ldap_service_password_file = /var/kerberos/krb5kdc/ldappwd + } + diff --git a/ipa-server/ipa-install/test/test-users.ldif b/ipa-server/ipa-install/test/test-users.ldif new file mode 100644 index 000000000..424eedb55 --- /dev/null +++ b/ipa-server/ipa-install/test/test-users.ldif @@ -0,0 +1,20 @@ +# test, users, default, $REALM +dn: uid=test,ou=users,ou=default,$SUFFIX +uidNumber: 1001 +uid: test +gecos: test +homeDirectory: /home/test +loginShell: /bin/bash +shadowMin: 0 +shadowWarning: 7 +shadowMax: 99999 +shadowExpire: -1 +shadowInactive: -1 +shadowLastChange: 13655 +shadowFlag: -1 +gidNumber: 100 +objectClass: posixAccount +objectClass: shadowAccount +objectClass: account +objectClass: top +cn: test diff --git a/ipa-server/ipa-slapi-plugins/README b/ipa-server/ipa-slapi-plugins/README new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/ipa-server/ipa-slapi-plugins/README diff --git a/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/Makefile b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/Makefile new file mode 100644 index 000000000..2a5646432 --- /dev/null +++ b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/Makefile @@ -0,0 +1,5 @@ +all: + gcc ipa_pwd_extop.c -I/usr/include -I/usr/include/nss3 -I/usr/include/mozldap -I/usr/include/nspr4 -I/usr/include/fedora-ds -lkrb5 -lmhash -llber -lssl -shared -g -fPIC -DPIC -Wl,-soname -Wl,libipa_pwd_extop.so -o libipa_pwd_extop.so + +install: + cp -f libipa_pwd_extop.so /usr/lib/fedora-ds/plugins/ diff --git a/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/README b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/README new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/README diff --git a/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/ipa_pwd_extop.c b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/ipa_pwd_extop.c new file mode 100644 index 000000000..f871ee4f6 --- /dev/null +++ b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/ipa_pwd_extop.c @@ -0,0 +1,1359 @@ +/** BEGIN COPYRIGHT BLOCK + * This Program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; version 2 of the License. + * + * 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, write to the Free Software Foundation, Inc., 59 Temple + * Place, Suite 330, Boston, MA 02111-1307 USA. + * + * In addition, as a special exception, Red Hat, Inc. gives You the additional + * right to link the code of this Program with code not covered under the GNU + * General Public License ("Non-GPL Code") and to distribute linked combinations + * including the two, subject to the limitations in this paragraph. Non-GPL Code + * permitted under this exception must only link to the code of this Program + * through those well defined interfaces identified in the file named EXCEPTION + * found in the source code files (the "Approved Interfaces"). The files of + * Non-GPL Code may instantiate templates or use macros or inline functions from + * the Approved Interfaces without causing the resulting work to be covered by + * the GNU General Public License. Only Red Hat, Inc. may make changes or + * additions to the list of Approved Interfaces. You must obey the GNU General + * Public License in all respects for all of the Program code and other code used + * in conjunction with the Program except the Non-GPL Code covered by this + * exception. If you modify this file, you may extend this exception to your + * version of the file, but you are not obligated to do so. If you do not wish to + * provide this exception without modification, you must delete this exception + * statement from your version and license this file solely under the GPL without + * exception. + * + * Authors: + * Simo Sorce <ssorce@redhat.com> + * + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * END COPYRIGHT BLOCK **/ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +/* + * Password Modify - LDAP Extended Operation. + * RFC 3062 + * + * + * This plugin implements the "Password Modify - LDAP3" + * extended operation for LDAP. The plugin function is called by + * the server if an LDAP client request contains the OID: + * "1.3.6.1.4.1.4203.1.11.1". + * + */ + +#include <stdio.h> +#include <string.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +#include <prio.h> +#include <ssl.h> +#include <slapi-plugin.h> +#include <krb5.h> +#include <lber.h> +#include <time.h> +#include <iconv.h> +#include <mhash.h> +#include <openssl/des.h> + +/* Type of connection for this operation;*/ +#define LDAP_EXTOP_PASSMOD_CONN_SECURE + +/* Uncomment the following line FOR TESTING: allows non-SSL connections to use the password change extended op */ +/* #undef LDAP_EXTOP_PASSMOD_CONN_SECURE */ + +/* ber tags for the PasswdModifyRequestValue sequence */ +#define LDAP_EXTOP_PASSMOD_TAG_USERID 0x80U +#define LDAP_EXTOP_PASSMOD_TAG_OLDPWD 0x81U +#define LDAP_EXTOP_PASSMOD_TAG_NEWPWD 0x82U + +/* ber tags for the PasswdModifyResponseValue sequence */ +#define LDAP_EXTOP_PASSMOD_TAG_GENPWD 0x80U + +/* number of bytes used for random password generation */ +#define LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN 8 + +/* number of random bytes needed to generate password */ +#define LDAP_EXTOP_PASSMOD_RANDOM_BYTES 6 + +/* OID of the extended operation handled by this plug-in */ +#define EXOP_PASSWD_OID "1.3.6.1.4.1.4203.1.11.1" + +/* These are thye default enc:salt ypes if nothing is defined. + * TODO: retrieve the configure set of ecntypes either from the + * kfc.conf file or by synchronizing the the file content into + * the directory */ + +#define KTF_DISALLOW_POSTDATED 0x00000001 +#define KTF_DISALLOW_FORWARDABLE 0x00000002 +#define KTF_DISALLOW_TGT_BASED 0x00000004 +#define KTF_DISALLOW_RENEWABLE 0x00000008 +#define KTF_DISALLOW_PROXIABLE 0x00000010 +#define KTF_DISALLOW_DUP_SKEY 0x00000020 +#define KTF_DISALLOW_ALL_TIX 0x00000040 +#define KTF_REQUIRES_PRE_AUTH 0x00000080 +#define KTF_REQUIRES_HW_AUTH 0x00000100 +#define KTF_REQUIRES_PWCHANGE 0x00000200 +#define KTF_DISALLOW_SVR 0x00001000 +#define KTF_PWCHANGE_SERVICE 0x00002000 + +/* Salt types */ +#define KRB5_KDB_SALTTYPE_NORMAL 0 +#define KRB5_KDB_SALTTYPE_V4 1 +#define KRB5_KDB_SALTTYPE_NOREALM 2 +#define KRB5_KDB_SALTTYPE_ONLYREALM 3 +#define KRB5_KDB_SALTTYPE_SPECIAL 4 +#define KRB5_KDB_SALTTYPE_AFS3 5 + +#define KRB5P_SALT_SIZE 16 + +struct krb5p_keysalt { + krb5_int32 enc_type; + krb5_int32 salt_type; +}; + +static void *ipapwd_plugin_id; + +krb5_keyblock kmkey; + +struct krb5p_keysalt *keysalts; +int n_keysalts; + +/* Novell key-format scheme: + + KrbKeySet ::= SEQUENCE { + attribute-major-vno [0] UInt16, + attribute-minor-vno [1] UInt16, + kvno [2] UInt32, + mkvno [3] UInt32 OPTIONAL, + keys [4] SEQUENCE OF KrbKey, + ... + } + + KrbKey ::= SEQUENCE { + salt [0] KrbSalt OPTIONAL, + key [1] EncryptionKey, + s2kparams [2] OCTET STRING OPTIONAL, + ... + } + + KrbSalt ::= SEQUENCE { + type [0] Int32, + salt [1] OCTET STRING OPTIONAL + } + + EncryptionKey ::= SEQUENCE { + keytype [0] Int32, + keyvalue [1] OCTET STRING + } + + */ + +static inline void encode_int16(unsigned int val, unsigned char *p) +{ + p[1] = (val >> 8) & 0xff; + p[0] = (val ) & 0xff; +} + +static Slapi_Value **encrypt_encode_key(krb5_context krbctx, Slapi_Entry *e, const char *newPasswd) +{ + struct berval *bval = NULL; + Slapi_Value **svals = NULL; + BerElement *be = NULL; + int num_versions; + int krbTicketFlags; + const char *krbPrincipalName; + krb5_principal princ; + krb5_error_code krberr; + krb5_data pwd; + int ret, i; + + krbPrincipalName = slapi_entry_attr_get_charptr(e, "krbPrincipalName"); + if (!krbPrincipalName) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "no krbPrincipalName present in this entry\n"); + return NULL; + } + + /* TODO: retrieve current kvno and increment it */ + /* TODO: keep previous version */ + num_versions = 1; + + svals = (Slapi_Value **)calloc(num_versions + 1, sizeof(Slapi_Value *)); + if (!svals) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "memory allocation failed\n"); + return NULL; + } + + svals[1] = NULL; + + krberr = krb5_parse_name(krbctx, krbPrincipalName, &princ); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "krb5_parse_name failed [%s]\n", + krb5_get_error_message(krbctx, krberr)); + goto enc_error; + } + + krbTicketFlags = slapi_entry_attr_get_int(e, "krbTicketFlags"); + + pwd.data = (char *)newPasswd; + pwd.length = strlen(newPasswd); + + be = ber_alloc_t( LBER_USE_DER ); + + if (!be) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "memory allocation failed\n"); + goto enc_error; + } + + /* major-vno = 1 and minor-von = 1 */ + /* this encoding assumes all keys have the same kvno (currently set at 1) */ + /* we also assum mkvno is 0 */ + ret = ber_printf(be, "{t[i]t[i]t[i]t[i]t[{", + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 0), 1, + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 1), 1, + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 2), 1, + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 3), 0, + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 4)); + if (ret == -1) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "encoding asn1 vno info failed\n"); + goto enc_error; + } + + for (i = 0; i < n_keysalts; i++) { + krb5_keyblock key; + krb5_data salt; + krb5_octet *ptr; + krb5_data plain; + krb5_enc_data cipher; + size_t len; + const char *p; + + salt.data = NULL; + + switch (keysalts[i].salt_type) { + + case KRB5_KDB_SALTTYPE_ONLYREALM: + + p = strchr(krbPrincipalName, '@'); + if (!p) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "Invalid principal name, no realm found!\n"); + goto enc_error; + } + p++; + salt.data = strdup(p); + if (!salt.data) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "memory allocation failed\n"); + goto enc_error; + } + salt.length = strlen(salt.data); /* final \0 omitted on purpose */ + break; + + case KRB5_KDB_SALTTYPE_NOREALM: + + krberr = krb5_principal2salt_norealm(krbctx, princ, &salt); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "krb5_principal2salt failed [%s]\n", + krb5_get_error_message(krbctx, krberr)); + goto enc_error; + } + break; + + case KRB5_KDB_SALTTYPE_NORMAL: + + /* If pre auth is required we can set a random salt, otherwise + * we have to use a more conservative approach and set the salt + * to be REALMprincipal (the concatenation of REALM and principal + * name without any separator) */ + if (krbTicketFlags & KTF_REQUIRES_PRE_AUTH) { + salt.length = KRB5P_SALT_SIZE; + krberr = krb5_c_random_make_octets(krbctx, &salt); + if (!krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "krb5_c_random_make_octets failed [%s]\n", + krb5_get_error_message(krbctx, krberr)); + goto enc_error; + } + } else { + krberr = krb5_principal2salt(krbctx, princ, &salt); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "krb5_principal2salt failed [%s]\n", + krb5_get_error_message(krbctx, krberr)); + goto enc_error; + } + } + break; + + case KRB5_KDB_SALTTYPE_V4: + salt.length = 0; + break; + + case KRB5_KDB_SALTTYPE_AFS3: + + p = strchr(krbPrincipalName, '@'); + if (!p) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "Invalid principal name, no realm found!\n"); + goto enc_error; + } + p++; + salt.data = strdup(p); + if (!salt.data) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "memory allocation failed\n"); + goto enc_error; + } + salt.length = SALT_TYPE_AFS_LENGTH; /* special value */ + break; + + default: + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "Invalid salt type [%d]\n", keysalts[i].salt_type); + goto enc_error; + } + + /* need to build the key now to manage the AFS salt.length special case */ + krberr = krb5_c_string_to_key(krbctx, keysalts[i].enc_type, &pwd, &salt, &key); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "krb5_c_string_to_key failed [%s]\n", + krb5_get_error_message(krbctx, krberr)); + krb5_free_data_contents(krbctx, &salt); + goto enc_error; + } + if (salt.length == SALT_TYPE_AFS_LENGTH) { + salt.length = strlen(salt.data); + } + + krberr = krb5_c_encrypt_length(krbctx, kmkey.enctype, key.length, &len); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "krb5_c_string_to_key failed [%s]\n", + krb5_get_error_message(krbctx, krberr)); + krb5int_c_free_keyblock_contents(krbctx, &key); + krb5_free_data_contents(krbctx, &salt); + goto enc_error; + } + + if ((ptr = (krb5_octet *) malloc(2 + len)) == NULL) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "memory allocation failed\n"); + krb5int_c_free_keyblock_contents(krbctx, &key); + krb5_free_data_contents(krbctx, &salt); + goto enc_error; + } + + encode_int16(key.length, ptr); + + plain.length = key.length; + plain.data = key.contents; + + cipher.ciphertext.length = len; + cipher.ciphertext.data = ptr+2; + + krberr = krb5_c_encrypt(krbctx, &kmkey, 0, 0, &plain, &cipher); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "krb5_c_encrypt failed [%s]\n", + krb5_get_error_message(krbctx, krberr)); + krb5int_c_free_keyblock_contents(krbctx, &key); + krb5_free_data_contents(krbctx, &salt); + free(ptr); + goto enc_error; + } + + /* KrbSalt */ + if (salt.length) { + ret = ber_printf(be, "{t[{t[i]t[o]}]", + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 0), + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 0), keysalts[i].salt_type, + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 1), salt.data, salt.length); + } else { + ret = ber_printf(be, "{t[{t[i]}]", + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 0), + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 0), keysalts[i].salt_type); + } + if (ret == -1) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "encoding asn1 KrbSalt failed\n"); + krb5int_c_free_keyblock_contents(krbctx, &key); + krb5_free_data_contents(krbctx, &salt); + free(ptr); + goto enc_error; + } + + /* EncryptionKey */ + ret = ber_printf(be, "t[{t[i]t[o]}]}", + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 1), + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 0), key.enctype, + (ber_tag_t)(LBER_CONSTRUCTED | LBER_CLASS_CONTEXT | 1), ptr, len+2); + if (ret == -1) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "encoding asn1 EncryptionKey failed\n"); + krb5int_c_free_keyblock_contents(krbctx, &key); + krb5_free_data_contents(krbctx, &salt); + free(ptr); + goto enc_error; + } + + /* make sure we free the memory used now that we are done with it */ + krb5int_c_free_keyblock_contents(krbctx, &key); + krb5_free_data_contents(krbctx, &salt); + free(ptr); + } + + ret = ber_printf(be, "}]}"); + if (ret == -1) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "encoding asn1 end of sequences failed\n"); + goto enc_error; + } + + ret = ber_flatten(be, &bval); + if (ret == -1) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "flattening asn1 failed\n"); + goto enc_error; + } + + svals[0] = slapi_value_new_berval(bval); + if (!svals[0]) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", + "Converting berval to Slapi_Value\n"); + goto enc_error; + } + + krb5_free_principal(krbctx, princ); + ber_bvfree(bval); + ber_free(be, 1); + return svals; + +enc_error: + krb5_free_principal(krbctx, princ); + if (bval) ber_bvfree(bval); + if (svals) free(svals); + if (be) ber_free(be, 1); + return NULL; +} + +struct ntlm_keys { + uint8_t lm[16]; + uint8_t nt[16]; +}; + +#define KTF_LM_HASH 0x01 +#define KTF_NT_HASH 0x02 +#define KTF_DOS_CHARSET "CP850" /* same default as samba */ +#define KTF_UTF8 "UTF-8" +#define KTF_UCS2 "UCS-2LE" + +static const uint8_t parity_table[128] = { + 1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, + 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59, 61, 62, + 64, 67, 69, 70, 73, 74, 76, 79, 81, 82, 84, 87, 88, 91, 93, 94, + 97, 98,100,103,104,107,109,110,112,115,117,118,121,122,124,127, + 128,131,133,134,137,138,140,143,145,146,148,151,152,155,157,158, + 161,162,164,167,168,171,173,174,176,179,181,182,185,186,188,191, + 193,194,196,199,200,203,205,206,208,211,213,214,217,218,220,223, + 224,227,229,230,233,234,236,239,241,242,244,247,248,251,253,254}; + +static void lm_shuffle(char *out, char *in) +{ + uint8_t *outb = (uint8_t *)out; + uint8_t *inb = (uint8_t *)in; + + outb[0] = parity_table[inb[0]>>1]; + outb[1] = parity_table[((inb[0]<<6)|(in[1]>>2)) & 0x7F]; + outb[2] = parity_table[((inb[1]<<5)|(in[2]>>3)) & 0x7F]; + outb[3] = parity_table[((inb[2]<<4)|(in[3]>>4)) & 0x7F]; + outb[4] = parity_table[((inb[3]<<3)|(in[4]>>5)) & 0x7F]; + outb[5] = parity_table[((inb[4]<<2)|(in[5]>>6)) & 0x7F]; + outb[6] = parity_table[((inb[5]<<1)|(in[6]>>7)) & 0x7F]; + outb[7] = parity_table[inb[6] & 0x7F]; +} + +/* create the lm and nt hashes + newPassword: the clear text utf8 password + flags: KTF_LM_HASH | KTF_NT_HASH +*/ +static int encode_ntlm_keys(char *newPasswd, unsigned int flags, struct ntlm_keys *keys) +{ + int ret = 0; + + /* do lanman first */ + if (flags & KTF_LM_HASH) { + iconv_t cd; + size_t cs, il, ol; + char *inc, *outc; + char *upperPasswd; + char *asciiPasswd; + DES_key_schedule schedule; + DES_cblock deskey; + DES_cblock magic = "KGS!@#$%"; + + /* TODO: must store the dos charset somewhere in the directory */ + cd = iconv_open(KTF_DOS_CHARSET, KTF_UTF8); + if (cd == (iconv_t)(-1)) { + ret = -1; + goto done; + } + + /* the lanman password is upper case */ + upperPasswd = slapi_utf8StrToUpper(newPasswd); + if (!upperPasswd) { + ret = -1; + goto done; + } + il = strlen(upperPasswd); + + /* an ascii string can only be smaller than or equal to an utf8 one */ + ol = il; + if (ol < 14) ol = 14; + asciiPasswd = calloc(ol+1, 1); + if (!asciiPasswd) { + slapi_ch_free_string(&upperPasswd); + ret = -1; + goto done; + } + + inc = upperPasswd; + outc = asciiPasswd; + cs = iconv(cd, &inc, &il, &outc, &ol); + if (cs == -1) { + ret = -1; + slapi_ch_free_string(&upperPasswd); + free(asciiPasswd); + iconv_close(cd); + goto done; + } + + /* done with these */ + slapi_ch_free_string(&upperPasswd); + iconv_close(cd); + + /* we are interested only in the first 14 ASCII chars for lanman */ + if (strlen(asciiPasswd) > 14) { + asciiPasswd[14] = '\0'; + } + + /* first half */ + lm_shuffle(deskey, asciiPasswd); + + DES_set_key_unchecked(&deskey, &schedule); + DES_ecb_encrypt(&magic, (DES_cblock *)keys->lm, &schedule, DES_ENCRYPT); + + /* second half */ + lm_shuffle(deskey, &asciiPasswd[7]); + + DES_set_key_unchecked(&deskey, &schedule); + DES_ecb_encrypt(&magic, (DES_cblock *)&(keys->lm[8]), &schedule, DES_ENCRYPT); + + /* done with it */ + free(asciiPasswd); + + } else { + memset(keys->lm, 0, 16); + } + + if (flags & KTF_NT_HASH) { + iconv_t cd; + size_t cs, il, ol, sl; + char *inc, *outc; + char *ucs2Passwd; + MHASH td; + + /* TODO: must store the dos charset somewhere in the directory */ + cd = iconv_open(KTF_UCS2, KTF_UTF8); + if (cd == (iconv_t)(-1)) { + ret = -1; + goto done; + } + + il = strlen(newPasswd); + + /* an ucs2 string can be at most double than an utf8 one */ + sl = ol = (il+1)*2; + ucs2Passwd = calloc(ol, 1); + if (!ucs2Passwd) { + ret = -1; + goto done; + } + + inc = newPasswd; + outc = ucs2Passwd; + cs = iconv(cd, &inc, &il, &outc, &ol); + if (cs == -1) { + ret = -1; + free(ucs2Passwd); + iconv_close(cd); + goto done; + } + + /* done with it */ + iconv_close(cd); + + /* get the final ucs2 string length */ + sl -= ol; + /* we are interested only in the first 14 wchars for the nt password */ + if (sl > 28) { + sl = 28; + } + + td = mhash_init(MHASH_MD4); + if (td == MHASH_FAILED) { + ret = -1; + free(ucs2Passwd); + goto done; + } + + mhash(td, ucs2Passwd, sl); + mhash_deinit(td, keys->nt); + + } else { + memset(keys->nt, 0, 16); + } + +done: + return ret; +} + +/* Searches the dn in directory, + * If found : fills in slapi_entry structure and returns 0 + * If NOT found : returns the search result as LDAP_NO_SUCH_OBJECT + */ +static int +ipapwd_getEntry( const char *dn, Slapi_Entry **e2 ) { + int search_result = 0; + Slapi_DN *sdn; + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "=> ipapwd_getEntry\n"); + + sdn = slapi_sdn_new_dn_byref(dn); + if ((search_result = slapi_search_internal_get_entry( sdn, NULL, e2, + ipapwd_plugin_id)) != LDAP_SUCCESS ){ + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "ipapwd_getEntry: No such entry-(%s), err (%d)\n", + dn, search_result); + } + + slapi_sdn_free( &sdn ); + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "<= ipapwd_getEntry: %d\n", search_result); + return search_result; +} + + +/* Construct Mods pblock and perform the modify operation + * Sets result of operation in SLAPI_PLUGIN_INTOP_RESULT + */ +static int ipapwd_apply_mods(const char *dn, Slapi_Mods *mods) +{ + Slapi_PBlock *pb; + int ret=0; + + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "=> ipapwd_apply_mods\n"); + + if (mods && (slapi_mods_get_num_mods(mods) > 0)) + { + pb = slapi_pblock_new(); + slapi_modify_internal_set_pb (pb, dn, + slapi_mods_get_ldapmods_byref(mods), + NULL, /* Controls */ + NULL, /* UniqueID */ + ipapwd_plugin_id, /* PluginID */ + 0); /* Flags */ + + ret = slapi_modify_internal_pb (pb); + + slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &ret); + + if (ret != LDAP_SUCCESS){ + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "WARNING: modify error %d on entry '%s'\n", + ret, dn); + } + + slapi_pblock_destroy(pb); + } + + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "<= ipapwd_apply_mods: %d\n", ret); + + return ret; +} + +/* ascii hex output of bytes in "in" + * out len is 32 (preallocated) + * in len is 16 */ +static const char hexchars[] = "0123456789ABCDEF"; +static void hexbuf(char *out, const uint8_t *in) +{ + int i; + + for (i = 0; i < 16; i++) { + out[i*2] = hexchars[in[i] >> 4]; + out[i*2+1] = hexchars[in[i] & 0x0f]; + } +} + +/* Modify the userPassword attribute field of the entry */ +static int ipapwd_userpassword(Slapi_Entry *targetEntry, const char *newPasswd) +{ + char *dn = NULL; + int ret = 0, i = 0; + Slapi_Mods *smods; + Slapi_Mod *keymod; + Slapi_Value **svals; + time_t curtime; + struct tm utctime; + char timestr[16]; + krb5_context krbctx; + krb5_error_code krberr; + char lm[33], nt[33]; + struct ntlm_keys ntlm; + int ntlm_flags = 0; + Slapi_Value *sambaSamAccount; + + krberr = krb5_init_context(&krbctx); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "krb5_init_context failed\n"); + return LDAP_OPERATIONS_ERROR; + } + + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "=> ipapwd_userpassword\n"); + + smods = slapi_mods_new(); + dn = slapi_entry_get_ndn( targetEntry ); + + /* generate kerberos keys to be put into krbPrincipalKey */ + svals = encrypt_encode_key(krbctx, targetEntry, newPasswd); + if (!svals) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "key encryption/encoding failed\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + /* done with it */ + krb5_free_context(krbctx); + + slapi_mods_add_mod_values(smods, LDAP_MOD_REPLACE, "krbPrincipalKey", svals); + + /* change Last Password Change field with the current date */ + curtime = time(NULL); + if (!gmtime_r(&curtime, &utctime)) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "failed to retrieve current date (buggy gmtime_r ?)\n"); + return LDAP_OPERATIONS_ERROR; + } + if (utctime.tm_year > 8099 || utctime.tm_mon > 11 || utctime.tm_mday > 31 || + utctime.tm_hour > 23 || utctime.tm_min > 59 || utctime.tm_sec > 59) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "retrieved a bad date (buggy gmtime_r ?)\n"); + return LDAP_OPERATIONS_ERROR; + } + + snprintf(timestr, 16, "%04d%02d%02d%02d%02d%02dZ", utctime.tm_year+1900, utctime.tm_mon+1, + utctime.tm_mday, utctime.tm_hour, utctime.tm_min, utctime.tm_sec); + + slapi_mods_add_string(smods, LDAP_MOD_REPLACE, "krbLastPwdChange", timestr); + /* TODO: krbPasswordExpiration, (krbMaxTicketLife, krbMaxRenewableAge, krbTicketFlags ?) */ + + sambaSamAccount = slapi_value_new_string("sambaSamAccount"); + if (slapi_entry_attr_has_syntax_value(targetEntry, "objectClass", sambaSamAccount)) { + /* TODO: retrieve if we want to store the LM hash or not */ + ntlm_flags = KTF_LM_HASH | KTF_NT_HASH; + } + slapi_value_free(&sambaSamAccount); + + if (ntlm_flags) { + if (encode_ntlm_keys((char *)newPasswd, ntlm_flags, &ntlm) != 0) { + return LDAP_OPERATIONS_ERROR; + } + if (ntlm_flags & KTF_LM_HASH) { + hexbuf(lm, ntlm.lm); + lm[32] = '\0'; + slapi_mods_add_string(smods, LDAP_MOD_REPLACE, "sambaLMPassword", lm); + } + if (ntlm_flags & KTF_NT_HASH) { + hexbuf(nt, ntlm.nt); + nt[32] = '\0'; + slapi_mods_add_string(smods, LDAP_MOD_REPLACE, "sambaNTPassword", nt); + } + } + + /* commit changes */ + ret = ipapwd_apply_mods(dn, smods); + + slapi_mods_free(&smods); + + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "<= ipapwd_userpassword: %d\n", ret); + + +mod_done: + for (i = 0; svals[i]; i++) { + slapi_value_free(&svals[i]); + } + free(svals); + return ret; +} + +/* Generate a new, basic random password */ +static int ipapwd_generate_basic_passwd( int passlen, char **genpasswd ) +{ + unsigned char *data = NULL; + char *enc = NULL; + int datalen = LDAP_EXTOP_PASSMOD_RANDOM_BYTES; + int enclen = LDAP_EXTOP_PASSMOD_GEN_PASSWD_LEN + 1; + + if ( genpasswd == NULL ) { + return LDAP_OPERATIONS_ERROR; + } + + if ( passlen > 0 ) { + datalen = passlen * 3 / 4 + 1; + enclen = datalen * 4; /* allocate the large enough space */ + } + + data = (unsigned char *)slapi_ch_calloc( datalen, 1 ); + enc = (char *)slapi_ch_calloc( enclen, 1 ); + + /* get random bytes from NSS */ + PK11_GenerateRandom( data, datalen ); + + /* b64 encode the random bytes to get a password made up + * of printable characters. ldif_base64_encode() will + * zero-terminate the string */ + (void)ldif_base64_encode( data, enc, passlen, -1 ); + + /* This will get freed by the caller */ + *genpasswd = slapi_ch_malloc( 1 + passlen ); + + /* trim the password to the proper length */ + PL_strncpyz( *genpasswd, enc, passlen + 1 ); + + slapi_ch_free( (void **)&data ); + slapi_ch_free_string( &enc ); + + return LDAP_SUCCESS; +} + + +/* Password Modify Extended operation plugin function */ +int +ipapwd_extop( Slapi_PBlock *pb ) +{ + char *oid = NULL; + char *bindDN = NULL; + char *authmethod = NULL; + char *dn = NULL; + char *oldPasswd = NULL; + char *newPasswd = NULL; + char *errMesg = NULL; + int ret=0, rc=0, sasl_ssf=0, is_ssl=0, is_root=0; + ber_tag_t tag=0; + ber_len_t len=-1; + struct berval *extop_value = NULL; + BerElement *ber = NULL; + BerElement *response_ber = NULL; + Slapi_Entry *targetEntry=NULL; + /* Slapi_DN sdn; */ + + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "=> ipa_pwd_extop\n"); + + /* Before going any further, we'll make sure that the right extended operation plugin + * has been called: i.e., the OID shipped whithin the extended operation request must + * match this very plugin's OID: EXOP_PASSWD_OID. */ + if ( slapi_pblock_get( pb, SLAPI_EXT_OP_REQ_OID, &oid ) != 0 ) { + errMesg = "Could not get OID value from request.\n"; + rc = LDAP_OPERATIONS_ERROR; + slapi_log_error( SLAPI_LOG_PLUGIN, "ipa_pwd_extop", + errMesg ); + goto free_and_return; + } else { + slapi_log_error( SLAPI_LOG_PLUGIN, "ipa_pwd_extop", + "Received extended operation request with OID %s\n", oid ); + } + + if ( strcasecmp( oid, EXOP_PASSWD_OID ) != 0) { + errMesg = "Request OID does not match Passwd OID.\n"; + rc = LDAP_OPERATIONS_ERROR; + goto free_and_return; + } else { + slapi_log_error( SLAPI_LOG_PLUGIN, "ipa_pwd_extop", + "Password Modify extended operation request confirmed.\n" ); + } + + /* Now , at least we know that the request was indeed a Password Modify one. */ + +#ifdef LDAP_EXTOP_PASSMOD_CONN_SECURE + /* Allow password modify only for SSL/TLS established connections and + * connections using SASL privacy layers */ + if ( slapi_pblock_get(pb, SLAPI_CONN_SASL_SSF, &sasl_ssf) != 0) { + errMesg = "Could not get SASL SSF from connection\n"; + rc = LDAP_OPERATIONS_ERROR; + slapi_log_error( SLAPI_LOG_PLUGIN, "ipa_pwd_extop", + errMesg ); + goto free_and_return; + } + + if (slapi_pblock_get(pb, SLAPI_CONN_IS_SSL_SESSION, &is_ssl) != 0) { + errMesg = "Could not get IS SSL from connection\n"; + rc = LDAP_OPERATIONS_ERROR; + slapi_log_error( SLAPI_LOG_PLUGIN, "ipa_pwd_extop", + errMesg ); + goto free_and_return; + } + + if ( (is_ssl <=1) && (sasl_ssf <= 1) ) { + errMesg = "Operation requires a secure connection.\n"; + rc = LDAP_CONFIDENTIALITY_REQUIRED; + goto free_and_return; + } +#endif + + /* Get the ber value of the extended operation */ + slapi_pblock_get(pb, SLAPI_EXT_OP_REQ_VALUE, &extop_value); + + if ((ber = ber_init(extop_value)) == NULL) + { + errMesg = "PasswdModify Request decode failed.\n"; + rc = LDAP_PROTOCOL_ERROR; + goto free_and_return; + } + + /* Format of request to parse + * + * PasswdModifyRequestValue ::= SEQUENCE { + * userIdentity [0] OCTET STRING OPTIONAL + * oldPasswd [1] OCTET STRING OPTIONAL + * newPasswd [2] OCTET STRING OPTIONAL } + * + * The request value field is optional. If it is + * provided, at least one field must be filled in. + */ + + /* ber parse code */ + if ( ber_scanf( ber, "{") == LBER_ERROR ) + { + /* The request field wasn't provided. We'll + * now try to determine the userid and verify + * knowledge of the old password via other + * means. + */ + goto parse_req_done; + } else { + tag = ber_peek_tag( ber, &len); + } + + + /* identify userID field by tags */ + if (tag == LDAP_EXTOP_PASSMOD_TAG_USERID ) + { + if ( ber_scanf( ber, "a", &dn) == LBER_ERROR ) + { + slapi_ch_free_string(&dn); + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "ber_scanf failed :{\n"); + errMesg = "ber_scanf failed at userID parse.\n"; + rc = LDAP_PROTOCOL_ERROR; + goto free_and_return; + } + + tag = ber_peek_tag( ber, &len); + } + + + /* identify oldPasswd field by tags */ + if (tag == LDAP_EXTOP_PASSMOD_TAG_OLDPWD ) + { + if ( ber_scanf( ber, "a", &oldPasswd ) == LBER_ERROR ) + { + slapi_ch_free_string(&oldPasswd); + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "ber_scanf failed :{\n"); + errMesg = "ber_scanf failed at oldPasswd parse.\n"; + rc = LDAP_PROTOCOL_ERROR; + goto free_and_return; + } + tag = ber_peek_tag( ber, &len); + } + + /* identify newPasswd field by tags */ + if (tag == LDAP_EXTOP_PASSMOD_TAG_NEWPWD ) + { + if ( ber_scanf( ber, "a", &newPasswd ) == LBER_ERROR ) + { + slapi_ch_free_string(&newPasswd); + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "ber_scanf failed :{\n"); + errMesg = "ber_scanf failed at newPasswd parse.\n"; + rc = LDAP_PROTOCOL_ERROR; + goto free_and_return; + } + } + +parse_req_done: + /* Uncomment for debugging, otherwise we don't want to leak the password values into the log... */ + /* LDAPDebug( LDAP_DEBUG_ARGS, "passwd: dn (%s), oldPasswd (%s) ,newPasswd (%s)\n", + dn, oldPasswd, newPasswd); */ + + + /* Get Bind DN */ + slapi_pblock_get( pb, SLAPI_CONN_DN, &bindDN ); + + /* If the connection is bound anonymously, we must refuse to process this operation. */ + if (bindDN == NULL || *bindDN == '\0') { + /* Refuse the operation because they're bound anonymously */ + errMesg = "Anonymous Binds are not allowed.\n"; + rc = LDAP_INSUFFICIENT_ACCESS; + goto free_and_return; + } + + /* A new password was not supplied in the request, and we do not support + * password generation yet. + */ + if (newPasswd == NULL || *newPasswd == '\0') { + errMesg = "Password generation not implemented.\n"; + rc = LDAP_UNWILLING_TO_PERFORM; + goto free_and_return; + } + + if (oldPasswd == NULL || *oldPasswd == '\0') { + /* If user is authenticated, they already gave their password during + the bind operation (or used sasl or client cert auth or OS creds) */ + slapi_pblock_get(pb, SLAPI_CONN_AUTHMETHOD, &authmethod); + if (!authmethod || !strcmp(authmethod, SLAPD_AUTH_NONE)) { + errMesg = "User must be authenticated to the directory server.\n"; + rc = LDAP_INSUFFICIENT_ACCESS; + goto free_and_return; + } + } + + /* Determine the target DN for this operation */ + /* Did they give us a DN ? */ + if (dn == NULL || *dn == '\0') { + /* Get the DN from the bind identity on this connection */ + dn = slapi_ch_strdup(bindDN); + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", + "Missing userIdentity in request, using the bind DN instead.\n"); + } + + slapi_pblock_set( pb, SLAPI_ORIGINAL_TARGET, dn ); + + /* Now we have the DN, look for the entry */ + ret = ipapwd_getEntry(dn, &targetEntry); + /* If we can't find the entry, then that's an error */ + if (ret) { + /* Couldn't find the entry, fail */ + errMesg = "No such Entry exists.\n" ; + rc = LDAP_NO_SUCH_OBJECT ; + goto free_and_return; + } + + /* First thing to do is to ask access control if the bound identity has + rights to modify the userpassword attribute on this entry. If not, then + we fail immediately with insufficient access. This means that we don't + leak any useful information to the client such as current password + wrong, etc. + */ + + is_root = slapi_dn_isroot(bindDN); + slapi_pblock_set(pb, SLAPI_REQUESTOR_ISROOT, &is_root); + + /* In order to perform the access control check , we need to select a backend (even though + * we don't actually need it otherwise). + */ + { + Slapi_Backend *be = NULL; + + be = slapi_be_select(slapi_entry_get_sdn(targetEntry)); + if (NULL == be) { + errMesg = "Failed to find backend for target entry"; + rc = LDAP_OPERATIONS_ERROR; + goto free_and_return; + } + slapi_pblock_set(pb, SLAPI_BACKEND, be); + } + + ret = slapi_access_allowed ( pb, targetEntry, SLAPI_USERPWD_ATTR, NULL, SLAPI_ACL_WRITE ); + if ( ret != LDAP_SUCCESS ) { + errMesg = "Insufficient access rights\n"; + rc = LDAP_INSUFFICIENT_ACCESS; + goto free_and_return; + } + + /* Now we have the entry which we want to modify + * They gave us a password (old), check it against the target entry + * Is the old password valid ? + */ + if (oldPasswd && *oldPasswd) { + /* If user is authenticated, they already gave their password during + the bind operation (or used sasl or client cert auth or OS creds) */ + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "oldPasswd provided, but we will ignore it"); + } + + + /* Now we're ready to make actual password change */ + ret = ipapwd_userpassword(targetEntry, newPasswd); + if (ret != LDAP_SUCCESS) { + /* Failed to modify the password, e.g. because insufficient access allowed */ + errMesg = "Failed to update password\n"; + rc = ret; + goto free_and_return; + } + + slapi_log_error(SLAPI_LOG_TRACE, "ipa_pwd_extop", "<= ipa_pwd_extop: %d\n", rc); + + /* Free anything that we allocated above */ + free_and_return: + slapi_ch_free_string(&oldPasswd); + slapi_ch_free_string(&newPasswd); + /* Either this is the same pointer that we allocated and set above, + * or whoever used it should have freed it and allocated a new + * value that we need to free here */ + slapi_pblock_get( pb, SLAPI_ORIGINAL_TARGET, &dn ); + slapi_ch_free_string(&dn); + slapi_pblock_set( pb, SLAPI_ORIGINAL_TARGET, NULL ); + slapi_ch_free_string(&authmethod); + + if ( targetEntry != NULL ){ + slapi_entry_free (targetEntry); + } + + if ( ber != NULL ){ + ber_free(ber, 1); + ber = NULL; + } + + slapi_log_error( SLAPI_LOG_PLUGIN, "ipa_pwd_extop", + errMesg ? errMesg : "success" ); + send_ldap_result( pb, rc, NULL, errMesg, 0, NULL ); + + + return( SLAPI_PLUGIN_EXTENDED_SENT_RESULT ); + +}/* ipa_pwd_extop */ + + +static char *ipapwd_oid_list[] = { + EXOP_PASSWD_OID, + NULL +}; + + +static char *ipapwd_name_list[] = { + "ipa_pwd_extop", + NULL +}; + +/* will read this from the krbSupportedEncSaltTypes in the krbRealmContainer later on */ +const char *krb_sup_encs[] = { + "des3-hmac-sha1:normal", + "arcfour-hmac:normal", + "des-hmac-sha1:normal", + "des-cbc-md5:normal", + "des-cbc-crc:normal", + "des-cbc-crc:v4", + "des-cbc-crc:afs3", + NULL +}; + +#define KRBCHECK(ctx, err, fname) do { \ + if (err) { \ + slapi_log_error(SLAPI_LOG_PLUGIN, "ipapwd_start", \ + "%s failed [%s]\n", fname, \ + krb5_get_error_message(ctx, err)); \ + return LDAP_OPERATIONS_ERROR; \ + } } while(0) + +/* Init data structs */ +/* TODO: read input from tree */ +int ipapwd_start( Slapi_PBlock *pb ) +{ + int krberr, i; + krb5_context krbctx; + krb5_data pwd, salt; + krb5_enctype etype; + char *config_dn; + Slapi_Entry *config_entry; + const char *stash_file; + int fd; + ssize_t r; + uint16_t e; + unsigned int l; + char *o; + + krberr = krb5_init_context(&krbctx); + if (krberr) { + slapi_log_error(SLAPI_LOG_FATAL, "ipa_pwd_extop", "krb5_init_context failed\n"); + return LDAP_OPERATIONS_ERROR; + } + + for (i = 0; krb_sup_encs[i]; i++) /* count */ ; + keysalts = (struct krb5p_keysalt *)malloc(sizeof(struct krb5p_keysalt) * (i + 1)); + if (!keysalts) { + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + for (i = 0, n_keysalts = 0; krb_sup_encs[i]; i++) { + char *enc, *salt; + krb5_int32 tmpenc; + krb5_int32 tmpsalt; + krb5_boolean similar; + int j; + + enc = strdup(krb_sup_encs[i]); + if (!enc) { + slapi_log_error( SLAPI_LOG_PLUGIN, "ipapwd_start", "Allocation error\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + salt = strchr(enc, ':'); + if (!salt) { + slapi_log_error( SLAPI_LOG_PLUGIN, "ipapwd_start", "Invalid krb5 enc string\n"); + free(enc); + continue; + } + *salt = '\0'; /* null terminate the enc type */ + salt++; /* skip : */ + + krberr = krb5_string_to_enctype(enc, &tmpenc); + if (krberr) { + slapi_log_error( SLAPI_LOG_PLUGIN, "ipapwd_start", "Invalid krb5 enctype\n"); + free(enc); + continue; + } + + krberr = krb5_string_to_salttype(salt, &tmpsalt); + for (j = 0; j < n_keysalts; j++) { + krb5_c_enctype_compare(krbctx, keysalts[j].enc_type, tmpenc, &similar); + if (similar && (keysalts[j].salt_type == tmpsalt)) { + break; + } + } + + if (j == n_keysalts) { + /* not found */ + keysalts[j].enc_type = tmpenc; + keysalts[j].salt_type = tmpsalt; + n_keysalts++; + } + + free(enc); + } + + /*retrieve the master key from the stash file */ + if (slapi_pblock_get(pb, SLAPI_TARGET_DN, &config_dn) != 0) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "No config DN?\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + if (ipapwd_getEntry(config_dn, &config_entry) != LDAP_SUCCESS) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "No config Entry?\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + stash_file = slapi_entry_attr_get_charptr(config_entry, "nsslapd-pluginarg0"); + if (!stash_file) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "Missing Master key stash file path configuration entry (nsslapd-pluginarg0)!\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + fd = open(stash_file, O_RDONLY); + if (fd == -1) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "Missing Master key stash file!\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + r = read(fd, &e, 2); /* read enctype a local endian 16bit value */ + if (r != 2) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "Error reading Master key stash file!\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + r = read(fd, &l, sizeof(l)); /* read the key length, a horrible sizeof(int) local endian value */ + if (r != sizeof(l)) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "Error reading Master key stash file!\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + if (l == 0 || l > 1024) { /* the maximum key size should be 32 bytes, lets's not accept more than 1k anyway */ + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "Invalid key lenght, Master key stash file corrupted?\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + o = malloc(l); + if (!o) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "Memory allocation problem!\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + r = read(fd, o, l); + if (r != l) { + slapi_log_error( SLAPI_LOG_FATAL, "ipapwd_start", "Error reading Master key stash file!\n"); + krb5_free_context(krbctx); + return LDAP_OPERATIONS_ERROR; + } + + close(fd); + + kmkey.magic = KV5M_KEYBLOCK; + kmkey.enctype = e; + kmkey.length = l; + kmkey.contents = o; + + krb5_free_context(krbctx); + return LDAP_SUCCESS; +} + +/* Initialization function */ +int ipapwd_init( Slapi_PBlock *pb ) +{ + char **argv; + char *oid; + + /* Get the arguments appended to the plugin extendedop directive. The first argument + * (after the standard arguments for the directive) should contain the OID of the + * extended operation. + */ + + if ((slapi_pblock_get(pb, SLAPI_PLUGIN_IDENTITY, &ipapwd_plugin_id) != 0) + || (ipapwd_plugin_id == NULL)) { + slapi_log_error( SLAPI_LOG_PLUGIN, "ipapwd_init", "Could not get identity or identity was NULL\n"); + return( -1 ); + } + + /* Register the plug-in function as an extended operation + * plug-in function that handles the operation identified by + * OID 1.3.6.1.4.1.4203.1.11.1 . Also specify the version of the server + * plug-in */ + if ( slapi_pblock_set( pb, SLAPI_PLUGIN_VERSION, SLAPI_PLUGIN_VERSION_01 ) != 0 || + slapi_pblock_set( pb, SLAPI_PLUGIN_START_FN, (void *) ipapwd_start ) != 0 || + slapi_pblock_set( pb, SLAPI_PLUGIN_EXT_OP_FN, (void *) ipapwd_extop ) != 0 || + slapi_pblock_set( pb, SLAPI_PLUGIN_EXT_OP_OIDLIST, ipapwd_oid_list ) != 0 || + slapi_pblock_set( pb, SLAPI_PLUGIN_EXT_OP_NAMELIST, ipapwd_name_list ) != 0 ) { + + slapi_log_error( SLAPI_LOG_PLUGIN, "ipapwd_init", + "Failed to set plug-in version, function, and OID.\n" ); + return( -1 ); + } + + return( 0 ); +} diff --git a/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/plugin-conf.ldif b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/plugin-conf.ldif new file mode 100644 index 000000000..738ef7ab5 --- /dev/null +++ b/ipa-server/ipa-slapi-plugins/ipa-pwd-extop/plugin-conf.ldif @@ -0,0 +1,14 @@ +dn: cn=ipa_pwd_extop,cn=plugins,cn=config +objectclass: top +objectclass: nsSlapdPlugin +objectclass: extensibleObject +cn: ipa_pwd_extop +nsslapd-pluginpath: /usr/lib/fedora-ds/plugins/libipa_pwd_extop.so +nsslapd-plugininitfunc: ipapwd_init +nsslapd-plugintype: extendedop +nsslapd-pluginenabled: on +nsslapd-pluginid: Multi-hash Change Password Extended Operation +nsslapd-pluginversion: 1.0 +nsslapd-pluginvendor: RedHat +nsslapd-plugindescription: Support saving passwords in multiple fornmats for different consumers like krb5, samba, freeradius, etc. +nsslapd-pluginarg0: /var/kerberos/krb5kdc/.k5.$REALM diff --git a/ipa-server/ipaserver/__init__.py b/ipa-server/ipaserver/__init__.py new file mode 100644 index 000000000..6d254d6af --- /dev/null +++ b/ipa-server/ipaserver/__init__.py @@ -0,0 +1,57 @@ +#! /usr/bin/python -E +# Authors: Karl MacMillan <kmacmillan@mentalrootkit.com> +# see inline +# +# Copyright (C) 2007 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; version 2 or later +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +__all__ = ["dsinstance", "krbinstance"] + +# +# Functions common for the XML RPC client and server +# +# Authors: +# Mike McLean <mikem@redhat.com> (from koji) + +# functions for encoding/decoding optional arguments + +def encode_args(*args,**opts): + """The function encodes optional arguments as regular arguments. + + This is used to allow optional arguments in xmlrpc calls + Returns a tuple of args + """ + if opts: + opts['__starstar'] = True + args = args + (opts,) + return args + +def decode_args(*args): + """Decodes optional arguments from a flat argument list + + Complementary to encode_args + Returns a tuple (args,opts) where args is a tuple and opts is a dict + """ + opts = {} + if len(args) > 0: + last = args[-1] + if type(last) == dict and last.get('__starstar',False): + del last['__starstar'] + opts = last + args = args[:-1] + return args,opts + diff --git a/ipa-server/ipaserver/dsinstance.py b/ipa-server/ipaserver/dsinstance.py new file mode 100644 index 000000000..775a2f2b3 --- /dev/null +++ b/ipa-server/ipaserver/dsinstance.py @@ -0,0 +1,168 @@ +#! /usr/bin/python -E +# Authors: Karl MacMillan <kmacmillan@mentalrootkit.com> +# +# Copyright (C) 2007 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; version 2 or later +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +import subprocess +import string +import tempfile +import shutil +import logging +import pwd +from util import * + + +SHARE_DIR = "/usr/share/ipa/" +SERVER_ROOT_64 = "/usr/lib64/fedora-ds-base" +SERVER_ROOT_32 = "/usr/lib/fedora-ds-base" + + +def generate_serverid(): + """Generate a UUID (universally unique identifier) suitable + for use as a unique identifier for a DS instance. + """ + try: + import uuid + id = str(uuid.uuid1()) + except ImportError: + import commands + id = commands.getoutput("/usr/bin/uuidgen") + return id + +def realm_to_suffix(realm_name): + s = realm_name.split(".") + terms = ["dc=" + x.lower() for x in s] + return ",".join(terms) + +def find_server_root(): + if dir_exists(SERVER_ROOT_64): + return SERVER_ROOT_64 + else: + return SERVER_ROOT_32 + +INF_TEMPLATE = """ +[General] +FullMachineName= $FQHN +SuiteSpotUserID= $USER +ServerRoot= $SERVER_ROOT +[slapd] +ServerPort= 389 +ServerIdentifier= $SERVERID +Suffix= $SUFFIX +RootDN= cn=Directory Manager +RootDNPwd= $PASSWORD +""" + +class DsInstance: + def __init__(self): + self.serverid = None + self.realm_name = None + self.host_name = None + self.admin_password = None + self.sub_dict = None + + def create_instance(self, ds_user, realm_name, host_name, admin_password): + self.ds_user = ds_user + self.serverid = generate_serverid() + self.realm_name = realm_name.upper() + self.host_name = host_name + self.admin_password = admin_password + self.__setup_sub_dict() + + self.__create_ds_user() + self.__create_instance() + self.__add_default_schemas() + self.__enable_ssl() + self.restart() + self.__add_default_layout() + + def config_dirname(self): + if not self.serverid: + raise RuntimeError("serverid not set") + return "/etc/fedora-ds/slapd-" + self.serverid + "/" + + def schema_dirname(self): + return self.config_dirname() + "/schema/" + + def stop(self): + run(["/sbin/service", "fedora-ds", "stop"]) + + def start(self): + run(["/sbin/service", "fedora-ds", "start"]) + + def restart(self): + run(["/sbin/service", "fedora-ds", "restart"]) + + def __setup_sub_dict(self): + suffix = realm_to_suffix(self.realm_name) + server_root = find_server_root() + self.sub_dict = dict(FQHN=self.host_name, SERVERID=self.serverid, + PASSWORD=self.admin_password, SUFFIX=suffix, + REALM=self.realm_name, USER=self.ds_user, + SERVER_ROOT=server_root) + + def __create_ds_user(self): + try: + pwd.getpwnam(self.ds_user) + logging.debug("ds user %s exists" % self.ds_user) + except KeyError: + logging.debug("adding ds user %s" % self.ds_user) + args = ["/usr/sbin/useradd", "-c", "DS System User", "-d", "/var/lib/fedora-ds", "-M", "-r", "-s", "/sbin/nologin", self.ds_user] + run(args) + logging.debug("done adding user") + + def __create_instance(self): + logging.debug("creating ds instance . . . ") + inf_txt = template_str(INF_TEMPLATE, self.sub_dict) + logging.debug(inf_txt) + inf_fd = write_tmp_file(inf_txt) + logging.debug("writing inf template") + if file_exists("/usr/sbin/setup-ds.pl"): + args = ["/usr/sbin/setup-ds.pl", "--silent", "--logfile", "-", "-f", inf_fd.name] + logging.debug("calling setup-ds.pl") + else: + args = ["/usr/sbin/ds_newinst.pl", inf_fd.name] + logging.debug("calling ds_newinst.pl") + run(args) + logging.debug("completed creating ds instance") + logging.debug("restarting ds instance") + self.restart() + logging.debug("done restarting ds instance") + + def __add_default_schemas(self): + shutil.copyfile(SHARE_DIR + "60kerberos.ldif", + self.schema_dirname() + "60kerberos.ldif") + shutil.copyfile(SHARE_DIR + "60samba.ldif", + self.schema_dirname() + "60samba.ldif") + + def __enable_ssl(self): + logging.debug("configuring ssl for ds instance") + dirname = self.config_dirname() + args = ["/usr/sbin/ipa-server-setupssl", self.admin_password, + dirname, self.host_name] + run(args) + logging.debug("done configuring ssl for ds instance") + + def __add_default_layout(self): + txt = template_file(SHARE_DIR + "bootstrap-template.ldif", self.sub_dict) + inf_fd = write_tmp_file(txt) + logging.debug("adding default ds layout") + args = ["/usr/bin/ldapmodify", "-xv", "-D", "cn=Directory Manager", + "-w", self.admin_password, "-f", inf_fd.name] + run(args) + logging.debug("done adding default ds layout") diff --git a/ipa-server/ipaserver/ipaldap.py b/ipa-server/ipaserver/ipaldap.py new file mode 100644 index 000000000..f440ae4bb --- /dev/null +++ b/ipa-server/ipaserver/ipaldap.py @@ -0,0 +1,395 @@ +#! /usr/bin/python -E +# Authors: Rich Megginson <richm@redhat.com> +# Rob Crittenden <rcritten2redhat.com +# +# Copyright (C) 2007 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; version 2 or later +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +import sys +import os +import os.path +import popen2 +import base64 +import urllib +import urllib2 +import socket +import ldif +import re +import ldap +import cStringIO +import time +import operator + +from ldap.ldapobject import SimpleLDAPObject + +class Error(Exception): pass +class InvalidArgumentError(Error): + def __init__(self,message): self.message = message + def __repr__(self): return message +class NoSuchEntryError(Error): + def __init__(self,message): self.message = message + def __repr__(self): return message + +class Entry: + """This class represents an LDAP Entry object. An LDAP entry consists of a DN + and a list of attributes. Each attribute consists of a name and a list of + values. In python-ldap, entries are returned as a list of 2-tuples. + Instance variables: + dn - string - the string DN of the entry + data - cidict - case insensitive dict of the attributes and values""" + + def __init__(self,entrydata): + """data is the raw data returned from the python-ldap result method, which is + a search result entry or a reference or None. + If creating a new empty entry, data is the string DN.""" + if entrydata: + if isinstance(entrydata,tuple): + self.dn = entrydata[0] + self.data = ldap.cidict.cidict(entrydata[1]) + elif isinstance(entrydata,str): + self.dn = entrydata + self.data = ldap.cidict.cidict() + else: + self.dn = '' + self.data = ldap.cidict.cidict() + + def __nonzero__(self): + """This allows us to do tests like if entry: returns false if there is no data, + true otherwise""" + return self.data != None and len(self.data) > 0 + + def hasAttr(self,name): + """Return True if this entry has an attribute named name, False otherwise""" + return self.data and self.data.has_key(name) + + def __getattr__(self,name): + """If name is the name of an LDAP attribute, return the first value for that + attribute - equivalent to getValue - this allows the use of + entry.cn + instead of + entry.getValue('cn') + This also allows us to return None if an attribute is not found rather than + throwing an exception""" + return self.getValue(name) + + def getValues(self,name): + """Get the list (array) of values for the attribute named name""" + return self.data.get(name) + + def getValue(self,name): + """Get the first value for the attribute named name""" + return self.data.get(name,[None])[0] + + def setValue(self,name,*value): + """Value passed in may be a single value, several values, or a single sequence. + For example: + ent.setValue('name', 'value') + ent.setValue('name', 'value1', 'value2', ..., 'valueN') + ent.setValue('name', ['value1', 'value2', ..., 'valueN']) + ent.setValue('name', ('value1', 'value2', ..., 'valueN')) + Since *value is a tuple, we may have to extract a list or tuple from that + tuple as in the last two examples above""" + if isinstance(value[0],list) or isinstance(value[0],tuple): + self.data[name] = value[0] + else: + self.data[name] = value + + setValues = setValue + + def toTupleList(self): + """Convert the attrs and values to a list of 2-tuples. The first element + of the tuple is the attribute name. The second element is either a + single value or a list of values.""" + return self.data.items() + + def __str__(self): + """Convert the Entry to its LDIF representation""" + return self.__repr__() + + # the ldif class base64 encodes some attrs which I would rather see in raw form - to + # encode specific attrs as base64, add them to the list below + ldif.safe_string_re = re.compile('^$') + base64_attrs = ['nsstate', 'krbprincipalkey', 'krbExtraData'] + + def __repr__(self): + """Convert the Entry to its LDIF representation""" + sio = cStringIO.StringIO() + # what's all this then? the unparse method will currently only accept + # a list or a dict, not a class derived from them. self.data is a + # cidict, so unparse barfs on it. I've filed a bug against python-ldap, + # but in the meantime, we have to convert to a plain old dict for printing + # I also don't want to see wrapping, so set the line width really high (1000) + newdata = {} + newdata.update(self.data) + ldif.LDIFWriter(sio,Entry.base64_attrs,1000).unparse(self.dn,newdata) + return sio.getvalue() + +def wrapper(f,name): + """This is the method that wraps all of the methods of the superclass. This seems + to need to be an unbound method, that's why it's outside of IPAdmin. Perhaps there + is some way to do this with the new classmethod or staticmethod of 2.4. + Basically, we replace every call to a method in SimpleLDAPObject (the superclass + of IPAdmin) with a call to inner. The f argument to wrapper is the bound method + of IPAdmin (which is inherited from the superclass). Bound means that it will implicitly + be called with the self argument, it is not in the args list. name is the name of + the method to call. If name is a method that returns entry objects (e.g. result), + we wrap the data returned by an Entry class. If name is a method that takes an entry + argument, we extract the raw data from the entry object to pass in.""" + def inner(*args, **kargs): + if name == 'result': + type, data = f(*args, **kargs) + # data is either a 2-tuple or a list of 2-tuples + # print data + if data: + if isinstance(data,tuple): + return type, Entry(data) + elif isinstance(data,list): + return type, [Entry(x) for x in data] + else: + raise TypeError, "unknown data type %s returned by result" % type(data) + else: + return type, data + elif name.startswith('add'): + # the first arg is self + # the second and third arg are the dn and the data to send + # We need to convert the Entry into the format used by + # python-ldap + ent = args[0] + if isinstance(ent,Entry): + return f(ent.dn, ent.toTupleList(), *args[2:]) + else: + return f(*args, **kargs) + else: + return f(*args, **kargs) + return inner + +class IPAdmin(SimpleLDAPObject): + CFGSUFFIX = "o=NetscapeRoot" + DEFAULT_USER_ID = "nobody" + + def __initPart2(self): + if self.binddn and len(self.binddn) and not hasattr(self,'sroot'): + try: + ent = self.getEntry('cn=config', ldap.SCOPE_BASE, '(objectclass=*)', + [ 'nsslapd-instancedir', 'nsslapd-errorlog' ]) + instdir = ent.getValue('nsslapd-instancedir') + self.sroot, self.inst = re.match(r'(.*)[\/]slapd-(\w+)$', instdir).groups() + self.errlog = ent.getValue('nsslapd-errorlog') + except (ldap.INSUFFICIENT_ACCESS, ldap.CONNECT_ERROR, NoSuchEntryError): + pass # usually means +# print "ignored exception" + except ldap.LDAPError, e: + print "caught exception ", e + raise + + def __localinit__(self): + SimpleLDAPObject.__init__(self,'ldap://%s:%d' % (self.host,self.port)) + # see if binddn is a dn or a uid that we need to lookup + if self.binddn and not IPAdmin.is_a_dn(self.binddn): + self.simple_bind("","") # anon + ent = self.getEntry(IPAdmin.CFGSUFFIX, ldap.SCOPE_SUBTREE, + "(uid=%s)" % self.binddn, + ['uid']) + if ent: + self.binddn = ent.dn + else: + print "Error: could not find %s under %s" % (self.binddn, IPAdmin.CFGSUFFIX) + self.simple_bind(self.binddn,self.bindpw) +# self.__initPart2() + + def __init__(self,host,port,binddn,bindpw): + """We just set our instance variables and wrap the methods - the real work is + done in __localinit__ and __initPart2 - these are separated out this way so + that we can call them from places other than instance creation e.g. when + using the start command, we just need to reconnect, not create a new instance""" + self.__wrapmethods() + self.port = port or 389 + self.sslport = 0 + self.host = host + self.binddn = binddn + self.bindpw = bindpw + # see if is local or not + host1 = IPAdmin.getfqdn(host) + host2 = IPAdmin.getfqdn() + self.isLocal = (host1 == host2) + self.suffixes = {} + self.__localinit__() + + def __str__(self): + return self.host + ":" + str(self.port) + + def toLDAPURL(self): + return "ldap://%s:%d/" % (self.host,self.port) + + def getEntry(self,*args): + """This wraps the search function. It is common to just get one entry""" + res = self.search(*args) + type, obj = self.result(res) + if not obj: + raise NoSuchEntryError("no such entry for " + str(args)) + elif isinstance(obj,Entry): + return obj + else: # assume list/tuple + return obj[0] + + def addEntry(self,*args): + """This wraps the add function. It assumes that the entry is already + populated with all of the desired objectclasses and attributes""" + try: + self.add_s(*args) + except ldap.ALREADY_EXISTS: + raise ldap.ALREADY_EXISTS + except ldap.LDAPError, e: + raise e + return "Success" + + def __wrapmethods(self): + """This wraps all methods of SimpleLDAPObject, so that we can intercept + the methods that deal with entries. Instead of using a raw list of tuples + of lists of hashes of arrays as the entry object, we want to wrap entries + in an Entry class that provides some useful methods""" + for name in dir(self.__class__.__bases__[0]): + attr = getattr(self, name) + if callable(attr): + setattr(self, name, wrapper(attr, name)) + + def exportLDIF(self, file, suffix, forrepl=False, verbose=False): + cn = "export" + str(int(time.time())) + dn = "cn=%s, cn=export, cn=tasks, cn=config" % cn + entry = Entry(dn) + entry.setValues('objectclass', 'top', 'extensibleObject') + entry.setValues('cn', cn) + entry.setValues('nsFilename', file) + entry.setValues('nsIncludeSuffix', suffix) + if forrepl: + entry.setValues('nsExportReplica', 'true') + + rc = self.startTaskAndWait(entry, verbose) + + if rc: + if verbose: + print "Error: export task %s for file %s exited with %d" % (cn,file,rc) + else: + if verbose: + print "Export task %s for file %s completed successfully" % (cn,file) + return rc + + def waitForEntry(self, dn, timeout=7200, attr='', quiet=False): + scope = ldap.SCOPE_BASE + filter = "(objectclass=*)" + attrlist = [] + if attr: + filter = "(%s=*)" % attr + attrlist.append(attr) + timeout += int(time.time()) + + if isinstance(dn,Entry): + dn = dn.dn + + # wait for entry and/or attr to show up + if not quiet: + sys.stdout.write("Waiting for %s %s:%s " % (self,dn,attr)) + sys.stdout.flush() + entry = None + while not entry and int(time.time()) < timeout: + try: + entry = self.getEntry(dn, scope, filter, attrlist) + except NoSuchEntryError: pass # found entry, but no attr + except ldap.NO_SUCH_OBJECT: pass # no entry yet + except ldap.LDAPError, e: # badness + print "\nError reading entry", dn, e + break + if not entry: + if not quiet: + sys.stdout.write(".") + sys.stdout.flush() + time.sleep(1) + + if not entry and int(time.time()) > timeout: + print "\nwaitForEntry timeout for %s for %s" % (self,dn) + elif entry and not quiet: + print "\nThe waited for entry is:", entry + else: + print "\nError: could not read entry %s from %s" % (dn,self) + + return entry + + def addSchema(self, attr, val): + dn = "cn=schema" + self.modify_s(dn, [(ldap.MOD_ADD, attr, val)]) + + def addAttr(self, *args): + return self.addSchema('attributeTypes', args) + + def addObjClass(self, *args): + return self.addSchema('objectClasses', args) + + ########################### + # Static methods start here + ########################### + def normalizeDN(dn): + # not great, but will do until we use a newer version of python-ldap + # that has DN utilities + ary = ldap.explode_dn(dn.lower()) + return ",".join(ary) + normalizeDN = staticmethod(normalizeDN) + + def getfqdn(name=''): + return socket.getfqdn(name) + getfqdn = staticmethod(getfqdn) + + def getdomainname(name=''): + fqdn = IPAdmin.getfqdn(name) + index = fqdn.find('.') + if index >= 0: + return fqdn[index+1:] + else: + return fqdn + getdomainname = staticmethod(getdomainname) + + def getdefaultsuffix(name=''): + dm = IPAdmin.getdomainname(name) + if dm: + return "dc=" + dm.replace('.', ', dc=') + else: + return 'dc=localdomain' + getdefaultsuffix = staticmethod(getdefaultsuffix) + + def getnewhost(args): + """One of the arguments to createInstance is newhost. If this is specified, we need + to convert it to the fqdn. If not given, we need to figure out what the fqdn of the + local host is. This method sets newhost in args to the appropriate value and + returns True if newhost is the localhost, False otherwise""" + isLocal = False + if args.has_key('newhost'): + args['newhost'] = IPAdmin.getfqdn(args['newhost']) + myhost = IPAdmin.getfqdn() + if myhost == args['newhost']: + isLocal = True + elif args['newhost'] == 'localhost' or \ + args['newhost'] == 'localhost.localdomain': + isLocal = True + else: + isLocal = True + args['newhost'] = IPAdmin.getfqdn() + return isLocal + getnewhost = staticmethod(getnewhost) + + def is_a_dn(dn): + """Returns True if the given string is a DN, False otherwise.""" + return (dn.find("=") > 0) + is_a_dn = staticmethod(is_a_dn) diff --git a/ipa-server/ipaserver/krbinstance.py b/ipa-server/ipaserver/krbinstance.py new file mode 100644 index 000000000..131eee35a --- /dev/null +++ b/ipa-server/ipaserver/krbinstance.py @@ -0,0 +1,183 @@ +#! /usr/bin/python -E +# Authors: Simo Sorce <ssorce@redhat.com> +# +# Copyright (C) 2007 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; version 2 or later +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +import subprocess +import string +import tempfile +import shutil +import logging +from random import Random +from time import gmtime +import os +import pwd +import socket + +SHARE_DIR = "/usr/share/ipa/" + +def realm_to_suffix(realm_name): + s = realm_name.split(".") + terms = ["dc=" + x.lower() for x in s] + return ",".join(terms) + +def host_to_domain(fqdn): + s = fqdn.split(".") + return ".".join(s[1:]) + +def generate_kdc_password(): + rndpwd = '' + r = Random() + r.seed(gmtime()) + for x in range(12): +# rndpwd += chr(r.randint(32,126)) + rndpwd += chr(r.randint(65,90)) #stricter set for testing + return rndpwd + +def ldap_mod(fd, dn, pwd): + args = ["/usr/bin/ldapmodify", "-h", "127.0.0.1", "-xv", "-D", dn, "-w", pwd, "-f", fd.name] + run(args) + +class KrbInstance: + def __init__(self): + self.ds_user = None + self.fqdn = None + self.realm = None + self.domain = None + self.host = None + self.admin_password = None + self.master_password = None + self.suffix = None + self.kdc_password = None + self.sub_dict = None + + def create_instance(self, ds_user, realm_name, host_name, admin_password, master_password): + self.ds_user = ds_user + self.fqdn = host_name + self.ip = socket.gethostbyname(host_name) + self.realm = realm_name.upper() + self.host = host_name.split(".")[0] + self.domain = host_to_domain(host_name) + self.admin_password = admin_password + self.master_password = master_password + + self.suffix = realm_to_suffix(self.realm) + self.kdc_password = generate_kdc_password() + self.__configure_kdc_account_password() + + self.__setup_sub_dict() + + self.__configure_ldap() + + self.__create_instance() + + self.__create_ds_keytab() + + self.__create_sample_bind_zone() + + self.start() + + def stop(self): + run(["/sbin/service", "krb5kdc", "stop"]) + + def start(self): + run(["/sbin/service", "krb5kdc", "start"]) + + def restart(self): + run(["/sbin/service", "krb5kdc", "restart"]) + + def __configure_kdc_account_password(self): + hexpwd = '' + for x in self.kdc_password: + hexpwd += (hex(ord(x))[2:]) + pwd_fd = open("/var/kerberos/krb5kdc/ldappwd", "a+") + pwd_fd.write("uid=kdc,cn=kerberos,"+self.suffix+"#{HEX}"+hexpwd+"\n") + pwd_fd.close() + + def __setup_sub_dict(self): + self.sub_dict = dict(FQDN=self.fqdn, + IP=self.ip, + PASSWORD=self.kdc_password, + SUFFIX=self.suffix, + DOMAIN=self.domain, + HOST=self.host, + REALM=self.realm) + + def __configure_ldap(self): + + #TODO: test that the ldif is ok with any random charcter we may use in the password + kerberos_txt = template_file(SHARE_DIR + "kerberos.ldif", self.sub_dict) + kerberos_fd = write_tmp_file(kerberos_txt) + ldap_mod(kerberos_fd, "cn=Directory Manager", self.admin_password) + kerberos_fd.close() + + #Change the default ACL to avoid anonimous access to kerberos keys and othe hashes + aci_txt = template_file(SHARE_DIR + "default-aci.ldif", self.sub_dict) + aci_fd = write_tmp_file(aci_txt) + ldap_mod(aci_fd, "cn=Directory Manager", self.admin_password) + aci_fd.close() + + def __create_instance(self): + kdc_conf = template_file(SHARE_DIR+"kdc.conf.template", self.sub_dict) + kdc_fd = open("/var/kerberos/krb5kdc/kdc.conf", "w+") + kdc_fd.write(kdc_conf) + kdc_fd.close() + + krb5_conf = template_file(SHARE_DIR+"krb5.conf.template", self.sub_dict) + krb5_fd = open("/etc/krb5.conf", "w+") + krb5_fd.write(krb5_conf) + krb5_fd.close() + + #populate the directory with the realm structure + args = ["/usr/kerberos/sbin/kdb5_ldap_util", "-D", "uid=kdc,cn=kerberos,"+self.suffix, "-w", self.kdc_password, "create", "-s", "-P", self.master_password, "-r", self.realm, "-subtrees", self.suffix, "-sscope", "sub"] + run(args) + + # TODO: NOT called yet, need to find out how to make sure the plugin is available first + def __add_pwd_extop_module(self): + #add the password extop module + extop_txt = template_file(SHARE_DIR + "ipapwd_extop_plugin.ldif", self.sub_dict) + extop_fd = write_tmp_file(extop_txt) + ldap_mod(extop_fd, "cn=Directory Manager", self.admin_password) + extop_fd.close() + + #add an ACL to let the DS user read the master key + args = ["/usr/bin/setfacl", "-m", "u:"+self.ds_user+":r", "/var/kerberos/krb5kdc/.k5."+self.realm] + run(args) + + def __create_sample_bind_zone(self): + bind_txt = template_file(SHARE_DIR + "bind.zone.db.template", self.sub_dict) + [bind_fd, bind_name] = tempfile.mkstemp(".db","sammple.zone.") + os.write(bind_fd, bind_txt) + os.close(bind_fd) + print "Sample zone file for bind has been created in "+bind_name + + def __create_ds_keytab(self): + (kwrite, kread, kerr) = os.popen3("/usr/kerberos/sbin/kadmin.local") + kwrite.write("addprinc -randkey ldap/"+self.fqdn+"@"+self.realm+"\n") + kwrite.flush() + kwrite.write("ktadd -k /etc/fedora-ds/ds.keytab ldap/"+self.fqdn+"@"+self.realm+"\n") + kwrite.flush() + kwrite.close() + kread.close() + kerr.close() + + cfg_fd = open("/etc/sysconfig/fedora-ds", "a") + cfg_fd.write("export KRB5_KTNAME=/etc/fedora-ds/ds.keytab\n") + cfg_fd.close() + pent = pwd.getpwnam(self.ds_user) + os.chown("/etc/sysconfig/fedora-ds", pent.pw_uid, pent.pw_gid) diff --git a/ipa-server/ipaserver/util.py b/ipa-server/ipaserver/util.py new file mode 100644 index 000000000..2f677dad5 --- /dev/null +++ b/ipa-server/ipaserver/util.py @@ -0,0 +1,80 @@ +#! /usr/bin/python -E +# Authors: Simo Sorce <ssorce@redhat.com> +# +# Copyright (C) 2007 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; version 2 or later +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +SHARE_DIR = "/usr/share/ipa/" + +import string +import tempfile +import logging +import subprocess +import os +import stat + +def realm_to_suffix(realm_name): + s = realm_name.split(".") + terms = ["dc=" + x.lower() for x in s] + return ",".join(terms) + + +def template_str(txt, vars): + return string.Template(txt).substitute(vars) + +def template_file(infilename, vars): + txt = open(infilename).read() + return template_str(txt, vars) + +def write_tmp_file(txt): + fd = tempfile.NamedTemporaryFile() + fd.write(txt) + fd.flush() + + return fd + +def run(args, stdin=None): + p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if stdin: + stdout,stderr = p.communicate(stdin) + else: + stdout,stderr = p.communicate() + logging.info(stdout) + logging.info(stderr) + + if p.returncode != 0: + raise subprocess.CalledProcessError(p.returncode, args[0]) + +def file_exists(filename): + try: + mode = os.stat(filename)[stat.ST_MODE] + if stat.S_ISREG(mode): + return True + else: + return False + except: + return False + +def dir_exists(filename): + try: + mode = os.stat(filename)[stat.ST_MODE] + if stat.S_ISDIR(mode): + return True + else: + return False + except: + return False diff --git a/ipa-server/xmlrpc-server/Makefile b/ipa-server/xmlrpc-server/Makefile new file mode 100644 index 000000000..10b796ea6 --- /dev/null +++ b/ipa-server/xmlrpc-server/Makefile @@ -0,0 +1,12 @@ +SHAREDIR = $(DESTDIR)/usr/share/ipa/ipaserver +HTTPDIR = $(DESTDIR)/etc/httpd/conf.d/ + +all: ; + +install: + -mkdir -p $(SHAREDIR) + install -m 644 *.py $(SHAREDIR) + install -m 644 ipa.conf $(HTTPDIR) + +clean: + rm -f *~ *.pyc diff --git a/ipa-server/xmlrpc-server/README b/ipa-server/xmlrpc-server/README new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/ipa-server/xmlrpc-server/README diff --git a/ipa-server/xmlrpc-server/funcs.py b/ipa-server/xmlrpc-server/funcs.py new file mode 100644 index 000000000..d6473f9a7 --- /dev/null +++ b/ipa-server/xmlrpc-server/funcs.py @@ -0,0 +1,170 @@ +# Authors: Rob Crittenden <rcritten@redhat.com> +# +# Copyright (C) 2007 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; version 2 only +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +import sys +sys.path.append("/usr/share/ipa") + +import ldap +import ipaserver.dsinstance +import ipaserver.ipaldap +import pdb +import string +from types import * +import xmlrpclib + +# FIXME, this needs to be auto-discovered +host = 'localhost' +port = 389 +binddn = "cn=directory manager" +bindpw = "freeipa" + +basedn = "dc=greyoak,dc=com" +scope = ldap.SCOPE_SUBTREE + +def get_user (username): + """Get a specific user's entry. Return as a dict of values. + Multi-valued fields are represented as lists. + """ + ent="" + + # FIXME: Is this the filter we want or should it be more specific? + filter = "(uid=" + username + ")" + try: + m1 = ipaserver.ipaldap.IPAdmin(host,port,binddn,bindpw) + ent = m1.getEntry(basedn, scope, filter, None) + except ldap.LDAPError, e: + raise xmlrpclib.Fault(1, e) + except ipaserver.ipaldap.NoSuchEntryError: + raise xmlrpclib.Fault(2, "No such user") + + # Convert to LDIF + entry = str(ent) + + # Strip off any junk + entry = entry.strip() + + # Don't need to identify binary fields and this breaks the parser so + # remove double colons + entry = entry.replace('::', ':') + specs = [spec.split(':') for spec in entry.split('\n')] + + # Convert into a dict. We need to handle multi-valued attributes as well + # so we'll convert those into lists. + user={} + for (k,v) in specs: + k = k.lower() + if user.get(k) is not None: + if isinstance(user[k],list): + user[k].append(v.strip()) + else: + first = user[k] + user[k] = [] + user[k].append(first) + user[k].append(v.strip()) + else: + user[k] = v.strip() + + return user +# return str(ent) # return as LDIF + +def add_user (user): + """Add a user in LDAP""" + dn="uid=%s,ou=users,ou=default,dc=greyoak,dc=com" % user['uid'] + entry = ipaserver.ipaldap.Entry(dn) + + # some required objectclasses + entry.setValues('objectClass', 'top', 'posixAccount', 'shadowAccount', 'account', 'person', 'inetOrgPerson', 'organizationalPerson', 'krbPrincipalAux', 'krbTicketPolicyAux') + + # Fill in shadow fields + entry.setValue('shadowMin', '0') + entry.setValue('shadowMax', '99999') + entry.setValue('shadowWarning', '7') + entry.setValue('shadowExpire', '-1') + entry.setValue('shadowInactive', '-1') + entry.setValue('shadowFlag', '-1') + + # FIXME: calculate shadowLastChange + + # fill in our new entry with everything sent by the user + for u in user: + entry.setValues(u, user[u]) + + try: + m1 = ipaserver.ipaldap.IPAdmin(host,port,binddn,bindpw) + res = m1.addEntry(entry) + return res + except ldap.ALREADY_EXISTS: + raise xmlrpclib.Fault(3, "User already exists") + return None + except ldap.LDAPError, e: + raise xmlrpclib.Fault(1, str(e)) + return None + +def get_add_schema (): + """Get the list of fields to be used when adding users in the GUI.""" + + # FIXME: this needs to be pulled from LDAP + fields = [] + + field1 = { + "name": "uid" , + "label": "Login:", + "type": "text", + "validator": "text", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "userPassword" , + "label": "Password:", + "type": "password", + "validator": "String", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "gn" , + "label": "First name:", + "type": "text", + "validator": "string", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "sn" , + "label": "Last name:", + "type": "text", + "validator": "string", + "required": "true" + } + fields.append(field1) + + field1 = { + "name": "mail" , + "label": "E-mail address:", + "type": "text", + "validator": "email", + "required": "true" + } + fields.append(field1) + + return fields diff --git a/ipa-server/xmlrpc-server/ipa.conf b/ipa-server/xmlrpc-server/ipa.conf new file mode 100644 index 000000000..1880268cf --- /dev/null +++ b/ipa-server/xmlrpc-server/ipa.conf @@ -0,0 +1,24 @@ +# LoadModule auth_kerb_module modules/mod_auth_kerb.so + +Alias /ipa "/usr/share/ipa/ipaserver/XMLRPC" + +<Directory "/usr/share/ipa/ipaserver"> +# AuthType Kerberos +# AuthName "Kerberos Login" +# KrbMethodNegotiate on +# KrbMethodK5Passwd off +# KrbServiceName HTTP +# KrbAuthRealms GREYOAK.COM +# Krb5KeyTab /etc/httpd/conf/ipa.keytab +# KrbSaveCredentials on +# Require valid-user + ErrorDocument 401 /errors/unauthorized.html + + SetHandler mod_python + PythonHandler ipaxmlrpc + + PythonDebug Off + + # this is pointless to use since it would just reload ipaxmlrpc.py + PythonAutoReload Off +</Directory> diff --git a/ipa-server/xmlrpc-server/ipaxmlrpc.py b/ipa-server/xmlrpc-server/ipaxmlrpc.py new file mode 100644 index 000000000..ad5e30683 --- /dev/null +++ b/ipa-server/xmlrpc-server/ipaxmlrpc.py @@ -0,0 +1,277 @@ +# mod_python script + +# ipaxmlrpc - an XMLRPC interface for ipa. +# Copyright (c) 2007 Red Hat +# +# IPA is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; +# version 2.1 of the License. +# +# This software 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this software; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +# +# Based on kojixmlrpc - an XMLRPC interface for koji by +# Mike McLean <mikem@redhat.com> +# +# Authors: +# Rob Crittenden <rcritten@redhat.com> + +import sys +sys.path.append("/usr/share/ipa") + + +import time +import traceback +import pprint +from xmlrpclib import Marshaller,loads,dumps,Fault +from mod_python import apache + +import ipaserver +import funcs +import string +import base64 + +# +# An override so we can base64 encode all outgoing values. +# This is set by calling: Marshaller._Marshaller__dump = xmlrpclib_dump +# +# Not currently used. +# +def xmlrpclib_escape(s, replace = string.replace): + """ + xmlrpclib only handles certain characters. Lets encode the whole + blob + """ + + return base64.encodestring(s) + +def xmlrpclib_dump(self, value, write): + """ + xmlrpclib cannot marshal instances of subclasses of built-in + types. This function overrides xmlrpclib.Marshaller.__dump so that + any value that is an instance of one of its acceptable types is + marshalled as that type. + + xmlrpclib also cannot handle invalid 7-bit control characters. See + above. + """ + + # Use our escape function + args = [self, value, write] + if isinstance(value, (str, unicode)): + args.append(xmlrpclib_escape) + + try: + # Try for an exact match first + f = self.dispatch[type(value)] + except KeyError: + # Try for an isinstance() match + for Type, f in self.dispatch.iteritems(): + if isinstance(value, Type): + f(*args) + return + raise TypeError, "cannot marshal %s objects" % type(value) + else: + f(*args) + + +class ModXMLRPCRequestHandler(object): + """Simple XML-RPC handler for mod_python environment""" + + def __init__(self): + self.funcs = {} + self.traceback = False + #introspection functions + self.register_function(self.list_api, name="_listapi") + self.register_function(self.system_listMethods, name="system.listMethods") + self.register_function(self.system_methodSignature, name="system.methodSignature") + self.register_function(self.system_methodHelp, name="system.methodHelp") + self.register_function(self.multiCall) + + def register_function(self, function, name = None): + if name is None: + name = function.__name__ + self.funcs[name] = function + + def register_module(self, instance, prefix=None): + """Register all the public functions in an instance with prefix prepended + + For example + h.register_module(exports,"pub.sys") + will register the methods of exports with names like + pub.sys.method1 + pub.sys.method2 + ...etc + """ + for name in dir(instance): + if name.startswith('_'): + continue + function = getattr(instance, name) + if not callable(function): + continue + if prefix is not None: + name = "%s.%s" %(prefix,name) + self.register_function(function, name=name) + + def register_instance(self,instance): + self.register_module(instance) + + def _marshaled_dispatch(self, data): + """Dispatches an XML-RPC method from marshalled (XML) data.""" + + params, method = loads(data) + + # special case +# if method == "get_user": +# Marshaller._Marshaller__dump = xmlrpclib_dump + + start = time.time() + # generate response + try: + response = self._dispatch(method, params) + # wrap response in a singleton tuple + response = (response,) + response = dumps(response, methodresponse=1, allow_none=1) + except Fault, fault: + self.traceback = True + response = dumps(fault) + except: + self.traceback = True + # report exception back to server + e_class, e = sys.exc_info()[:2] + faultCode = getattr(e_class,'faultCode',1) + tb_str = ''.join(traceback.format_exception(*sys.exc_info())) + faultString = tb_str + response = dumps(Fault(faultCode, faultString)) + + return response + + def _dispatch(self,method,params): + func = self.funcs.get(method,None) + if func is None: + raise Fault(1, "Invalid method: %s" % method) + params,opts = ipaserver.decode_args(*params) + + ret = func(*params,**opts) + + return ret + + def multiCall(self, calls): + """Execute a multicall. Execute each method call in the calls list, collecting + results and errors, and return those as a list.""" + results = [] + for call in calls: + try: + result = self._dispatch(call['methodName'], call['params']) + except Fault, fault: + results.append({'faultCode': fault.faultCode, 'faultString': fault.faultString}) + except: + # transform unknown exceptions into XML-RPC Faults + # don't create a reference to full traceback since this creates + # a circular reference. + exc_type, exc_value = sys.exc_info()[:2] + faultCode = getattr(exc_type, 'faultCode', 1) + faultString = ', '.join(exc_value.args) + trace = traceback.format_exception(*sys.exc_info()) + # traceback is not part of the multicall spec, but we include it for debugging purposes + results.append({'faultCode': faultCode, 'faultString': faultString, 'traceback': trace}) + else: + results.append([result]) + + return results + + def list_api(self): + funcs = [] + for name,func in self.funcs.items(): + #the keys in self.funcs determine the name of the method as seen over xmlrpc + #func.__name__ might differ (e.g. for dotted method names) + args = self._getFuncArgs(func) + funcs.append({'name': name, + 'doc': func.__doc__, + 'args': args}) + return funcs + + def _getFuncArgs(self, func): + args = [] + for x in range(0, func.func_code.co_argcount): + if x == 0 and func.func_code.co_varnames[x] == "self": + continue + if func.func_defaults and func.func_code.co_argcount - x <= len(func.func_defaults): + args.append((func.func_code.co_varnames[x], func.func_defaults[x - func.func_code.co_argcount + len(func.func_defaults)])) + else: + args.append(func.func_code.co_varnames[x]) + return args + + def system_listMethods(self): + return self.funcs.keys() + + def system_methodSignature(self, method): + #it is not possible to autogenerate this data + return 'signatures not supported' + + def system_methodHelp(self, method): + func = self.funcs.get(method) + if func is None: + return "" + arglist = [] + for arg in self._getFuncArgs(func): + if isinstance(arg,str): + arglist.append(arg) + else: + arglist.append('%s=%s' % (arg[0], arg[1])) + ret = '%s(%s)' % (method, ", ".join(arglist)) + if func.__doc__: + ret += "\ndescription: %s" % func.__doc__ + return ret + + def handle_request(self,req): + """Handle a single XML-RPC request""" + + # XMLRPC uses POST only. Reject anything else + if req.method != 'POST': + req.allow_methods(['POST'],1) + raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED + + response = self._marshaled_dispatch(req.read()) + + req.content_type = "text/xml" + req.set_content_length(len(response)) + req.write(response) + + +# +# mod_python handler +# + +def handler(req, profiling=False): + if profiling: + import profile, pstats, StringIO, tempfile + global _profiling_req + _profiling_req = req + temp = tempfile.NamedTemporaryFile() + profile.run("import ipxmlrpc; ipaxmlrpc.handler(ipaxmlrpc._profiling_req, False)", temp.name) + stats = pstats.Stats(temp.name) + strstream = StringIO.StringIO() + sys.stdout = strstream + stats.sort_stats("time") + stats.print_stats() + req.write("<pre>" + strstream.getvalue() + "</pre>") + _profiling_req = None + else: + opts = req.get_options() + try: + h = ModXMLRPCRequestHandler() + h.register_function(funcs.get_user) + h.register_function(funcs.add_user) + h.register_function(funcs.get_add_schema) + h.handle_request(req) + finally: + pass + return apache.OK |