diff options
Diffstat (limited to 'source4/auth')
75 files changed, 30454 insertions, 0 deletions
diff --git a/source4/auth/auth.h b/source4/auth/auth.h new file mode 100644 index 0000000000..af9ed52f78 --- /dev/null +++ b/source4/auth/auth.h @@ -0,0 +1,256 @@ +/* + Unix SMB/CIFS implementation. + Standardised Authentication types + Copyright (C) Andrew Bartlett 2001 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _SAMBA_AUTH_H +#define _SAMBA_AUTH_H + +#include "librpc/gen_ndr/ndr_krb5pac.h" + +extern const char *user_attrs[]; + +union netr_Validation; +struct netr_SamBaseInfo; +struct netr_SamInfo3; +struct loadparm_context; + +/* modules can use the following to determine if the interface has changed + * please increment the version number after each interface change + * with a comment and maybe update struct auth_critical_sizes. + */ +/* version 1 - version from samba 3.0 - metze */ +/* version 2 - initial samba4 version - metze */ +/* version 3 - subsequent samba4 version - abartlet */ +/* version 4 - subsequent samba4 version - metze */ +/* version 0 - till samba4 is stable - metze */ +#define AUTH_INTERFACE_VERSION 0 + +#define USER_INFO_CASE_INSENSITIVE_USERNAME 0x01 /* username may be in any case */ +#define USER_INFO_CASE_INSENSITIVE_PASSWORD 0x02 /* password may be in any case */ +#define USER_INFO_DONT_CHECK_UNIX_ACCOUNT 0x04 /* dont check unix account status */ +#define USER_INFO_INTERACTIVE_LOGON 0x08 /* dont check unix account status */ + +enum auth_password_state { + AUTH_PASSWORD_RESPONSE, + AUTH_PASSWORD_HASH, + AUTH_PASSWORD_PLAIN +}; + +struct auth_usersupplied_info +{ + const char *workstation_name; + struct socket_address *remote_host; + + uint32_t logon_parameters; + + bool mapped_state; + /* the values the client gives us */ + struct { + const char *account_name; + const char *domain_name; + } client, mapped; + + enum auth_password_state password_state; + + union { + struct { + DATA_BLOB lanman; + DATA_BLOB nt; + } response; + struct { + struct samr_Password *lanman; + struct samr_Password *nt; + } hash; + + char *plaintext; + } password; + uint32_t flags; +}; + +struct auth_serversupplied_info +{ + struct dom_sid *account_sid; + struct dom_sid *primary_group_sid; + + size_t n_domain_groups; + struct dom_sid **domain_groups; + + DATA_BLOB user_session_key; + DATA_BLOB lm_session_key; + + const char *account_name; + const char *domain_name; + + const char *full_name; + const char *logon_script; + const char *profile_path; + const char *home_directory; + const char *home_drive; + const char *logon_server; + + NTTIME last_logon; + NTTIME last_logoff; + NTTIME acct_expiry; + NTTIME last_password_change; + NTTIME allow_password_change; + NTTIME force_password_change; + + uint16_t logon_count; + uint16_t bad_password_count; + + uint32_t acct_flags; + + bool authenticated; + + struct PAC_SIGNATURE_DATA pac_srv_sig, pac_kdc_sig; +}; + +struct auth_method_context; +struct auth_check_password_request; + +struct auth_operations { + const char *name; + + /* If you are using this interface, then you are probably + * getting something wrong. This interface is only for + * security=server, and makes a number of compromises to allow + * that. It is not compatible with being a PDC. */ + + NTSTATUS (*get_challenge)(struct auth_method_context *ctx, TALLOC_CTX *mem_ctx, DATA_BLOB *challenge); + + /* Given the user supplied info, check if this backend want to handle the password checking */ + + NTSTATUS (*want_check)(struct auth_method_context *ctx, TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info); + + /* Given the user supplied info, check a password */ + + NTSTATUS (*check_password)(struct auth_method_context *ctx, TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info); +}; + +struct auth_method_context { + struct auth_method_context *prev, *next; + struct auth_context *auth_ctx; + const struct auth_operations *ops; + int depth; + void *private_data; +}; + +struct auth_context { + struct { + /* Who set this up in the first place? */ + const char *set_by; + + bool may_be_modified; + + DATA_BLOB data; + } challenge; + + /* methods, in the order they should be called */ + struct auth_method_context *methods; + + /* the event context to use for calls that can block */ + struct event_context *event_ctx; + + /* the messaging context which can be used by backends */ + struct messaging_context *msg_ctx; + + /* loadparm context */ + struct loadparm_context *lp_ctx; +}; + +/* this structure is used by backends to determine the size of some critical types */ +struct auth_critical_sizes { + int interface_version; + int sizeof_auth_operations; + int sizeof_auth_methods; + int sizeof_auth_context; + int sizeof_auth_usersupplied_info; + int sizeof_auth_serversupplied_info; +}; + + NTSTATUS encrypt_user_info(TALLOC_CTX *mem_ctx, struct auth_context *auth_context, + enum auth_password_state to_state, + const struct auth_usersupplied_info *user_info_in, + const struct auth_usersupplied_info **user_info_encrypted); + +#include "auth/session.h" +#include "auth/system_session_proto.h" + +struct ldb_message; +struct ldb_context; +NTSTATUS auth_get_challenge(struct auth_context *auth_ctx, const uint8_t **_chal); +NTSTATUS authsam_account_ok(TALLOC_CTX *mem_ctx, + struct ldb_context *sam_ctx, + uint32_t logon_parameters, + struct ldb_message *msg, + struct ldb_message *msg_domain_ref, + const char *logon_workstation, + const char *name_for_logs); +struct auth_session_info *system_session(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx); +NTSTATUS authsam_make_server_info(TALLOC_CTX *mem_ctx, struct ldb_context *sam_ctx, + const char *netbios_name, + struct ldb_message *msg, + struct ldb_message *msg_domain_ref, + DATA_BLOB user_sess_key, DATA_BLOB lm_sess_key, + struct auth_serversupplied_info **_server_info); +NTSTATUS auth_system_session_info(TALLOC_CTX *parent_ctx, + struct loadparm_context *lp_ctx, + struct auth_session_info **_session_info) ; +NTSTATUS auth_nt_status_squash(NTSTATUS nt_status); + +NTSTATUS auth_context_create_methods(TALLOC_CTX *mem_ctx, const char **methods, + struct event_context *ev, + struct messaging_context *msg, + struct loadparm_context *lp_ctx, + struct auth_context **auth_ctx); + +NTSTATUS auth_context_create(TALLOC_CTX *mem_ctx, + struct event_context *ev, + struct messaging_context *msg, + struct loadparm_context *lp_ctx, + struct auth_context **auth_ctx); + +NTSTATUS auth_check_password(struct auth_context *auth_ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info); +NTSTATUS auth_init(void); +NTSTATUS auth_register(const struct auth_operations *ops); +NTSTATUS authenticate_username_pw(TALLOC_CTX *mem_ctx, + struct event_context *ev, + struct messaging_context *msg, + struct loadparm_context *lp_ctx, + const char *nt4_domain, + const char *nt4_username, + const char *password, + struct auth_session_info **session_info); +NTSTATUS auth_check_password_recv(struct auth_check_password_request *req, + TALLOC_CTX *mem_ctx, + struct auth_serversupplied_info **server_info); + +void auth_check_password_send(struct auth_context *auth_ctx, + const struct auth_usersupplied_info *user_info, + void (*callback)(struct auth_check_password_request *req, void *private_data), + void *private_data); +NTSTATUS auth_context_set_challenge(struct auth_context *auth_ctx, const uint8_t chal[8], const char *set_by); + +#endif /* _SMBAUTH_H_ */ diff --git a/source4/auth/auth.i b/source4/auth/auth.i new file mode 100644 index 0000000000..67c8137f67 --- /dev/null +++ b/source4/auth/auth.i @@ -0,0 +1,52 @@ +/* + Unix SMB/CIFS implementation. + Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +%define DOCSTRING +"Authentication and authorization support." +%enddef + +%module(docstring=DOCSTRING,package="samba.auth") auth + +%{ + +/* Include headers */ +#include <stdint.h> +#include <stdbool.h> + +#include "includes.h" +#include "auth/session.h" +#include "auth/system_session_proto.h" +#include "param/param.h" +%} + +%import "carrays.i" +%import "stdint.i" +%import "typemaps.i" +%import "../lib/talloc/talloc.i" +%import "../param/param.i" + +%typemap(default,noblock=1) struct auth_session_info * { + $1 = system_session_anon(NULL, global_loadparm); +} + +%typemap(freearg,noblock=1) struct auth_session_info * { + talloc_free($1); +} + +struct auth_session_info *system_session(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx); +struct auth_session_info *system_session_anon(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx); diff --git a/source4/auth/auth.py b/source4/auth/auth.py new file mode 100644 index 0000000000..226175a75b --- /dev/null +++ b/source4/auth/auth.py @@ -0,0 +1,68 @@ +# This file was automatically generated by SWIG (http://www.swig.org). +# Version 1.3.35 +# +# Don't modify this file, modify the SWIG interface instead. + +""" +Authentication and authorization support. +""" + +import _auth +import new +new_instancemethod = new.instancemethod +try: + _swig_property = property +except NameError: + pass # Python < 2.2 doesn't have 'property'. +def _swig_setattr_nondynamic(self,class_type,name,value,static=1): + if (name == "thisown"): return self.this.own(value) + if (name == "this"): + if type(value).__name__ == 'PySwigObject': + self.__dict__[name] = value + return + method = class_type.__swig_setmethods__.get(name,None) + if method: return method(self,value) + if (not static) or hasattr(self,name): + self.__dict__[name] = value + else: + raise AttributeError("You cannot add attributes to %s" % self) + +def _swig_setattr(self,class_type,name,value): + return _swig_setattr_nondynamic(self,class_type,name,value,0) + +def _swig_getattr(self,class_type,name): + if (name == "thisown"): return self.this.own() + method = class_type.__swig_getmethods__.get(name,None) + if method: return method(self) + raise AttributeError,name + +def _swig_repr(self): + try: strthis = "proxy of " + self.this.__repr__() + except: strthis = "" + return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + +import types +try: + _object = types.ObjectType + _newclass = 1 +except AttributeError: + class _object : pass + _newclass = 0 +del types + + +def _swig_setattr_nondynamic_method(set): + def set_attr(self,name,value): + if (name == "thisown"): return self.this.own(value) + if hasattr(self,name) or (name == "this"): + set(self,name,value) + else: + raise AttributeError("You cannot add attributes to %s" % self) + return set_attr + + +import param +system_session = _auth.system_session +system_session_anon = _auth.system_session_anon + + diff --git a/source4/auth/auth_sam_reply.c b/source4/auth/auth_sam_reply.c new file mode 100644 index 0000000000..ea6f0a1f60 --- /dev/null +++ b/source4/auth/auth_sam_reply.c @@ -0,0 +1,148 @@ +/* + Unix SMB/CIFS implementation. + + Convert a server info struct into the form for PAC and NETLOGON replies + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004 + Copyright (C) Stefan Metzmacher <metze@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "libcli/security/security.h" +#include "librpc/gen_ndr/ndr_netlogon.h" + +NTSTATUS auth_convert_server_info_sambaseinfo(TALLOC_CTX *mem_ctx, + struct auth_serversupplied_info *server_info, + struct netr_SamBaseInfo **_sam) +{ + struct netr_SamBaseInfo *sam = talloc_zero(mem_ctx, struct netr_SamBaseInfo); + NT_STATUS_HAVE_NO_MEMORY(sam); + + sam->domain_sid = dom_sid_dup(mem_ctx, server_info->account_sid); + NT_STATUS_HAVE_NO_MEMORY(sam->domain_sid); + sam->domain_sid->num_auths--; + + sam->last_logon = server_info->last_logon; + sam->last_logoff = server_info->last_logoff; + sam->acct_expiry = server_info->acct_expiry; + sam->last_password_change = server_info->last_password_change; + sam->allow_password_change = server_info->allow_password_change; + sam->force_password_change = server_info->force_password_change; + + sam->account_name.string = server_info->account_name; + sam->full_name.string = server_info->full_name; + sam->logon_script.string = server_info->logon_script; + sam->profile_path.string = server_info->profile_path; + sam->home_directory.string = server_info->home_directory; + sam->home_drive.string = server_info->home_drive; + + sam->logon_count = server_info->logon_count; + sam->bad_password_count = sam->bad_password_count; + sam->rid = server_info->account_sid->sub_auths[server_info->account_sid->num_auths-1]; + sam->primary_gid = server_info->primary_group_sid->sub_auths[server_info->primary_group_sid->num_auths-1]; + + sam->groups.count = 0; + sam->groups.rids = NULL; + + if (server_info->n_domain_groups > 0) { + int i; + sam->groups.rids = talloc_array(sam, struct samr_RidWithAttribute, + server_info->n_domain_groups); + + if (sam->groups.rids == NULL) + return NT_STATUS_NO_MEMORY; + + for (i=0; i<server_info->n_domain_groups; i++) { + struct dom_sid *group_sid = server_info->domain_groups[i]; + if (!dom_sid_in_domain(sam->domain_sid, group_sid)) { + /* We handle this elsewhere */ + continue; + } + sam->groups.rids[sam->groups.count].rid = + group_sid->sub_auths[group_sid->num_auths-1]; + + sam->groups.rids[sam->groups.count].attributes = + SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED; + sam->groups.count += 1; + } + } + + sam->user_flags = 0; /* w2k3 uses NETLOGON_EXTRA_SIDS | NETLOGON_NTLMV2_ENABLED */ + sam->acct_flags = server_info->acct_flags; + sam->logon_server.string = server_info->logon_server; + sam->domain.string = server_info->domain_name; + + ZERO_STRUCT(sam->unknown); + + ZERO_STRUCT(sam->key); + if (server_info->user_session_key.length == sizeof(sam->key.key)) { + memcpy(sam->key.key, server_info->user_session_key.data, sizeof(sam->key.key)); + } + + ZERO_STRUCT(sam->LMSessKey); + if (server_info->lm_session_key.length == sizeof(sam->LMSessKey.key)) { + memcpy(sam->LMSessKey.key, server_info->lm_session_key.data, + sizeof(sam->LMSessKey.key)); + } + + *_sam = sam; + + return NT_STATUS_OK; +} + +NTSTATUS auth_convert_server_info_saminfo3(TALLOC_CTX *mem_ctx, + struct auth_serversupplied_info *server_info, + struct netr_SamInfo3 **_sam3) +{ + struct netr_SamBaseInfo *sam; + struct netr_SamInfo3 *sam3 = talloc_zero(mem_ctx, struct netr_SamInfo3); + NTSTATUS status; + int i; + NT_STATUS_HAVE_NO_MEMORY(sam3); + + status = auth_convert_server_info_sambaseinfo(mem_ctx, server_info, &sam); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + sam3->base = *sam; + sam3->sidcount = 0; + sam3->sids = NULL; + + + sam3->sids = talloc_array(sam, struct netr_SidAttr, + server_info->n_domain_groups); + NT_STATUS_HAVE_NO_MEMORY(sam3->sids); + + for (i=0; i<server_info->n_domain_groups; i++) { + if (dom_sid_in_domain(sam->domain_sid, server_info->domain_groups[i])) { + continue; + } + sam3->sids[sam3->sidcount].sid = talloc_reference(sam3->sids,server_info->domain_groups[i]); + sam3->sids[sam3->sidcount].attributes = + SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED; + sam3->sidcount += 1; + } + if (sam3->sidcount) { + sam3->base.user_flags |= NETLOGON_EXTRA_SIDS; + } else { + sam3->sids = NULL; + } + *_sam3 = sam3; + + return NT_STATUS_OK; +} + diff --git a/source4/auth/auth_wrap.c b/source4/auth/auth_wrap.c new file mode 100644 index 0000000000..dea76ef87d --- /dev/null +++ b/source4/auth/auth_wrap.c @@ -0,0 +1,3216 @@ +/* ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). + * Version 1.3.35 + * + * This file is not intended to be easily readable and contains a number of + * coding conventions designed to improve portability and efficiency. Do not make + * changes to this file unless you know what you are doing--modify the SWIG + * interface file instead. + * ----------------------------------------------------------------------------- */ + +#define SWIGPYTHON +#define SWIG_PYTHON_NO_BUILD_NONE +/* ----------------------------------------------------------------------------- + * This section contains generic SWIG labels for method/variable + * declarations/attributes, and other compiler dependent labels. + * ----------------------------------------------------------------------------- */ + +/* template workaround for compilers that cannot correctly implement the C++ standard */ +#ifndef SWIGTEMPLATEDISAMBIGUATOR +# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) +# define SWIGTEMPLATEDISAMBIGUATOR template +# elif defined(__HP_aCC) +/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ +/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ +# define SWIGTEMPLATEDISAMBIGUATOR template +# else +# define SWIGTEMPLATEDISAMBIGUATOR +# endif +#endif + +/* inline attribute */ +#ifndef SWIGINLINE +# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) +# define SWIGINLINE inline +# else +# define SWIGINLINE +# endif +#endif + +/* attribute recognised by some compilers to avoid 'unused' warnings */ +#ifndef SWIGUNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +# elif defined(__ICC) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +#endif + +#ifndef SWIGUNUSEDPARM +# ifdef __cplusplus +# define SWIGUNUSEDPARM(p) +# else +# define SWIGUNUSEDPARM(p) p SWIGUNUSED +# endif +#endif + +/* internal SWIG method */ +#ifndef SWIGINTERN +# define SWIGINTERN static SWIGUNUSED +#endif + +/* internal inline SWIG method */ +#ifndef SWIGINTERNINLINE +# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE +#endif + +/* exporting methods */ +#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) +# ifndef GCC_HASCLASSVISIBILITY +# define GCC_HASCLASSVISIBILITY +# endif +#endif + +#ifndef SWIGEXPORT +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# if defined(STATIC_LINKED) +# define SWIGEXPORT +# else +# define SWIGEXPORT __declspec(dllexport) +# endif +# else +# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) +# define SWIGEXPORT __attribute__ ((visibility("default"))) +# else +# define SWIGEXPORT +# endif +# endif +#endif + +/* calling conventions for Windows */ +#ifndef SWIGSTDCALL +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# define SWIGSTDCALL __stdcall +# else +# define SWIGSTDCALL +# endif +#endif + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ +#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) +# define _SCL_SECURE_NO_DEPRECATE +#endif + + + +/* Python.h has to appear first */ +#include <Python.h> + +/* ----------------------------------------------------------------------------- + * swigrun.swg + * + * This file contains generic CAPI SWIG runtime support for pointer + * type checking. + * ----------------------------------------------------------------------------- */ + +/* This should only be incremented when either the layout of swig_type_info changes, + or for whatever reason, the runtime changes incompatibly */ +#define SWIG_RUNTIME_VERSION "4" + +/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ +#ifdef SWIG_TYPE_TABLE +# define SWIG_QUOTE_STRING(x) #x +# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) +# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) +#else +# define SWIG_TYPE_TABLE_NAME +#endif + +/* + You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for + creating a static or dynamic library from the swig runtime code. + In 99.9% of the cases, swig just needs to declare them as 'static'. + + But only do this if is strictly necessary, ie, if you have problems + with your compiler or so. +*/ + +#ifndef SWIGRUNTIME +# define SWIGRUNTIME SWIGINTERN +#endif + +#ifndef SWIGRUNTIMEINLINE +# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE +#endif + +/* Generic buffer size */ +#ifndef SWIG_BUFFER_SIZE +# define SWIG_BUFFER_SIZE 1024 +#endif + +/* Flags for pointer conversions */ +#define SWIG_POINTER_DISOWN 0x1 +#define SWIG_CAST_NEW_MEMORY 0x2 + +/* Flags for new pointer objects */ +#define SWIG_POINTER_OWN 0x1 + + +/* + Flags/methods for returning states. + + The swig conversion methods, as ConvertPtr, return and integer + that tells if the conversion was successful or not. And if not, + an error code can be returned (see swigerrors.swg for the codes). + + Use the following macros/flags to set or process the returning + states. + + In old swig versions, you usually write code as: + + if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { + // success code + } else { + //fail code + } + + Now you can be more explicit as: + + int res = SWIG_ConvertPtr(obj,vptr,ty.flags); + if (SWIG_IsOK(res)) { + // success code + } else { + // fail code + } + + that seems to be the same, but now you can also do + + Type *ptr; + int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); + if (SWIG_IsOK(res)) { + // success code + if (SWIG_IsNewObj(res) { + ... + delete *ptr; + } else { + ... + } + } else { + // fail code + } + + I.e., now SWIG_ConvertPtr can return new objects and you can + identify the case and take care of the deallocation. Of course that + requires also to SWIG_ConvertPtr to return new result values, as + + int SWIG_ConvertPtr(obj, ptr,...) { + if (<obj is ok>) { + if (<need new object>) { + *ptr = <ptr to new allocated object>; + return SWIG_NEWOBJ; + } else { + *ptr = <ptr to old object>; + return SWIG_OLDOBJ; + } + } else { + return SWIG_BADOBJ; + } + } + + Of course, returning the plain '0(success)/-1(fail)' still works, but you can be + more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the + swig errors code. + + Finally, if the SWIG_CASTRANK_MODE is enabled, the result code + allows to return the 'cast rank', for example, if you have this + + int food(double) + int fooi(int); + + and you call + + food(1) // cast rank '1' (1 -> 1.0) + fooi(1) // cast rank '0' + + just use the SWIG_AddCast()/SWIG_CheckState() + + + */ +#define SWIG_OK (0) +#define SWIG_ERROR (-1) +#define SWIG_IsOK(r) (r >= 0) +#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) + +/* The CastRankLimit says how many bits are used for the cast rank */ +#define SWIG_CASTRANKLIMIT (1 << 8) +/* The NewMask denotes the object was created (using new/malloc) */ +#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) +/* The TmpMask is for in/out typemaps that use temporal objects */ +#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) +/* Simple returning values */ +#define SWIG_BADOBJ (SWIG_ERROR) +#define SWIG_OLDOBJ (SWIG_OK) +#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) +#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) +/* Check, add and del mask methods */ +#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) +#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) +#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) +#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) +#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) +#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) + + +/* Cast-Rank Mode */ +#if defined(SWIG_CASTRANK_MODE) +# ifndef SWIG_TypeRank +# define SWIG_TypeRank unsigned long +# endif +# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ +# define SWIG_MAXCASTRANK (2) +# endif +# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) +# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) +SWIGINTERNINLINE int SWIG_AddCast(int r) { + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; +} +SWIGINTERNINLINE int SWIG_CheckState(int r) { + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; +} +#else /* no cast-rank mode */ +# define SWIG_AddCast +# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) +#endif + + + + +#include <string.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *(*swig_converter_func)(void *, int *); +typedef struct swig_type_info *(*swig_dycast_func)(void **); + +/* Structure to store information on one type */ +typedef struct swig_type_info { + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ +} swig_type_info; + +/* Structure to store a type and conversion function used for casting */ +typedef struct swig_cast_info { + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ +} swig_cast_info; + +/* Structure used to store module information + * Each module generates one structure like this, and the runtime collects + * all of these structures and stores them in a circularly linked list.*/ +typedef struct swig_module_info { + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ +} swig_module_info; + +/* + Compare two type names skipping the space characters, therefore + "char*" == "char *" and "Class<int>" == "Class<int >", etc. + + Return 0 when the two name types are equivalent, as in + strncmp, but skipping ' '. +*/ +SWIGRUNTIME int +SWIG_TypeNameComp(const char *f1, const char *l1, + const char *f2, const char *l2) { + for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); +} + +/* + Check type equivalence in a name list like <name1>|<name2>|... + Return 0 if not equal, 1 if equal +*/ +SWIGRUNTIME int +SWIG_TypeEquiv(const char *nb, const char *tb) { + int equiv = 0; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) ++ne; + } + return equiv; +} + +/* + Check type equivalence in a name list like <name1>|<name2>|... + Return 0 if equal, -1 if nb < tb, 1 if nb > tb +*/ +SWIGRUNTIME int +SWIG_TypeCompare(const char *nb, const char *tb) { + int equiv = 0; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) ++ne; + } + return equiv; +} + + +/* think of this as a c++ template<> or a scheme macro */ +#define SWIG_TypeCheck_Template(comparison, ty) \ + if (ty) { \ + swig_cast_info *iter = ty->cast; \ + while (iter) { \ + if (comparison) { \ + if (iter == ty->cast) return iter; \ + /* Move iter to the top of the linked list */ \ + iter->prev->next = iter->next; \ + if (iter->next) \ + iter->next->prev = iter->prev; \ + iter->next = ty->cast; \ + iter->prev = 0; \ + if (ty->cast) ty->cast->prev = iter; \ + ty->cast = iter; \ + return iter; \ + } \ + iter = iter->next; \ + } \ + } \ + return 0 + +/* + Check the typename +*/ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheck(const char *c, swig_type_info *ty) { + SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); +} + +/* Same as previous function, except strcmp is replaced with a pointer comparison */ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { + SWIG_TypeCheck_Template(iter->type == from, into); +} + +/* + Cast a pointer up an inheritance hierarchy +*/ +SWIGRUNTIMEINLINE void * +SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); +} + +/* + Dynamic pointer casting. Down an inheritance hierarchy +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; +} + +/* + Return the name associated with this type +*/ +SWIGRUNTIMEINLINE const char * +SWIG_TypeName(const swig_type_info *ty) { + return ty->name; +} + +/* + Return the pretty name associated with this type, + that is an unmangled type name in a form presentable to the user. +*/ +SWIGRUNTIME const char * +SWIG_TypePrettyName(const swig_type_info *type) { + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. We choose + to print the last name, as it is often (?) the most + specific. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s+1; + return last_name; + } + else + return type->name; +} + +/* + Set the clientdata field for a type +*/ +SWIGRUNTIME void +SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; + + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; + } +} +SWIGRUNTIME void +SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; +} + +/* + Search for a swig_type_info structure only by mangled name + Search is a O(log #types) + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_MangledTypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + register size_t l = 0; + register size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + register size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + register int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; +} + +/* + Search for a swig_type_info structure for either a mangled name or a human readable name. + It first searches the mangled names of the types, which is a O(log #types) + If a type is not found it then searches the human readable names, which is O(#types). + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + register size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } + + /* neither found a match */ + return 0; +} + +/* + Pack binary data into a string +*/ +SWIGRUNTIME char * +SWIG_PackData(char *c, void *ptr, size_t sz) { + static const char hex[17] = "0123456789abcdef"; + register const unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; +} + +/* + Unpack binary data from a string +*/ +SWIGRUNTIME const char * +SWIG_UnpackData(const char *c, void *ptr, size_t sz) { + register unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register char d = *(c++); + register unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = ((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = ((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; +} + +/* + Pack 'void *' into a string buffer. +*/ +SWIGRUNTIME char * +SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { + char *r = buff; + if ((2*sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,&ptr,sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r,name); + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sizeof(void *)); +} + +SWIGRUNTIME char * +SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2*sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,ptr,sz); + if (lname) { + strncpy(r,name,lname+1); + } else { + *r = 0; + } + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + memset(ptr,0,sz); + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sz); +} + +#ifdef __cplusplus +} +#endif + +/* Errors in SWIG */ +#define SWIG_UnknownError -1 +#define SWIG_IOError -2 +#define SWIG_RuntimeError -3 +#define SWIG_IndexError -4 +#define SWIG_TypeError -5 +#define SWIG_DivisionByZero -6 +#define SWIG_OverflowError -7 +#define SWIG_SyntaxError -8 +#define SWIG_ValueError -9 +#define SWIG_SystemError -10 +#define SWIG_AttributeError -11 +#define SWIG_MemoryError -12 +#define SWIG_NullReferenceError -13 + + + + +/* Add PyOS_snprintf for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) +# define PyOS_snprintf _snprintf +# else +# define PyOS_snprintf snprintf +# endif +#endif + +/* A crude PyString_FromFormat implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 + +#ifndef SWIG_PYBUFFER_SIZE +# define SWIG_PYBUFFER_SIZE 1024 +#endif + +static PyObject * +PyString_FromFormat(const char *fmt, ...) { + va_list ap; + char buf[SWIG_PYBUFFER_SIZE * 2]; + int res; + va_start(ap, fmt); + res = vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); +} +#endif + +/* Add PyObject_Del for old Pythons */ +#if PY_VERSION_HEX < 0x01060000 +# define PyObject_Del(op) PyMem_DEL((op)) +#endif +#ifndef PyObject_DEL +# define PyObject_DEL PyObject_Del +#endif + +/* A crude PyExc_StopIteration exception for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# ifndef PyExc_StopIteration +# define PyExc_StopIteration PyExc_RuntimeError +# endif +# ifndef PyObject_GenericGetAttr +# define PyObject_GenericGetAttr 0 +# endif +#endif +/* Py_NotImplemented is defined in 2.1 and up. */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef Py_NotImplemented +# define Py_NotImplemented PyExc_RuntimeError +# endif +#endif + + +/* A crude PyString_AsStringAndSize implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef PyString_AsStringAndSize +# define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} +# endif +#endif + +/* PySequence_Size for old Pythons */ +#if PY_VERSION_HEX < 0x02000000 +# ifndef PySequence_Size +# define PySequence_Size PySequence_Length +# endif +#endif + + +/* PyBool_FromLong for old Pythons */ +#if PY_VERSION_HEX < 0x02030000 +static +PyObject *PyBool_FromLong(long ok) +{ + PyObject *result = ok ? Py_True : Py_False; + Py_INCREF(result); + return result; +} +#endif + +/* Py_ssize_t for old Pythons */ +/* This code is as recommended by: */ +/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ +#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) +typedef int Py_ssize_t; +# define PY_SSIZE_T_MAX INT_MAX +# define PY_SSIZE_T_MIN INT_MIN +#endif + +/* ----------------------------------------------------------------------------- + * error manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIME PyObject* +SWIG_Python_ErrorType(int code) { + PyObject* type = 0; + switch(code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; +} + + +SWIGRUNTIME void +SWIG_Python_AddErrorMsg(const char* mesg) +{ + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + + if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyErr_Clear(); + Py_XINCREF(type); + PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); + Py_DECREF(old_str); + Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } +} + + + +#if defined(SWIG_PYTHON_NO_THREADS) +# if defined(SWIG_PYTHON_THREADS) +# undef SWIG_PYTHON_THREADS +# endif +#endif +#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ +# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) +# if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ +# define SWIG_PYTHON_USE_GIL +# endif +# endif +# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ +# ifndef SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() +# endif +# ifdef __cplusplus /* C++ code */ + class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } + }; + class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { PyEval_RestoreThread(save); status = false; }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } + }; +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block +# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow +# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() +# else /* C code */ +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() +# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() +# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) +# endif +# else /* Old thread way, not implemented, user must provide it */ +# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) +# define SWIG_PYTHON_INITIALIZE_THREADS +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) +# define SWIG_PYTHON_THREAD_END_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# endif +# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) +# define SWIG_PYTHON_THREAD_END_ALLOW +# endif +# endif +#else /* No thread support */ +# define SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# define SWIG_PYTHON_THREAD_END_BLOCK +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# define SWIG_PYTHON_THREAD_END_ALLOW +#endif + +/* ----------------------------------------------------------------------------- + * Python API portion that goes into the runtime + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* cc-mode */ +#endif +#endif + +/* ----------------------------------------------------------------------------- + * Constant declarations + * ----------------------------------------------------------------------------- */ + +/* Constant Types */ +#define SWIG_PY_POINTER 4 +#define SWIG_PY_BINARY 5 + +/* Constant information structure */ +typedef struct swig_const_info { + int type; + char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; +} swig_const_info; + +#ifdef __cplusplus +#if 0 +{ /* cc-mode */ +#endif +} +#endif + + +/* ----------------------------------------------------------------------------- + * See the LICENSE file for information on copyright, usage and redistribution + * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * + * pyrun.swg + * + * This file contains the runtime support for Python modules + * and includes code for managing global variables and pointer + * type checking. + * + * ----------------------------------------------------------------------------- */ + +/* Common SWIG API */ + +/* for raw pointers */ +#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) +#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) +#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) +#define swig_owntype int + +/* for raw packed data */ +#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + +/* for class or struct pointers */ +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) + +/* for C or C++ function pointers */ +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) + +/* for C++ member pointers, ie, member methods */ +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + + +/* Runtime API */ + +#define SWIG_GetModule(clientdata) SWIG_Python_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) +#define SWIG_NewClientData(obj) PySwigClientData_New(obj) + +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail + + +/* Runtime API implementation */ + +/* Error manipulation */ + +SWIGINTERN void +SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +SWIGINTERN void +SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, (char *) msg); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) + +/* Set a constant value */ + +SWIGINTERN void +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { + PyDict_SetItemString(d, (char*) name, obj); + Py_DECREF(obj); +} + +/* Append a value to the result obj */ + +SWIGINTERN PyObject* +SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { +#if !defined(SWIG_PYTHON_OUTPUT_TUPLE) + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + PyList_SetItem(result, 0, o2); + } + PyList_Append(result,obj); + Py_DECREF(obj); + } + return result; +#else + PyObject* o2; + PyObject* o3; + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyTuple_Check(result)) { + o2 = result; + result = PyTuple_New(1); + PyTuple_SET_ITEM(result, 0, o2); + } + o3 = PyTuple_New(1); + PyTuple_SET_ITEM(o3, 0, obj); + o2 = result; + result = PySequence_Concat(o2, o3); + Py_DECREF(o2); + Py_DECREF(o3); + } + return result; +#endif +} + +/* Unpack the argument tuple */ + +SWIGINTERN int +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) +{ + if (!args) { + if (!min && !max) { + return 1; + } else { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; + } + } + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; + } else { + register Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + register int i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } +} + +/* A functor is a function object with one single object argument */ +#if PY_VERSION_HEX >= 0x02020000 +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); +#else +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); +#endif + +/* + Helper for static pointer initialization for both C and C++ code, for example + static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); +*/ +#ifdef __cplusplus +#define SWIG_STATIC_POINTER(var) var +#else +#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var +#endif + +/* ----------------------------------------------------------------------------- + * Pointer declarations + * ----------------------------------------------------------------------------- */ + +/* Flags for new pointer objects */ +#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) +#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) + +#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* cc-mode */ +#endif +#endif + +/* How to access Py_None */ +#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# ifndef SWIG_PYTHON_NO_BUILD_NONE +# ifndef SWIG_PYTHON_BUILD_NONE +# define SWIG_PYTHON_BUILD_NONE +# endif +# endif +#endif + +#ifdef SWIG_PYTHON_BUILD_NONE +# ifdef Py_None +# undef Py_None +# define Py_None SWIG_Py_None() +# endif +SWIGRUNTIMEINLINE PyObject * +_SWIG_Py_None(void) +{ + PyObject *none = Py_BuildValue((char*)""); + Py_DECREF(none); + return none; +} +SWIGRUNTIME PyObject * +SWIG_Py_None(void) +{ + static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); + return none; +} +#endif + +/* The python void return value */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) +{ + PyObject *none = Py_None; + Py_INCREF(none); + return none; +} + +/* PySwigClientData */ + +typedef struct { + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; +} PySwigClientData; + +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) +{ + PySwigClientData *data = (PySwigClientData *)ty->clientdata; + return data ? data->implicitconv : 0; +} + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_ExceptionType(swig_type_info *desc) { + PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); +} + + +SWIGRUNTIME PySwigClientData * +PySwigClientData_New(PyObject* obj) +{ + if (!obj) { + return 0; + } else { + PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData)); + /* the klass element */ + data->klass = obj; + Py_INCREF(data->klass); + /* the newraw method and newargs arguments used to create a new raw instance */ + if (PyClass_Check(obj)) { + data->newraw = 0; + data->newargs = obj; + Py_INCREF(obj); + } else { +#if (PY_VERSION_HEX < 0x02020000) + data->newraw = 0; +#else + data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); +#endif + if (data->newraw) { + Py_INCREF(data->newraw); + data->newargs = PyTuple_New(1); + PyTuple_SetItem(data->newargs, 0, obj); + } else { + data->newargs = obj; + } + Py_INCREF(data->newargs); + } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + int flags; + Py_INCREF(data->destroy); + flags = PyCFunction_GET_FLAGS(data->destroy); +#ifdef METH_O + data->delargs = !(flags & (METH_O)); +#else + data->delargs = 0; +#endif + } else { + data->delargs = 0; + } + data->implicitconv = 0; + return data; + } +} + +SWIGRUNTIME void +PySwigClientData_Del(PySwigClientData* data) +{ + Py_XDECREF(data->newraw); + Py_XDECREF(data->newargs); + Py_XDECREF(data->destroy); +} + +/* =============== PySwigObject =====================*/ + +typedef struct { + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; +} PySwigObject; + +SWIGRUNTIME PyObject * +PySwigObject_long(PySwigObject *v) +{ + return PyLong_FromVoidPtr(v->ptr); +} + +SWIGRUNTIME PyObject * +PySwigObject_format(const char* fmt, PySwigObject *v) +{ + PyObject *res = NULL; + PyObject *args = PyTuple_New(1); + if (args) { + if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) { + PyObject *ofmt = PyString_FromString(fmt); + if (ofmt) { + res = PyString_Format(ofmt,args); + Py_DECREF(ofmt); + } + Py_DECREF(args); + } + } + return res; +} + +SWIGRUNTIME PyObject * +PySwigObject_oct(PySwigObject *v) +{ + return PySwigObject_format("%o",v); +} + +SWIGRUNTIME PyObject * +PySwigObject_hex(PySwigObject *v) +{ + return PySwigObject_format("%x",v); +} + +SWIGRUNTIME PyObject * +#ifdef METH_NOARGS +PySwigObject_repr(PySwigObject *v) +#else +PySwigObject_repr(PySwigObject *v, PyObject *args) +#endif +{ + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *hex = PySwigObject_hex(v); + PyObject *repr = PyString_FromFormat("<Swig Object of type '%s' at 0x%s>", name, PyString_AsString(hex)); + Py_DECREF(hex); + if (v->next) { +#ifdef METH_NOARGS + PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next); +#else + PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args); +#endif + PyString_ConcatAndDel(&repr,nrep); + } + return repr; +} + +SWIGRUNTIME int +PySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) +{ +#ifdef METH_NOARGS + PyObject *repr = PySwigObject_repr(v); +#else + PyObject *repr = PySwigObject_repr(v, NULL); +#endif + if (repr) { + fputs(PyString_AsString(repr), fp); + Py_DECREF(repr); + return 0; + } else { + return 1; + } +} + +SWIGRUNTIME PyObject * +PySwigObject_str(PySwigObject *v) +{ + char result[SWIG_BUFFER_SIZE]; + return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? + PyString_FromString(result) : 0; +} + +SWIGRUNTIME int +PySwigObject_compare(PySwigObject *v, PySwigObject *w) +{ + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); +} + +SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); + +SWIGRUNTIME PyTypeObject* +PySwigObject_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); + return type; +} + +SWIGRUNTIMEINLINE int +PySwigObject_Check(PyObject *op) { + return ((op)->ob_type == PySwigObject_type()) + || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0); +} + +SWIGRUNTIME PyObject * +PySwigObject_New(void *ptr, swig_type_info *ty, int own); + +SWIGRUNTIME void +PySwigObject_dealloc(PyObject *v) +{ + PySwigObject *sobj = (PySwigObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; + if (data->delargs) { + /* we need to create a temporal object to carry the destroy operation */ + PyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0); + res = SWIG_Python_CallFunctor(destroy, tmp); + Py_DECREF(tmp); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + Py_XDECREF(res); + } +#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + } +#endif + } + Py_XDECREF(next); + PyObject_DEL(v); +} + +SWIGRUNTIME PyObject* +PySwigObject_append(PyObject* v, PyObject* next) +{ + PySwigObject *sobj = (PySwigObject *) v; +#ifndef METH_O + PyObject *tmp = 0; + if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; + next = tmp; +#endif + if (!PySwigObject_Check(next)) { + return NULL; + } + sobj->next = next; + Py_INCREF(next); + return SWIG_Py_Void(); +} + +SWIGRUNTIME PyObject* +#ifdef METH_NOARGS +PySwigObject_next(PyObject* v) +#else +PySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + PySwigObject *sobj = (PySwigObject *) v; + if (sobj->next) { + Py_INCREF(sobj->next); + return sobj->next; + } else { + return SWIG_Py_Void(); + } +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +PySwigObject_disown(PyObject *v) +#else +PySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + PySwigObject *sobj = (PySwigObject *)v; + sobj->own = 0; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +PySwigObject_acquire(PyObject *v) +#else +PySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + PySwigObject *sobj = (PySwigObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +PySwigObject_own(PyObject *v, PyObject *args) +{ + PyObject *val = 0; +#if (PY_VERSION_HEX < 0x02020000) + if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) +#else + if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) +#endif + { + return NULL; + } + else + { + PySwigObject *sobj = (PySwigObject *)v; + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { +#ifdef METH_NOARGS + if (PyObject_IsTrue(val)) { + PySwigObject_acquire(v); + } else { + PySwigObject_disown(v); + } +#else + if (PyObject_IsTrue(val)) { + PySwigObject_acquire(v,args); + } else { + PySwigObject_disown(v,args); + } +#endif + } + return obj; + } +} + +#ifdef METH_O +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)PySwigObject_append, METH_O, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)PySwigObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_NOARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#else +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)PySwigObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)PySwigObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_VARARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#endif + +#if PY_VERSION_HEX < 0x02020000 +SWIGINTERN PyObject * +PySwigObject_getattr(PySwigObject *sobj,char *name) +{ + return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); +} +#endif + +SWIGRUNTIME PyTypeObject* +_PySwigObject_type(void) { + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; + + static PyNumberMethods PySwigObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + (binaryfunc)0, /*nb_divide*/ + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + (coercion)0, /*nb_coerce*/ + (unaryfunc)PySwigObject_long, /*nb_int*/ + (unaryfunc)PySwigObject_long, /*nb_long*/ + (unaryfunc)0, /*nb_float*/ + (unaryfunc)PySwigObject_oct, /*nb_oct*/ + (unaryfunc)PySwigObject_hex, /*nb_hex*/ +#if PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ +#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ +#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ + 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ +#endif + }; + + static PyTypeObject pyswigobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + (char *)"PySwigObject", /* tp_name */ + sizeof(PySwigObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PySwigObject_dealloc, /* tp_dealloc */ + (printfunc)PySwigObject_print, /* tp_print */ +#if PY_VERSION_HEX < 0x02020000 + (getattrfunc)PySwigObject_getattr, /* tp_getattr */ +#else + (getattrfunc)0, /* tp_getattr */ +#endif + (setattrfunc)0, /* tp_setattr */ + (cmpfunc)PySwigObject_compare, /* tp_compare */ + (reprfunc)PySwigObject_repr, /* tp_repr */ + &PySwigObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)PySwigObject_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + pyswigobject_type = tmp; + pyswigobject_type.ob_type = &PyType_Type; + type_init = 1; + } + return &pyswigobject_type; +} + +SWIGRUNTIME PyObject * +PySwigObject_New(void *ptr, swig_type_info *ty, int own) +{ + PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; + } + return (PyObject *)sobj; +} + +/* ----------------------------------------------------------------------------- + * Implements a simple Swig Packed type, and use it instead of string + * ----------------------------------------------------------------------------- */ + +typedef struct { + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; +} PySwigPacked; + +SWIGRUNTIME int +PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) +{ + char result[SWIG_BUFFER_SIZE]; + fputs("<Swig Packed ", fp); + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + fputs("at ", fp); + fputs(result, fp); + } + fputs(v->ty->name,fp); + fputs(">", fp); + return 0; +} + +SWIGRUNTIME PyObject * +PySwigPacked_repr(PySwigPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name); + } else { + return PyString_FromFormat("<Swig Packed %s>", v->ty->name); + } +} + +SWIGRUNTIME PyObject * +PySwigPacked_str(PySwigPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ + return PyString_FromFormat("%s%s", result, v->ty->name); + } else { + return PyString_FromString(v->ty->name); + } +} + +SWIGRUNTIME int +PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w) +{ + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); +} + +SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); + +SWIGRUNTIME PyTypeObject* +PySwigPacked_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); + return type; +} + +SWIGRUNTIMEINLINE int +PySwigPacked_Check(PyObject *op) { + return ((op)->ob_type == _PySwigPacked_type()) + || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0); +} + +SWIGRUNTIME void +PySwigPacked_dealloc(PyObject *v) +{ + if (PySwigPacked_Check(v)) { + PySwigPacked *sobj = (PySwigPacked *) v; + free(sobj->pack); + } + PyObject_DEL(v); +} + +SWIGRUNTIME PyTypeObject* +_PySwigPacked_type(void) { + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; + static PyTypeObject pyswigpacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + (char *)"PySwigPacked", /* tp_name */ + sizeof(PySwigPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PySwigPacked_dealloc, /* tp_dealloc */ + (printfunc)PySwigPacked_print, /* tp_print */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ + (cmpfunc)PySwigPacked_compare, /* tp_compare */ + (reprfunc)PySwigPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)PySwigPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + pyswigpacked_type = tmp; + pyswigpacked_type.ob_type = &PyType_Type; + type_init = 1; + } + return &pyswigpacked_type; +} + +SWIGRUNTIME PyObject * +PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty) +{ + PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_DEL((PyObject *) sobj); + sobj = 0; + } + } + return (PyObject *) sobj; +} + +SWIGRUNTIME swig_type_info * +PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size) +{ + if (PySwigPacked_Check(obj)) { + PySwigPacked *sobj = (PySwigPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } +} + +/* ----------------------------------------------------------------------------- + * pointers/data manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIMEINLINE PyObject * +_SWIG_This(void) +{ + return PyString_FromString("this"); +} + +SWIGRUNTIME PyObject * +SWIG_This(void) +{ + static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); + return swig_this; +} + +/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ + +SWIGRUNTIME PySwigObject * +SWIG_Python_GetSwigThis(PyObject *pyobj) +{ + if (PySwigObject_Check(pyobj)) { + return (PySwigObject *) pyobj; + } else { + PyObject *obj = 0; +#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); + } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + } else { +#ifdef PyWeakref_CheckProxy + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } +#endif + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } + } + } +#else + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } +#endif + if (obj && !PySwigObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + PySwigObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (PySwigObject *)obj; + } +} + +/* Acquire a pointer value */ + +SWIGRUNTIME int +SWIG_Python_AcquirePtr(PyObject *obj, int own) { + if (own == SWIG_POINTER_OWN) { + PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; + } + } + return 0; +} + +/* Convert a pointer value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { + if (!obj) return SWIG_ERROR; + if (obj == Py_None) { + if (ptr) *ptr = 0; + return SWIG_OK; + } else { + PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) { + sobj = (PySwigObject *)sobj->next; + } else { + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; + } + } + break; + } + } + } else { + if (ptr) *ptr = vptr; + break; + } + } + if (sobj) { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + return SWIG_OK; + } else { + int res = SWIG_ERROR; + if (flags & SWIG_POINTER_IMPLICIT_CONV) { + PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + Py_DECREF(impconv); + } + } + } + } + return res; + } + } +} + +/* Convert a function ptr value */ + +SWIGRUNTIME int +SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); + } else { + void *vptr = 0; + + /* here we get the method pointer for callbacks */ + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) { + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; + if (!desc) return SWIG_ERROR; + } + if (ty) { + swig_cast_info *tc = SWIG_TypeCheck(desc,ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } + } else { + *ptr = vptr; + } + return SWIG_OK; + } +} + +/* Convert a packed value value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; + } + } + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * Create a new pointer object + * ----------------------------------------------------------------------------- */ + +/* + Create a new instance object, whitout calling __init__, and set the + 'this' attribute. +*/ + +SWIGRUNTIME PyObject* +SWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this) +{ +#if (PY_VERSION_HEX >= 0x02020000) + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); + if (inst) { +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + PyDict_SetItem(dict, SWIG_This(), swig_this); + } + } +#else + PyObject *key = SWIG_This(); + PyObject_SetAttr(inst, key, swig_this); +#endif + } + } else { + PyObject *dict = PyDict_New(); + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + } + return inst; +#else +#if (PY_VERSION_HEX >= 0x02010000) + PyObject *inst; + PyObject *dict = PyDict_New(); + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + return (PyObject *) inst; +#else + PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); + if (inst == NULL) { + return NULL; + } + inst->in_class = (PyClassObject *)data->newargs; + Py_INCREF(inst->in_class); + inst->in_dict = PyDict_New(); + if (inst->in_dict == NULL) { + Py_DECREF(inst); + return NULL; + } +#ifdef Py_TPFLAGS_HAVE_WEAKREFS + inst->in_weakreflist = NULL; +#endif +#ifdef Py_TPFLAGS_GC + PyObject_GC_Init(inst); +#endif + PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); + return (PyObject *) inst; +#endif +#endif +} + +SWIGRUNTIME void +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) +{ + PyObject *dict; +#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + PyDict_SetItem(dict, SWIG_This(), swig_this); + return; + } +#endif + dict = PyObject_GetAttrString(inst, (char*)"__dict__"); + PyDict_SetItem(dict, SWIG_This(), swig_this); + Py_DECREF(dict); +} + + +SWIGINTERN PyObject * +SWIG_Python_InitShadowInstance(PyObject *args) { + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { + return NULL; + } else { + PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + PySwigObject_append((PyObject*) sthis, obj[1]); + } else { + SWIG_Python_SetSwigThis(obj[0], obj[1]); + } + return SWIG_Py_Void(); + } +} + +/* Create a new pointer object */ + +SWIGRUNTIME PyObject * +SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { + if (!ptr) { + return SWIG_Py_Void(); + } else { + int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + PyObject *robj = PySwigObject_New(ptr, type, own); + PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0; + if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + if (inst) { + Py_DECREF(robj); + robj = inst; + } + } + return robj; + } +} + +/* Create a new packed object */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { + return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); +} + +/* -----------------------------------------------------------------------------* + * Get type list + * -----------------------------------------------------------------------------*/ + +#ifdef SWIG_LINK_RUNTIME +void *SWIG_ReturnGlobalTypeList(void *); +#endif + +SWIGRUNTIME swig_module_info * +SWIG_Python_GetModule(void) { + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { +#ifdef SWIG_LINK_RUNTIME + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); +#else + type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, + (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } +#endif + } + return (swig_module_info *) type_pointer; +} + +#if PY_MAJOR_VERSION < 2 +/* PyModule_AddObject function was introduced in Python 2.0. The following function + is copied out of Python/modsupport.c in python version 2.3.4 */ +SWIGINTERN int +PyModule_AddObject(PyObject *m, char *name, PyObject *o) +{ + PyObject *dict; + if (!PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs module as first arg"); + return SWIG_ERROR; + } + if (!o) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs non-NULL value"); + return SWIG_ERROR; + } + + dict = PyModule_GetDict(m); + if (dict == NULL) { + /* Internal error -- modules must have a dict! */ + PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", + PyModule_GetName(m)); + return SWIG_ERROR; + } + if (PyDict_SetItemString(dict, name, o)) + return SWIG_ERROR; + Py_DECREF(o); + return SWIG_OK; +} +#endif + +SWIGRUNTIME void +SWIG_Python_DestroyModule(void *vptr) +{ + swig_module_info *swig_module = (swig_module_info *) vptr; + swig_type_info **types = swig_module->types; + size_t i; + for (i =0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + PySwigClientData *data = (PySwigClientData *) ty->clientdata; + if (data) PySwigClientData_Del(data); + } + } + Py_DECREF(SWIG_This()); +} + +SWIGRUNTIME void +SWIG_Python_SetModule(swig_module_info *swig_module) { + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ + + PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, + swig_empty_runtime_method_table); + PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); + if (pointer && module) { + PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); + } else { + Py_XDECREF(pointer); + } +} + +/* The python cached type query */ +SWIGRUNTIME PyObject * +SWIG_Python_TypeCache(void) { + static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); + return cache; +} + +SWIGRUNTIME swig_type_info * +SWIG_Python_TypeQuery(const char *type) +{ + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = PyString_FromString(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { + descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); + } else { + swig_module_info *swig_module = SWIG_Python_GetModule(); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { + obj = PyCObject_FromVoidPtr(descriptor, NULL); + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } + } + Py_DECREF(key); + return descriptor; +} + +/* + For backward compatibility only +*/ +#define SWIG_POINTER_EXCEPTION 0 +#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) +#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) + +SWIGRUNTIME int +SWIG_Python_AddErrMesg(const char* mesg, int infront) +{ + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str)); + } else { + PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); + } + Py_DECREF(old_str); + } + return 1; + } else { + return 0; + } +} + +SWIGRUNTIME int +SWIG_Python_ArgFail(int argnum) +{ + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } +} + +SWIGRUNTIMEINLINE const char * +PySwigObject_GetDesc(PyObject *self) +{ + PySwigObject *v = (PySwigObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : (char*)""; +} + +SWIGRUNTIME void +SWIG_Python_TypeError(const char *type, PyObject *obj) +{ + if (type) { +#if defined(SWIG_COBJECT_TYPES) + if (obj && PySwigObject_Check(obj)) { + const char *otype = (const char *) PySwigObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received", + type, otype); + return; + } + } else +#endif + { + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + const char *cstr = str ? PyString_AsString(str) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + Py_XDECREF(str); + return; + } + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } +} + + +/* Convert a pointer value, signal an exception on a type mismatch */ +SWIGRUNTIME void * +SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); + if (flags & SWIG_POINTER_EXCEPTION) { + SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); + SWIG_Python_ArgFail(argnum); + } + } + return result; +} + + +#ifdef __cplusplus +#if 0 +{ /* cc-mode */ +#endif +} +#endif + + + +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) + +#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else + + + +/* -------- TYPES TABLE (BEGIN) -------- */ + +#define SWIGTYPE_p_TALLOC_CTX swig_types[0] +#define SWIGTYPE_p_auth_session_info swig_types[1] +#define SWIGTYPE_p_char swig_types[2] +#define SWIGTYPE_p_int swig_types[3] +#define SWIGTYPE_p_loadparm_context swig_types[4] +#define SWIGTYPE_p_loadparm_service swig_types[5] +#define SWIGTYPE_p_long_long swig_types[6] +#define SWIGTYPE_p_param_context swig_types[7] +#define SWIGTYPE_p_param_opt swig_types[8] +#define SWIGTYPE_p_param_section swig_types[9] +#define SWIGTYPE_p_short swig_types[10] +#define SWIGTYPE_p_signed_char swig_types[11] +#define SWIGTYPE_p_unsigned_char swig_types[12] +#define SWIGTYPE_p_unsigned_int swig_types[13] +#define SWIGTYPE_p_unsigned_long_long swig_types[14] +#define SWIGTYPE_p_unsigned_short swig_types[15] +static swig_type_info *swig_types[17]; +static swig_module_info swig_module = {swig_types, 16, 0, 0, 0, 0}; +#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) +#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) + +/* -------- TYPES TABLE (END) -------- */ + +#if (PY_VERSION_HEX <= 0x02000000) +# if !defined(SWIG_PYTHON_CLASSIC) +# error "This python version requires swig to be run with the '-classic' option" +# endif +#endif +#if (PY_VERSION_HEX <= 0x02020000) +# error "This python version requires swig to be run with the '-nomodern' option" +#endif +#if (PY_VERSION_HEX <= 0x02020000) +# error "This python version requires swig to be run with the '-nomodernargs' option" +#endif +#ifndef METH_O +# error "This python version requires swig to be run with the '-nofastunpack' option" +#endif +#ifdef SWIG_TypeQuery +# undef SWIG_TypeQuery +#endif +#define SWIG_TypeQuery SWIG_Python_TypeQuery + +/*----------------------------------------------- + @(target):= _auth.so + ------------------------------------------------*/ +#define SWIG_init init_auth + +#define SWIG_name "_auth" + +#define SWIGVERSION 0x010335 +#define SWIG_VERSION SWIGVERSION + + +#define SWIG_as_voidptr(a) (void *)((const void *)(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) + + + +/* Include headers */ +#include <stdint.h> +#include <stdbool.h> + +#include "includes.h" +#include "auth/session.h" +#include "auth/system_session_proto.h" +#include "param/param.h" + +#ifdef __cplusplus +extern "C" { +#endif +SWIGINTERN PyObject *_wrap_system_session(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + TALLOC_CTX *arg1 = (TALLOC_CTX *) 0 ; + struct loadparm_context *arg2 = (struct loadparm_context *) 0 ; + struct auth_session_info *result = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "lp_ctx", NULL + }; + + arg2 = loadparm_init(NULL); + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:system_session",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res2 = SWIG_ConvertPtr(obj0, &argp2,SWIGTYPE_p_loadparm_context, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "system_session" "', argument " "2"" of type '" "struct loadparm_context *""'"); + } + arg2 = (struct loadparm_context *)(argp2); + } + result = (struct auth_session_info *)system_session(arg1,arg2); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_auth_session_info, 0 | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_system_session_anon(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + TALLOC_CTX *arg1 = (TALLOC_CTX *) 0 ; + struct loadparm_context *arg2 = (struct loadparm_context *) 0 ; + struct auth_session_info *result = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "lp_ctx", NULL + }; + + arg2 = loadparm_init(NULL); + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:system_session_anon",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res2 = SWIG_ConvertPtr(obj0, &argp2,SWIGTYPE_p_loadparm_context, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "system_session_anon" "', argument " "2"" of type '" "struct loadparm_context *""'"); + } + arg2 = (struct loadparm_context *)(argp2); + } + result = (struct auth_session_info *)system_session_anon(arg1,arg2); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_auth_session_info, 0 | 0 ); + return resultobj; +fail: + return NULL; +} + + +static PyMethodDef SwigMethods[] = { + { (char *)"system_session", (PyCFunction) _wrap_system_session, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"system_session_anon", (PyCFunction) _wrap_system_session_anon, METH_VARARGS | METH_KEYWORDS, NULL}, + { NULL, NULL, 0, NULL } +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ + +static swig_type_info _swigt__p_TALLOC_CTX = {"_p_TALLOC_CTX", "TALLOC_CTX *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_auth_session_info = {"_p_auth_session_info", "struct auth_session_info *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_int = {"_p_int", "intptr_t *|int *|int_least32_t *|int_fast32_t *|int32_t *|int_fast16_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_loadparm_context = {"_p_loadparm_context", "struct loadparm_context *|loadparm_context *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_loadparm_service = {"_p_loadparm_service", "struct loadparm_service *|loadparm_service *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_long_long = {"_p_long_long", "int_least64_t *|int_fast64_t *|int64_t *|long long *|intmax_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_param_context = {"_p_param_context", "struct param_context *|param *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_param_opt = {"_p_param_opt", "struct param_opt *|param_opt *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_param_section = {"_p_param_section", "struct param_section *|param_section *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_short = {"_p_short", "short *|int_least16_t *|int16_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_signed_char = {"_p_signed_char", "signed char *|int_least8_t *|int_fast8_t *|int8_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_char = {"_p_unsigned_char", "unsigned char *|uint_least8_t *|uint_fast8_t *|uint8_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "uintptr_t *|uint_least32_t *|uint_fast32_t *|uint32_t *|unsigned int *|uint_fast16_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_long_long = {"_p_unsigned_long_long", "uint_least64_t *|uint_fast64_t *|uint64_t *|unsigned long long *|uintmax_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_short = {"_p_unsigned_short", "unsigned short *|uint_least16_t *|uint16_t *", 0, 0, (void*)0, 0}; + +static swig_type_info *swig_type_initial[] = { + &_swigt__p_TALLOC_CTX, + &_swigt__p_auth_session_info, + &_swigt__p_char, + &_swigt__p_int, + &_swigt__p_loadparm_context, + &_swigt__p_loadparm_service, + &_swigt__p_long_long, + &_swigt__p_param_context, + &_swigt__p_param_opt, + &_swigt__p_param_section, + &_swigt__p_short, + &_swigt__p_signed_char, + &_swigt__p_unsigned_char, + &_swigt__p_unsigned_int, + &_swigt__p_unsigned_long_long, + &_swigt__p_unsigned_short, +}; + +static swig_cast_info _swigc__p_TALLOC_CTX[] = { {&_swigt__p_TALLOC_CTX, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_auth_session_info[] = { {&_swigt__p_auth_session_info, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_loadparm_context[] = { {&_swigt__p_loadparm_context, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_loadparm_service[] = { {&_swigt__p_loadparm_service, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_long_long[] = { {&_swigt__p_long_long, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_param_context[] = { {&_swigt__p_param_context, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_param_opt[] = { {&_swigt__p_param_opt, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_param_section[] = { {&_swigt__p_param_section, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_short[] = { {&_swigt__p_short, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_signed_char[] = { {&_swigt__p_signed_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_char[] = { {&_swigt__p_unsigned_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_long_long[] = { {&_swigt__p_unsigned_long_long, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_short[] = { {&_swigt__p_unsigned_short, 0, 0, 0},{0, 0, 0, 0}}; + +static swig_cast_info *swig_cast_initial[] = { + _swigc__p_TALLOC_CTX, + _swigc__p_auth_session_info, + _swigc__p_char, + _swigc__p_int, + _swigc__p_loadparm_context, + _swigc__p_loadparm_service, + _swigc__p_long_long, + _swigc__p_param_context, + _swigc__p_param_opt, + _swigc__p_param_section, + _swigc__p_short, + _swigc__p_signed_char, + _swigc__p_unsigned_char, + _swigc__p_unsigned_int, + _swigc__p_unsigned_long_long, + _swigc__p_unsigned_short, +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ + +static swig_const_info swig_const_table[] = { +{0, 0, 0, 0.0, 0, 0}}; + +#ifdef __cplusplus +} +#endif +/* ----------------------------------------------------------------------------- + * Type initialization: + * This problem is tough by the requirement that no dynamic + * memory is used. Also, since swig_type_info structures store pointers to + * swig_cast_info structures and swig_cast_info structures store pointers back + * to swig_type_info structures, we need some lookup code at initialization. + * The idea is that swig generates all the structures that are needed. + * The runtime then collects these partially filled structures. + * The SWIG_InitializeModule function takes these initial arrays out of + * swig_module, and does all the lookup, filling in the swig_module.types + * array with the correct data and linking the correct swig_cast_info + * structures together. + * + * The generated swig_type_info structures are assigned staticly to an initial + * array. We just loop through that array, and handle each type individually. + * First we lookup if this type has been already loaded, and if so, use the + * loaded structure instead of the generated one. Then we have to fill in the + * cast linked list. The cast data is initially stored in something like a + * two-dimensional array. Each row corresponds to a type (there are the same + * number of rows as there are in the swig_type_initial array). Each entry in + * a column is one of the swig_cast_info structures for that type. + * The cast_initial array is actually an array of arrays, because each row has + * a variable number of columns. So to actually build the cast linked list, + * we find the array of casts associated with the type, and loop through it + * adding the casts to the list. The one last trick we need to do is making + * sure the type pointer in the swig_cast_info struct is correct. + * + * First off, we lookup the cast->type name to see if it is already loaded. + * There are three cases to handle: + * 1) If the cast->type has already been loaded AND the type we are adding + * casting info to has not been loaded (it is in this module), THEN we + * replace the cast->type pointer with the type pointer that has already + * been loaded. + * 2) If BOTH types (the one we are adding casting info to, and the + * cast->type) are loaded, THEN the cast info has already been loaded by + * the previous module so we just ignore it. + * 3) Finally, if cast->type has not already been loaded, then we add that + * swig_cast_info to the linked list (because the cast->type) pointer will + * be correct. + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* c-mode */ +#endif +#endif + +#if 0 +#define SWIGRUNTIME_DEBUG +#endif + + +SWIGRUNTIME void +SWIG_InitializeModule(void *clientdata) { + size_t i; + swig_module_info *module_head, *iter; + int found, init; + + clientdata = clientdata; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next==0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; + } else { + init = 0; + } + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + module_head = &swig_module; + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + found=0; + iter=module_head; + do { + if (iter==&swig_module) { + found=1; + break; + } + iter=iter->next; + } while (iter!= module_head); + + /* if the is found in the list, then all is done and we may leave */ + if (found) return; + /* otherwise we must add out module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpeters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: size %d\n", swig_module.size); +#endif + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } + } else { + type = swig_module.type_initial[i]; + } + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; + } + swig_module.types[i] = 0; + +#ifdef SWIGRUNTIME_DEBUG + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n",j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); +#endif +} + +/* This function will propagate the clientdata field of type to +* any new swig_type_info structures that have been added into the list +* of equivalent types. It is like calling +* SWIG_TypeClientData(type, clientdata) a second time. +*/ +SWIGRUNTIME void +SWIG_PropagateClientData(void) { + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } + } + } +} + +#ifdef __cplusplus +#if 0 +{ + /* c-mode */ +#endif +} +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + + /* Python-specific SWIG API */ +#define SWIG_newvarlink() SWIG_Python_newvarlink() +#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) +#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) + + /* ----------------------------------------------------------------------------- + * global variable support code. + * ----------------------------------------------------------------------------- */ + + typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; + } swig_globalvar; + + typedef struct swig_varlinkobject { + PyObject_HEAD + swig_globalvar *vars; + } swig_varlinkobject; + + SWIGINTERN PyObject * + swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { + return PyString_FromString("<Swig global variables>"); + } + + SWIGINTERN PyObject * + swig_varlink_str(swig_varlinkobject *v) { + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + PyString_ConcatAndDel(&str,PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str,PyString_FromString(")")); + return str; + } + + SWIGINTERN int + swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { + PyObject *str = swig_varlink_str(v); + fprintf(fp,"Swig global variables "); + fprintf(fp,"%s\n", PyString_AsString(str)); + Py_DECREF(str); + return 0; + } + + SWIGINTERN void + swig_varlink_dealloc(swig_varlinkobject *v) { + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } + } + + SWIGINTERN PyObject * + swig_varlink_getattr(swig_varlinkobject *v, char *n) { + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->get_attr)(); + break; + } + var = var->next; + } + if (res == NULL && !PyErr_Occurred()) { + PyErr_SetString(PyExc_NameError,"Unknown C global variable"); + } + return res; + } + + SWIGINTERN int + swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->set_attr)(p); + break; + } + var = var->next; + } + if (res == 1 && !PyErr_Occurred()) { + PyErr_SetString(PyExc_NameError,"Unknown C global variable"); + } + return res; + } + + SWIGINTERN PyTypeObject* + swig_varlink_type(void) { + static char varlink__doc__[] = "Swig var link object"; + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + PyObject_HEAD_INIT(NULL) + 0, /* Number of items in variable part (ob_size) */ + (char *)"swigvarlink", /* Type name (tp_name) */ + sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ + 0, /* Itemsize (tp_itemsize) */ + (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ + (printfunc) swig_varlink_print, /* Print (tp_print) */ + (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ + (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + varlink_type = tmp; + varlink_type.ob_type = &PyType_Type; + type_init = 1; + } + return &varlink_type; + } + + /* Create a variable linking object for use later */ + SWIGINTERN PyObject * + SWIG_Python_newvarlink(void) { + swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject*) result); + } + + SWIGINTERN void + SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name)+1; + gv->name = (char *)malloc(size); + if (gv->name) { + strncpy(gv->name,name,size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; + } + } + v->vars = gv; + } + + SWIGINTERN PyObject * + SWIG_globals(void) { + static PyObject *_SWIG_globals = 0; + if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); + return _SWIG_globals; + } + + /* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + + /* Install Constants */ + SWIGINTERN void + SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + PyObject *obj = 0; + size_t i; + for (i = 0; constants[i].type; ++i) { + switch(constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + Py_DECREF(obj); + } + } + } + + /* -----------------------------------------------------------------------------*/ + /* Fix SwigMethods to carry the callback ptrs when needed */ + /* -----------------------------------------------------------------------------*/ + + SWIGINTERN void + SWIG_Python_FixMethods(PyMethodDef *methods, + swig_const_info *const_table, + swig_type_info **types, + swig_type_info **types_initial) { + size_t i; + for (i = 0; methods[i].ml_name; ++i) { + const char *c = methods[i].ml_doc; + if (c && (c = strstr(c, "swig_ptr: "))) { + int j; + swig_const_info *ci = 0; + const char *name = c + 10; + for (j = 0; const_table[j].type; ++j) { + if (strncmp(const_table[j].name, name, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } + } + if (ci) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; + char *ndoc = (char*)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + strncpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + strncpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } + } + } + } + } + +#ifdef __cplusplus +} +#endif + +/* -----------------------------------------------------------------------------* + * Partial Init method + * -----------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" +#endif +SWIGEXPORT void SWIG_init(void) { + PyObject *m, *d; + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + + m = Py_InitModule((char *) SWIG_name, SwigMethods); + d = PyModule_GetDict(m); + + SWIG_InitializeModule(0); + SWIG_InstallConstants(d,swig_const_table); + + +} + diff --git a/source4/auth/config.m4 b/source4/auth/config.m4 new file mode 100644 index 0000000000..1338b775ec --- /dev/null +++ b/source4/auth/config.m4 @@ -0,0 +1,30 @@ +############################### +# start SMB_EXT_LIB_PAM +# check for security/pam_appl.h and -lpam +AC_CHECK_HEADERS(security/pam_appl.h) +AC_CHECK_LIB_EXT(pam, PAM_LIBS, pam_start) +if test x"$ac_cv_header_security_pam_appl_h" = x"yes" -a x"$ac_cv_lib_ext_pam_pam_start" = x"yes";then + SMB_ENABLE(PAM,YES) +fi +SMB_EXT_LIB(PAM, $PAM_LIBS) +# end SMB_EXT_LIB_PAM +############################### + +################################################ +# test for where we get crypt() from +AC_CHECK_LIB_EXT(crypt, CRYPT_LIBS, crypt) +SMB_ENABLE(CRYPT,YES) +SMB_EXT_LIB(CRYPT, $CRYPT_LIBS) + +AC_CHECK_FUNCS(crypt16 getauthuid getpwanam) + +AC_CHECK_HEADERS(sasl/sasl.h) +AC_CHECK_LIB_EXT(sasl2, SASL_LIBS, sasl_client_init) +SMB_EXT_LIB(SASL, $SASL_LIBS) + +if test x"$ac_cv_header_sasl_sasl_h" = x"yes" -a x"$ac_cv_lib_ext_sasl2_sasl_client_init" = x"yes";then + SMB_ENABLE(SASL,YES) + SMB_ENABLE(cyrus_sasl,YES) +else + SMB_ENABLE(cyrus_sasl,NO) +fi diff --git a/source4/auth/config.mk b/source4/auth/config.mk new file mode 100644 index 0000000000..f13c2e5758 --- /dev/null +++ b/source4/auth/config.mk @@ -0,0 +1,48 @@ +# auth server subsystem +gensecsrcdir := $(authsrcdir)/gensec +mkinclude gensec/config.mk +mkinclude kerberos/config.mk +mkinclude ntlmssp/config.mk +mkinclude ntlm/config.mk +mkinclude credentials/config.mk + +[SUBSYSTEM::auth_session] +PUBLIC_DEPENDENCIES = CREDENTIALS + +PUBLIC_HEADERS += $(authsrcdir)/session.h + +auth_session_OBJ_FILES = $(addprefix $(authsrcdir)/, session.o) + +$(eval $(call proto_header_template,$(authsrcdir)/session_proto.h,$(auth_session_OBJ_FILES:.o=.c))) + +[SUBSYSTEM::auth_system_session] +PUBLIC_DEPENDENCIES = CREDENTIALS +PRIVATE_DEPENDENCIES = auth_session LIBSAMBA-UTIL LIBSECURITY + +auth_system_session_OBJ_FILES = $(addprefix $(authsrcdir)/, system_session.o) +$(eval $(call proto_header_template,$(authsrcdir)/system_session_proto.h,$(auth_system_session_OBJ_FILES:.o=.c))) + +[SUBSYSTEM::auth_sam] +PUBLIC_DEPENDENCIES = SAMDB UTIL_LDB LIBSECURITY +PRIVATE_DEPENDENCIES = LDAP_ENCODE + +auth_sam_OBJ_FILES = $(addprefix $(authsrcdir)/, sam.o) + +$(eval $(call proto_header_template,$(authsrcdir)/auth_sam.h,$(auth_sam_OBJ_FILES:.o=.c))) + +[SUBSYSTEM::auth_sam_reply] + +auth_sam_reply_OBJ_FILES = $(addprefix $(authsrcdir)/, auth_sam_reply.o) + +$(eval $(call proto_header_template,$(authsrcdir)/auth_sam_reply.h,$(auth_sam_reply_OBJ_FILES:.o=.c))) + +[PYTHON::swig_auth] +LIBRARY_REALNAME = samba/_auth.$(SHLIBEXT) +PUBLIC_DEPENDENCIES = auth_system_session +PRIVATE_DEPENDENCIES = SAMDB + +$(eval $(call python_py_module_template,samba/auth.py,$(authsrcdir)/auth.py)) + +swig_auth_OBJ_FILES = $(authsrcdir)/auth_wrap.o + +$(swig_auth_OBJ_FILES): CFLAGS+=$(CFLAG_NO_UNUSED_MACROS) $(CFLAG_NO_CAST_QUAL) diff --git a/source4/auth/credentials/config.mk b/source4/auth/credentials/config.mk new file mode 100644 index 0000000000..2eeeec20ec --- /dev/null +++ b/source4/auth/credentials/config.mk @@ -0,0 +1,24 @@ +################################# +# Start SUBSYSTEM CREDENTIALS +[SUBSYSTEM::CREDENTIALS] +PUBLIC_DEPENDENCIES = \ + LIBCLI_AUTH SECRETS LIBCRYPTO KERBEROS UTIL_LDB HEIMDAL_GSSAPI +PRIVATE_DEPENDENCIES = \ + SECRETS + + +CREDENTIALS_OBJ_FILES = $(addprefix $(authsrcdir)/credentials/, credentials.o credentials_files.o credentials_ntlm.o credentials_krb5.o ../kerberos/kerberos_util.o) + +$(eval $(call proto_header_template,$(authsrcdir)/credentials/credentials_proto.h,$(CREDENTIALS_OBJ_FILES:.o=.c))) + +PUBLIC_HEADERS += $(authsrcdir)/credentials/credentials.h + +[PYTHON::swig_credentials] +LIBRARY_REALNAME = samba/_credentials.$(SHLIBEXT) +PUBLIC_DEPENDENCIES = CREDENTIALS LIBCMDLINE_CREDENTIALS + +$(eval $(call python_py_module_template,samba/credentials.py,$(authsrcdir)/credentials/credentials.py)) + +swig_credentials_OBJ_FILES = $(authsrcdir)/credentials/credentials_wrap.o + +$(swig_credentials_OBJ_FILES): CFLAGS+=$(CFLAG_NO_UNUSED_MACROS) $(CFLAG_NO_CAST_QUAL) diff --git a/source4/auth/credentials/credentials.c b/source4/auth/credentials/credentials.c new file mode 100644 index 0000000000..adabe49cb4 --- /dev/null +++ b/source4/auth/credentials/credentials.c @@ -0,0 +1,760 @@ +/* + Unix SMB/CIFS implementation. + + User credentials handling + + Copyright (C) Jelmer Vernooij 2005 + Copyright (C) Tim Potter 2001 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "librpc/gen_ndr/samr.h" /* for struct samrPassword */ +#include "auth/credentials/credentials.h" +#include "auth/credentials/credentials_krb5.h" +#include "libcli/auth/libcli_auth.h" +#include "lib/events/events.h" +#include "param/param.h" + +/** + * Create a new credentials structure + * @param mem_ctx TALLOC_CTX parent for credentials structure + */ +_PUBLIC_ struct cli_credentials *cli_credentials_init(TALLOC_CTX *mem_ctx) +{ + struct cli_credentials *cred = talloc(mem_ctx, struct cli_credentials); + if (!cred) { + return cred; + } + + cred->netlogon_creds = NULL; + cred->machine_account_pending = false; + cred->workstation_obtained = CRED_UNINITIALISED; + cred->username_obtained = CRED_UNINITIALISED; + cred->password_obtained = CRED_UNINITIALISED; + cred->domain_obtained = CRED_UNINITIALISED; + cred->realm_obtained = CRED_UNINITIALISED; + cred->ccache_obtained = CRED_UNINITIALISED; + cred->client_gss_creds_obtained = CRED_UNINITIALISED; + cred->server_gss_creds_obtained = CRED_UNINITIALISED; + cred->keytab_obtained = CRED_UNINITIALISED; + cred->principal_obtained = CRED_UNINITIALISED; + + cred->ccache_threshold = CRED_UNINITIALISED; + cred->client_gss_creds_threshold = CRED_UNINITIALISED; + + cred->old_password = NULL; + cred->smb_krb5_context = NULL; + cred->salt_principal = NULL; + cred->machine_account = false; + + cred->bind_dn = NULL; + + cred->tries = 3; + cred->callback_running = false; + + cli_credentials_set_kerberos_state(cred, CRED_AUTO_USE_KERBEROS); + cli_credentials_set_gensec_features(cred, 0); + + return cred; +} + +/** + * Create a new anonymous credential + * @param mem_ctx TALLOC_CTX parent for credentials structure + */ +_PUBLIC_ struct cli_credentials *cli_credentials_init_anon(TALLOC_CTX *mem_ctx) +{ + struct cli_credentials *anon_credentials; + + anon_credentials = cli_credentials_init(mem_ctx); + cli_credentials_set_anonymous(anon_credentials); + + return anon_credentials; +} + +_PUBLIC_ void cli_credentials_set_kerberos_state(struct cli_credentials *creds, + enum credentials_use_kerberos use_kerberos) +{ + creds->use_kerberos = use_kerberos; +} + +_PUBLIC_ enum credentials_use_kerberos cli_credentials_get_kerberos_state(struct cli_credentials *creds) +{ + return creds->use_kerberos; +} + +_PUBLIC_ void cli_credentials_set_gensec_features(struct cli_credentials *creds, uint32_t gensec_features) +{ + creds->gensec_features = gensec_features; +} + +_PUBLIC_ uint32_t cli_credentials_get_gensec_features(struct cli_credentials *creds) +{ + return creds->gensec_features; +} + + +/** + * Obtain the username for this credentials context. + * @param cred credentials context + * @retval The username set on this context. + * @note Return value will never be NULL except by programmer error. + */ +_PUBLIC_ const char *cli_credentials_get_username(struct cli_credentials *cred) +{ + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, + cred->machine_account_pending_lp_ctx); + } + + if (cred->username_obtained == CRED_CALLBACK && + !cred->callback_running) { + cred->callback_running = true; + cred->username = cred->username_cb(cred); + cred->callback_running = false; + cred->username_obtained = CRED_SPECIFIED; + cli_credentials_invalidate_ccache(cred, cred->username_obtained); + } + + return cred->username; +} + +_PUBLIC_ bool cli_credentials_set_username(struct cli_credentials *cred, + const char *val, enum credentials_obtained obtained) +{ + if (obtained >= cred->username_obtained) { + cred->username = talloc_strdup(cred, val); + cred->username_obtained = obtained; + cli_credentials_invalidate_ccache(cred, cred->username_obtained); + return true; + } + + return false; +} + +bool cli_credentials_set_username_callback(struct cli_credentials *cred, + const char *(*username_cb) (struct cli_credentials *)) +{ + if (cred->username_obtained < CRED_CALLBACK) { + cred->username_cb = username_cb; + cred->username_obtained = CRED_CALLBACK; + return true; + } + + return false; +} + +_PUBLIC_ bool cli_credentials_set_bind_dn(struct cli_credentials *cred, + const char *bind_dn) +{ + cred->bind_dn = talloc_strdup(cred, bind_dn); + return true; +} + +/** + * Obtain the BIND DN for this credentials context. + * @param cred credentials context + * @retval The username set on this context. + * @note Return value will be NULL if not specified explictly + */ +_PUBLIC_ const char *cli_credentials_get_bind_dn(struct cli_credentials *cred) +{ + return cred->bind_dn; +} + + +/** + * Obtain the client principal for this credentials context. + * @param cred credentials context + * @retval The username set on this context. + * @note Return value will never be NULL except by programmer error. + */ +_PUBLIC_ const char *cli_credentials_get_principal(struct cli_credentials *cred, TALLOC_CTX *mem_ctx) +{ + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, + cred->machine_account_pending_lp_ctx); + } + + if (cred->principal_obtained == CRED_CALLBACK && + !cred->callback_running) { + cred->callback_running = true; + cred->principal = cred->principal_cb(cred); + cred->callback_running = false; + cred->principal_obtained = CRED_SPECIFIED; + cli_credentials_invalidate_ccache(cred, cred->principal_obtained); + } + + if (cred->principal_obtained < cred->username_obtained) { + if (cred->domain_obtained > cred->realm_obtained) { + return talloc_asprintf(mem_ctx, "%s@%s", + cli_credentials_get_username(cred), + cli_credentials_get_domain(cred)); + } else { + return talloc_asprintf(mem_ctx, "%s@%s", + cli_credentials_get_username(cred), + cli_credentials_get_realm(cred)); + } + } + return talloc_reference(mem_ctx, cred->principal); +} + +bool cli_credentials_set_principal(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained) +{ + if (obtained >= cred->principal_obtained) { + cred->principal = talloc_strdup(cred, val); + cred->principal_obtained = obtained; + cli_credentials_invalidate_ccache(cred, cred->principal_obtained); + return true; + } + + return false; +} + +/* Set a callback to get the principal. This could be a popup dialog, + * a terminal prompt or similar. */ +bool cli_credentials_set_principal_callback(struct cli_credentials *cred, + const char *(*principal_cb) (struct cli_credentials *)) +{ + if (cred->principal_obtained < CRED_CALLBACK) { + cred->principal_cb = principal_cb; + cred->principal_obtained = CRED_CALLBACK; + return true; + } + + return false; +} + +/* Some of our tools are 'anonymous by default'. This is a single + * function to determine if authentication has been explicitly + * requested */ + +_PUBLIC_ bool cli_credentials_authentication_requested(struct cli_credentials *cred) +{ + if (cred->bind_dn) { + return true; + } + + if (cli_credentials_is_anonymous(cred)){ + return false; + } + + if (cred->principal_obtained >= CRED_SPECIFIED) { + return true; + } + if (cred->username_obtained >= CRED_SPECIFIED) { + return true; + } + + if (cli_credentials_get_kerberos_state(cred) == CRED_MUST_USE_KERBEROS) { + return true; + } + + return false; +} + +/** + * Obtain the password for this credentials context. + * @param cred credentials context + * @retval If set, the cleartext password, otherwise NULL + */ +_PUBLIC_ const char *cli_credentials_get_password(struct cli_credentials *cred) +{ + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, + cred->machine_account_pending_lp_ctx); + } + + if (cred->password_obtained == CRED_CALLBACK && + !cred->callback_running) { + cred->callback_running = true; + cred->password = cred->password_cb(cred); + cred->callback_running = false; + cred->password_obtained = CRED_CALLBACK_RESULT; + cli_credentials_invalidate_ccache(cred, cred->password_obtained); + } + + return cred->password; +} + +/* Set a password on the credentials context, including an indication + * of 'how' the password was obtained */ + +_PUBLIC_ bool cli_credentials_set_password(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained) +{ + if (obtained >= cred->password_obtained) { + cred->password = talloc_strdup(cred, val); + cred->password_obtained = obtained; + cli_credentials_invalidate_ccache(cred, cred->password_obtained); + + cred->nt_hash = NULL; + cred->lm_response = data_blob(NULL, 0); + cred->nt_response = data_blob(NULL, 0); + return true; + } + + return false; +} + +_PUBLIC_ bool cli_credentials_set_password_callback(struct cli_credentials *cred, + const char *(*password_cb) (struct cli_credentials *)) +{ + if (cred->password_obtained < CRED_CALLBACK) { + cred->password_cb = password_cb; + cred->password_obtained = CRED_CALLBACK; + cli_credentials_invalidate_ccache(cred, cred->password_obtained); + return true; + } + + return false; +} + +/** + * Obtain the 'old' password for this credentials context (used for join accounts). + * @param cred credentials context + * @retval If set, the cleartext password, otherwise NULL + */ +const char *cli_credentials_get_old_password(struct cli_credentials *cred) +{ + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, + cred->machine_account_pending_lp_ctx); + } + + return cred->old_password; +} + +bool cli_credentials_set_old_password(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained) +{ + cred->old_password = talloc_strdup(cred, val); + return true; +} + +/** + * Obtain the password, in the form MD4(unicode(password)) for this credentials context. + * + * Sometimes we only have this much of the password, while the rest of + * the time this call avoids calling E_md4hash themselves. + * + * @param cred credentials context + * @retval If set, the cleartext password, otherwise NULL + */ +_PUBLIC_ const struct samr_Password *cli_credentials_get_nt_hash(struct cli_credentials *cred, + TALLOC_CTX *mem_ctx) +{ + const char *password = cli_credentials_get_password(cred); + + if (password) { + struct samr_Password *nt_hash = talloc(mem_ctx, struct samr_Password); + if (!nt_hash) { + return NULL; + } + + E_md4hash(password, nt_hash->hash); + + return nt_hash; + } else { + return cred->nt_hash; + } +} + +/** + * Obtain the 'short' or 'NetBIOS' domain for this credentials context. + * @param cred credentials context + * @retval The domain set on this context. + * @note Return value will never be NULL except by programmer error. + */ +_PUBLIC_ const char *cli_credentials_get_domain(struct cli_credentials *cred) +{ + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, + cred->machine_account_pending_lp_ctx); + } + + if (cred->domain_obtained == CRED_CALLBACK && + !cred->callback_running) { + cred->callback_running = true; + cred->domain = cred->domain_cb(cred); + cred->callback_running = false; + cred->domain_obtained = CRED_SPECIFIED; + cli_credentials_invalidate_ccache(cred, cred->domain_obtained); + } + + return cred->domain; +} + + +_PUBLIC_ bool cli_credentials_set_domain(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained) +{ + if (obtained >= cred->domain_obtained) { + /* it is important that the domain be in upper case, + * particularly for the sensitive NTLMv2 + * calculations */ + cred->domain = strupper_talloc(cred, val); + cred->domain_obtained = obtained; + cli_credentials_invalidate_ccache(cred, cred->domain_obtained); + return true; + } + + return false; +} + +bool cli_credentials_set_domain_callback(struct cli_credentials *cred, + const char *(*domain_cb) (struct cli_credentials *)) +{ + if (cred->domain_obtained < CRED_CALLBACK) { + cred->domain_cb = domain_cb; + cred->domain_obtained = CRED_CALLBACK; + return true; + } + + return false; +} + +/** + * Obtain the Kerberos realm for this credentials context. + * @param cred credentials context + * @retval The realm set on this context. + * @note Return value will never be NULL except by programmer error. + */ +_PUBLIC_ const char *cli_credentials_get_realm(struct cli_credentials *cred) +{ + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, + cred->machine_account_pending_lp_ctx); + } + + if (cred->realm_obtained == CRED_CALLBACK && + !cred->callback_running) { + cred->callback_running = true; + cred->realm = cred->realm_cb(cred); + cred->callback_running = false; + cred->realm_obtained = CRED_SPECIFIED; + cli_credentials_invalidate_ccache(cred, cred->realm_obtained); + } + + return cred->realm; +} + +/** + * Set the realm for this credentials context, and force it to + * uppercase for the sainity of our local kerberos libraries + */ +_PUBLIC_ bool cli_credentials_set_realm(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained) +{ + if (obtained >= cred->realm_obtained) { + cred->realm = strupper_talloc(cred, val); + cred->realm_obtained = obtained; + cli_credentials_invalidate_ccache(cred, cred->realm_obtained); + return true; + } + + return false; +} + +bool cli_credentials_set_realm_callback(struct cli_credentials *cred, + const char *(*realm_cb) (struct cli_credentials *)) +{ + if (cred->realm_obtained < CRED_CALLBACK) { + cred->realm_cb = realm_cb; + cred->realm_obtained = CRED_CALLBACK; + return true; + } + + return false; +} + +/** + * Obtain the 'short' or 'NetBIOS' workstation name for this credentials context. + * + * @param cred credentials context + * @retval The workstation name set on this context. + * @note Return value will never be NULL except by programmer error. + */ +_PUBLIC_ const char *cli_credentials_get_workstation(struct cli_credentials *cred) +{ + if (cred->workstation_obtained == CRED_CALLBACK && + !cred->callback_running) { + cred->callback_running = true; + cred->workstation = cred->workstation_cb(cred); + cred->callback_running = false; + cred->workstation_obtained = CRED_SPECIFIED; + } + + return cred->workstation; +} + +_PUBLIC_ bool cli_credentials_set_workstation(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained) +{ + if (obtained >= cred->workstation_obtained) { + cred->workstation = talloc_strdup(cred, val); + cred->workstation_obtained = obtained; + return true; + } + + return false; +} + +bool cli_credentials_set_workstation_callback(struct cli_credentials *cred, + const char *(*workstation_cb) (struct cli_credentials *)) +{ + if (cred->workstation_obtained < CRED_CALLBACK) { + cred->workstation_cb = workstation_cb; + cred->workstation_obtained = CRED_CALLBACK; + return true; + } + + return false; +} + +/** + * Given a string, typically obtained from a -U argument, parse it into domain, username, realm and password fields + * + * The format accepted is [domain\\]user[%password] or user[@realm][%password] + * + * @param credentials Credentials structure on which to set the password + * @param data the string containing the username, password etc + * @param obtained This enum describes how 'specified' this password is + */ + +_PUBLIC_ void cli_credentials_parse_string(struct cli_credentials *credentials, const char *data, enum credentials_obtained obtained) +{ + char *uname, *p; + + if (strcmp("%",data) == 0) { + cli_credentials_set_anonymous(credentials); + return; + } + + uname = talloc_strdup(credentials, data); + if ((p = strchr_m(uname,'%'))) { + *p = 0; + cli_credentials_set_password(credentials, p+1, obtained); + } + + if ((p = strchr_m(uname,'@'))) { + cli_credentials_set_principal(credentials, uname, obtained); + *p = 0; + cli_credentials_set_realm(credentials, p+1, obtained); + return; + } else if ((p = strchr_m(uname,'\\')) || (p = strchr_m(uname, '/'))) { + *p = 0; + cli_credentials_set_domain(credentials, uname, obtained); + uname = p+1; + } + cli_credentials_set_username(credentials, uname, obtained); +} + +/** + * Given a a credentials structure, print it as a string + * + * The format output is [domain\\]user[%password] or user[@realm][%password] + * + * @param credentials Credentials structure on which to set the password + * @param mem_ctx The memory context to place the result on + */ + +_PUBLIC_ const char *cli_credentials_get_unparsed_name(struct cli_credentials *credentials, TALLOC_CTX *mem_ctx) +{ + const char *bind_dn = cli_credentials_get_bind_dn(credentials); + const char *domain; + const char *username; + const char *name; + + if (bind_dn) { + name = talloc_reference(mem_ctx, bind_dn); + } else { + cli_credentials_get_ntlm_username_domain(credentials, mem_ctx, &username, &domain); + if (domain && domain[0]) { + name = talloc_asprintf(mem_ctx, "%s\\%s", + domain, username); + } else { + name = talloc_asprintf(mem_ctx, "%s", + username); + } + } + return name; +} + +/** + * Specifies default values for domain, workstation and realm + * from the smb.conf configuration file + * + * @param cred Credentials structure to fill in + */ +_PUBLIC_ void cli_credentials_set_conf(struct cli_credentials *cred, + struct loadparm_context *lp_ctx) +{ + cli_credentials_set_username(cred, "", CRED_UNINITIALISED); + cli_credentials_set_domain(cred, lp_workgroup(lp_ctx), CRED_UNINITIALISED); + cli_credentials_set_workstation(cred, lp_netbios_name(lp_ctx), CRED_UNINITIALISED); + cli_credentials_set_realm(cred, lp_realm(lp_ctx), CRED_UNINITIALISED); +} + +/** + * Guess defaults for credentials from environment variables, + * and from the configuration file + * + * @param cred Credentials structure to fill in + */ +_PUBLIC_ void cli_credentials_guess(struct cli_credentials *cred, + struct loadparm_context *lp_ctx) +{ + char *p; + + if (lp_ctx != NULL) { + cli_credentials_set_conf(cred, lp_ctx); + } + + if (getenv("LOGNAME")) { + cli_credentials_set_username(cred, getenv("LOGNAME"), CRED_GUESS_ENV); + } + + if (getenv("USER")) { + cli_credentials_parse_string(cred, getenv("USER"), CRED_GUESS_ENV); + if ((p = strchr_m(getenv("USER"),'%'))) { + memset(p,0,strlen(cred->password)); + } + } + + if (getenv("PASSWD")) { + cli_credentials_set_password(cred, getenv("PASSWD"), CRED_GUESS_ENV); + } + + if (getenv("PASSWD_FD")) { + cli_credentials_parse_password_fd(cred, atoi(getenv("PASSWD_FD")), + CRED_GUESS_FILE); + } + + p = getenv("PASSWD_FILE"); + if (p && p[0]) { + cli_credentials_parse_password_file(cred, p, CRED_GUESS_FILE); + } + + if (cli_credentials_get_kerberos_state(cred) != CRED_DONT_USE_KERBEROS) { + cli_credentials_set_ccache(cred, event_context_find(cred), lp_ctx, NULL, CRED_GUESS_FILE); + } +} + +/** + * Attach NETLOGON credentials for use with SCHANNEL + */ + +_PUBLIC_ void cli_credentials_set_netlogon_creds(struct cli_credentials *cred, + struct creds_CredentialState *netlogon_creds) +{ + cred->netlogon_creds = talloc_reference(cred, netlogon_creds); +} + +/** + * Return attached NETLOGON credentials + */ + +struct creds_CredentialState *cli_credentials_get_netlogon_creds(struct cli_credentials *cred) +{ + return cred->netlogon_creds; +} + +/** + * Set NETLOGON secure channel type + */ + +_PUBLIC_ void cli_credentials_set_secure_channel_type(struct cli_credentials *cred, + enum netr_SchannelType secure_channel_type) +{ + cred->secure_channel_type = secure_channel_type; +} + +/** + * Return NETLOGON secure chanel type + */ + +_PUBLIC_ enum netr_SchannelType cli_credentials_get_secure_channel_type(struct cli_credentials *cred) +{ + return cred->secure_channel_type; +} + +/** + * Fill in a credentials structure as the anonymous user + */ +_PUBLIC_ void cli_credentials_set_anonymous(struct cli_credentials *cred) +{ + cli_credentials_set_username(cred, "", CRED_SPECIFIED); + cli_credentials_set_domain(cred, "", CRED_SPECIFIED); + cli_credentials_set_password(cred, NULL, CRED_SPECIFIED); + cli_credentials_set_realm(cred, NULL, CRED_SPECIFIED); + cli_credentials_set_workstation(cred, "", CRED_UNINITIALISED); +} + +/** + * Describe a credentials context as anonymous or authenticated + * @retval true if anonymous, false if a username is specified + */ + +_PUBLIC_ bool cli_credentials_is_anonymous(struct cli_credentials *cred) +{ + const char *username; + + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, + cred->machine_account_pending_lp_ctx); + } + + username = cli_credentials_get_username(cred); + + /* Yes, it is deliberate that we die if we have a NULL pointer + * here - anonymous is "", not NULL, which is 'never specified, + * never guessed', ie programmer bug */ + if (!username[0]) { + return true; + } + + return false; +} + +/** + * Mark the current password for a credentials struct as wrong. This will + * cause the password to be prompted again (if a callback is set). + * + * This will decrement the number of times the password can be tried. + * + * @retval whether the credentials struct is finished + */ +_PUBLIC_ bool cli_credentials_wrong_password(struct cli_credentials *cred) +{ + if (cred->password_obtained != CRED_CALLBACK_RESULT) { + return false; + } + + cred->password_obtained = CRED_CALLBACK; + + cred->tries--; + + return (cred->tries > 0); +} diff --git a/source4/auth/credentials/credentials.h b/source4/auth/credentials/credentials.h new file mode 100644 index 0000000000..79c50ae5af --- /dev/null +++ b/source4/auth/credentials/credentials.h @@ -0,0 +1,263 @@ +/* + samba -- Unix SMB/CIFS implementation. + + Client credentials structure + + Copyright (C) Jelmer Vernooij 2004-2006 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ +#ifndef __CREDENTIALS_H__ +#define __CREDENTIALS_H__ + +#include "util/data_blob.h" +#include "librpc/gen_ndr/misc.h" + +struct ccache_container; +struct event_context; + +/* In order of priority */ +enum credentials_obtained { + CRED_UNINITIALISED = 0, /* We don't even have a guess yet */ + CRED_CALLBACK, /* Callback should be used to obtain value */ + CRED_GUESS_ENV, /* Current value should be used, which was guessed */ + CRED_GUESS_FILE, /* A guess from a file (or file pointed at in env variable) */ + CRED_CALLBACK_RESULT, /* Value was obtained from a callback */ + CRED_SPECIFIED /* Was explicitly specified on the command-line */ +}; + +enum credentials_use_kerberos { + CRED_AUTO_USE_KERBEROS = 0, /* Default, we try kerberos if available */ + CRED_DONT_USE_KERBEROS, /* Sometimes trying kerberos just does 'bad things', so don't */ + CRED_MUST_USE_KERBEROS /* Sometimes administrators are parinoid, so always do kerberos */ +}; + +#define CLI_CRED_NTLM2 0x01 +#define CLI_CRED_NTLMv2_AUTH 0x02 +#define CLI_CRED_LANMAN_AUTH 0x04 +#define CLI_CRED_NTLM_AUTH 0x08 +#define CLI_CRED_CLEAR_AUTH 0x10 /* TODO: Push cleartext auth with this flag */ + +struct cli_credentials { + enum credentials_obtained workstation_obtained; + enum credentials_obtained username_obtained; + enum credentials_obtained password_obtained; + enum credentials_obtained domain_obtained; + enum credentials_obtained realm_obtained; + enum credentials_obtained ccache_obtained; + enum credentials_obtained client_gss_creds_obtained; + enum credentials_obtained principal_obtained; + enum credentials_obtained keytab_obtained; + enum credentials_obtained server_gss_creds_obtained; + + /* Threshold values (essentially a MAX() over a number of the + * above) for the ccache and GSS credentials, to ensure we + * regenerate/pick correctly */ + + enum credentials_obtained ccache_threshold; + enum credentials_obtained client_gss_creds_threshold; + + const char *workstation; + const char *username; + const char *password; + const char *old_password; + const char *domain; + const char *realm; + const char *principal; + const char *salt_principal; + + const char *bind_dn; + + /* Allows authentication from a keytab or similar */ + struct samr_Password *nt_hash; + + /* Allows NTLM pass-though authentication */ + DATA_BLOB lm_response; + DATA_BLOB nt_response; + + struct ccache_container *ccache; + struct gssapi_creds_container *client_gss_creds; + struct keytab_container *keytab; + struct gssapi_creds_container *server_gss_creds; + + const char *(*workstation_cb) (struct cli_credentials *); + const char *(*password_cb) (struct cli_credentials *); + const char *(*username_cb) (struct cli_credentials *); + const char *(*domain_cb) (struct cli_credentials *); + const char *(*realm_cb) (struct cli_credentials *); + const char *(*principal_cb) (struct cli_credentials *); + + /* Private handle for the callback routines to use */ + void *priv_data; + + struct creds_CredentialState *netlogon_creds; + enum netr_SchannelType secure_channel_type; + int kvno; + + struct smb_krb5_context *smb_krb5_context; + + /* We are flagged to get machine account details from the + * secrets.ldb when we are asked for a username or password */ + bool machine_account_pending; + struct loadparm_context *machine_account_pending_lp_ctx; + + /* Is this a machine account? */ + bool machine_account; + + /* Should we be trying to use kerberos? */ + enum credentials_use_kerberos use_kerberos; + + /* gensec features which should be used for connections */ + uint32_t gensec_features; + + /* Number of retries left before bailing out */ + int tries; + + /* Whether any callback is currently running */ + bool callback_running; +}; + +struct ldb_context; +struct loadparm_context; +struct ccache_container; + +struct gssapi_creds_container; + +const char *cli_credentials_get_workstation(struct cli_credentials *cred); +bool cli_credentials_set_workstation(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained); +bool cli_credentials_is_anonymous(struct cli_credentials *cred); +struct cli_credentials *cli_credentials_init(TALLOC_CTX *mem_ctx); +void cli_credentials_set_anonymous(struct cli_credentials *cred); +bool cli_credentials_wrong_password(struct cli_credentials *cred); +const char *cli_credentials_get_password(struct cli_credentials *cred); +void cli_credentials_get_ntlm_username_domain(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, + const char **username, + const char **domain); +NTSTATUS cli_credentials_get_ntlm_response(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, + int *flags, + DATA_BLOB challenge, DATA_BLOB target_info, + DATA_BLOB *_lm_response, DATA_BLOB *_nt_response, + DATA_BLOB *_lm_session_key, DATA_BLOB *_session_key); +const char *cli_credentials_get_realm(struct cli_credentials *cred); +const char *cli_credentials_get_username(struct cli_credentials *cred); +int cli_credentials_get_krb5_context(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct smb_krb5_context **smb_krb5_context); +int cli_credentials_get_ccache(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct ccache_container **ccc); +int cli_credentials_get_keytab(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct keytab_container **_ktc); +const char *cli_credentials_get_domain(struct cli_credentials *cred); +struct creds_CredentialState *cli_credentials_get_netlogon_creds(struct cli_credentials *cred); +void cli_credentials_set_machine_account_pending(struct cli_credentials *cred, + struct loadparm_context *lp_ctx); +void cli_credentials_set_conf(struct cli_credentials *cred, + struct loadparm_context *lp_ctx); +const char *cli_credentials_get_principal(struct cli_credentials *cred, TALLOC_CTX *mem_ctx); +int cli_credentials_get_server_gss_creds(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct gssapi_creds_container **_gcc); +int cli_credentials_get_client_gss_creds(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct gssapi_creds_container **_gcc); +void cli_credentials_set_kerberos_state(struct cli_credentials *creds, + enum credentials_use_kerberos use_kerberos); +bool cli_credentials_set_domain(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained); +bool cli_credentials_set_username(struct cli_credentials *cred, + const char *val, enum credentials_obtained obtained); +bool cli_credentials_set_password(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained); +struct cli_credentials *cli_credentials_init_anon(TALLOC_CTX *mem_ctx); +void cli_credentials_parse_string(struct cli_credentials *credentials, const char *data, enum credentials_obtained obtained); +const struct samr_Password *cli_credentials_get_nt_hash(struct cli_credentials *cred, + TALLOC_CTX *mem_ctx); +bool cli_credentials_set_realm(struct cli_credentials *cred, + const char *val, + enum credentials_obtained obtained); +void cli_credentials_set_secure_channel_type(struct cli_credentials *cred, + enum netr_SchannelType secure_channel_type); +void cli_credentials_set_netlogon_creds(struct cli_credentials *cred, + struct creds_CredentialState *netlogon_creds); +NTSTATUS cli_credentials_set_krb5_context(struct cli_credentials *cred, + struct smb_krb5_context *smb_krb5_context); +NTSTATUS cli_credentials_set_stored_principal(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *serviceprincipal); +NTSTATUS cli_credentials_set_machine_account(struct cli_credentials *cred, + struct loadparm_context *lp_ctx); +bool cli_credentials_authentication_requested(struct cli_credentials *cred); +void cli_credentials_guess(struct cli_credentials *cred, + struct loadparm_context *lp_ctx); +bool cli_credentials_set_bind_dn(struct cli_credentials *cred, + const char *bind_dn); +const char *cli_credentials_get_bind_dn(struct cli_credentials *cred); +bool cli_credentials_parse_file(struct cli_credentials *cred, const char *file, enum credentials_obtained obtained); +const char *cli_credentials_get_unparsed_name(struct cli_credentials *credentials, TALLOC_CTX *mem_ctx); +bool cli_credentials_set_password_callback(struct cli_credentials *cred, + const char *(*password_cb) (struct cli_credentials *)); +enum netr_SchannelType cli_credentials_get_secure_channel_type(struct cli_credentials *cred); +void cli_credentials_set_kvno(struct cli_credentials *cred, + int kvno); +bool cli_credentials_set_nt_hash(struct cli_credentials *cred, + const struct samr_Password *nt_hash, + enum credentials_obtained obtained); +bool cli_credentials_set_ntlm_response(struct cli_credentials *cred, + const DATA_BLOB *lm_response, + const DATA_BLOB *nt_response, + enum credentials_obtained obtained); +int cli_credentials_set_keytab_name(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *keytab_name, + enum credentials_obtained obtained); +int cli_credentials_update_keytab(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx); +void cli_credentials_set_gensec_features(struct cli_credentials *creds, uint32_t gensec_features); +uint32_t cli_credentials_get_gensec_features(struct cli_credentials *creds); +int cli_credentials_set_ccache(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *name, + enum credentials_obtained obtained); +bool cli_credentials_parse_password_file(struct cli_credentials *credentials, const char *file, enum credentials_obtained obtained); +bool cli_credentials_parse_password_fd(struct cli_credentials *credentials, + int fd, enum credentials_obtained obtained); +void cli_credentials_invalidate_ccache(struct cli_credentials *cred, + enum credentials_obtained obtained); +void cli_credentials_set_salt_principal(struct cli_credentials *cred, const char *principal); +enum credentials_use_kerberos cli_credentials_get_kerberos_state(struct cli_credentials *creds); +NTSTATUS cli_credentials_set_secrets(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct ldb_context *ldb, + const char *base, + const char *filter); + int cli_credentials_get_kvno(struct cli_credentials *cred); + +#endif /* __CREDENTIALS_H__ */ diff --git a/source4/auth/credentials/credentials.i b/source4/auth/credentials/credentials.i new file mode 100644 index 0000000000..bb31d6d4c0 --- /dev/null +++ b/source4/auth/credentials/credentials.i @@ -0,0 +1,147 @@ +/* + Unix SMB/CIFS implementation. + Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +%module(docstring="Credentials management.",package="samba.credentials") credentials + +%{ + +/* Include headers */ +#include <stdint.h> +#include <stdbool.h> + +#include "includes.h" +#include "auth/credentials/credentials.h" +#include "param/param.h" +#include "lib/cmdline/credentials.h" +typedef struct cli_credentials cli_credentials; +%} + +%import "carrays.i" +%import "typemaps.i" +%import "param/param.i" + +%typemap(default,noblock=1) struct cli_credentials * { + $1 = NULL; +} + +%constant int AUTO_USE_KERBEROS = CRED_AUTO_USE_KERBEROS; +%constant int DONT_USE_KERBEROS = CRED_DONT_USE_KERBEROS; +%constant int MUST_USE_KERBEROS = CRED_MUST_USE_KERBEROS; + +%{ +#include "librpc/gen_ndr/samr.h" /* for struct samr_Password */ +%} + +%typemap(out,noblock=1) struct samr_Password * { + $result = PyString_FromStringAndSize((char *)$1->hash, 16); +} + +%talloctype(cli_credentials); +%rename(Credentials) cli_credentials; +typedef struct cli_credentials { + %extend { + cli_credentials(void) { + return cli_credentials_init(NULL); + } + /* username */ + %feature("docstring") get_username "S.get_username() -> username\nObtain username."; + const char *get_username(void); + %feature("docstring") set_username "S.set_username(name, obtained=CRED_SPECIFIED) -> None\nChange username."; + bool set_username(const char *value, + enum credentials_obtained obtained=CRED_SPECIFIED); + + /* password */ + %feature("docstring") get_password "S.get_password() -> password\n" \ + "Obtain password."; + const char *get_password(void); + %feature("docstring") set_password "S.set_password(password, obtained=CRED_SPECIFIED) -> None\n" \ + "Change password."; + bool set_password(const char *val, + enum credentials_obtained obtained=CRED_SPECIFIED); + + /* domain */ + %feature("docstring") get_password "S.get_domain() -> domain\nObtain domain name."; + const char *get_domain(void); + %feature("docstring") set_domain "S.set_domain(domain, obtained=CRED_SPECIFIED) -> None\n" \ + "Change domain name."; + bool set_domain(const char *val, + enum credentials_obtained obtained=CRED_SPECIFIED); + + /* realm */ + %feature("docstring") get_realm "S.get_realm() -> realm\nObtain realm name."; + const char *get_realm(void); + %feature("docstring") set_realm "S.set_realm(realm, obtained=CRED_SPECIFIED) -> None\n" \ + "Change realm name."; + bool set_realm(const char *val, + enum credentials_obtained obtained=CRED_SPECIFIED); + + /* Kerberos */ + void set_kerberos_state(enum credentials_use_kerberos use_kerberos); + + %feature("docstring") parse_string "S.parse_string(text, obtained=CRED_SPECIFIED) -> None\n" \ + "Parse credentials string."; + void parse_string(const char *text, + enum credentials_obtained obtained=CRED_SPECIFIED); + + /* bind dn */ + %feature("docstring") get_bind_dn "S.get_bind_dn() -> bind dn\nObtain bind DN."; + const char *get_bind_dn(void); + %feature("docstring") set_bind_dn "S.set_bind_dn(bind_dn) -> None\nChange bind DN."; + bool set_bind_dn(const char *bind_dn); + + %feature("docstring") set_anonymous "S.set_anonymous() -> None\nUse anonymous credentials."; + void set_anonymous(); + + /* workstation name */ + const char *get_workstation(void); + bool set_workstation(const char *workstation, + enum credentials_obtained obtained=CRED_SPECIFIED); + + NTSTATUS set_machine_account(struct loadparm_context *lp_ctx); + + void guess(struct loadparm_context *lp_ctx); + bool is_anonymous(void); + + const struct samr_Password *get_nt_hash(TALLOC_CTX *mem_ctx); + + bool authentication_requested(void); + + %feature("docstring") wrong_password "S.wrong_password() -> bool\nIndicate the returned password was incorrect."; + bool wrong_password(void); + + %feature("docstring") set_cmdline_callbacks "S.set_cmdline_callbacks() -> bool\nUse command-line to obtain credentials not explicitly set."; + bool set_cmdline_callbacks(); + } +} cli_credentials; + +%{ +struct cli_credentials *cli_credentials_from_py_object(PyObject *py_obj) +{ + struct cli_credentials *ret; + + if (py_obj == Py_None) { + return cli_credentials_init_anon(NULL); + } + + if (SWIG_ConvertPtr(py_obj, (void *)&ret, SWIGTYPE_p_cli_credentials, 0 | 0 ) < 0) { + return NULL; + } + return ret; +} + +%} diff --git a/source4/auth/credentials/credentials.py b/source4/auth/credentials/credentials.py new file mode 100644 index 0000000000..2cd56c3599 --- /dev/null +++ b/source4/auth/credentials/credentials.py @@ -0,0 +1,191 @@ +# This file was automatically generated by SWIG (http://www.swig.org). +# Version 1.3.35 +# +# Don't modify this file, modify the SWIG interface instead. + +""" +Credentials management. +""" + +import _credentials +import new +new_instancemethod = new.instancemethod +try: + _swig_property = property +except NameError: + pass # Python < 2.2 doesn't have 'property'. +def _swig_setattr_nondynamic(self,class_type,name,value,static=1): + if (name == "thisown"): return self.this.own(value) + if (name == "this"): + if type(value).__name__ == 'PySwigObject': + self.__dict__[name] = value + return + method = class_type.__swig_setmethods__.get(name,None) + if method: return method(self,value) + if (not static) or hasattr(self,name): + self.__dict__[name] = value + else: + raise AttributeError("You cannot add attributes to %s" % self) + +def _swig_setattr(self,class_type,name,value): + return _swig_setattr_nondynamic(self,class_type,name,value,0) + +def _swig_getattr(self,class_type,name): + if (name == "thisown"): return self.this.own() + method = class_type.__swig_getmethods__.get(name,None) + if method: return method(self) + raise AttributeError,name + +def _swig_repr(self): + try: strthis = "proxy of " + self.this.__repr__() + except: strthis = "" + return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + +import types +try: + _object = types.ObjectType + _newclass = 1 +except AttributeError: + class _object : pass + _newclass = 0 +del types + + +def _swig_setattr_nondynamic_method(set): + def set_attr(self,name,value): + if (name == "thisown"): return self.this.own(value) + if hasattr(self,name) or (name == "this"): + set(self,name,value) + else: + raise AttributeError("You cannot add attributes to %s" % self) + return set_attr + + +import param +AUTO_USE_KERBEROS = _credentials.AUTO_USE_KERBEROS +DONT_USE_KERBEROS = _credentials.DONT_USE_KERBEROS +MUST_USE_KERBEROS = _credentials.MUST_USE_KERBEROS +class Credentials(object): + thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args, **kwargs): + _credentials.Credentials_swiginit(self,_credentials.new_Credentials(*args, **kwargs)) + def get_username(*args, **kwargs): + """ + S.get_username() -> username + Obtain username. + """ + return _credentials.Credentials_get_username(*args, **kwargs) + + def set_username(*args, **kwargs): + """ + S.set_username(name, obtained=CRED_SPECIFIED) -> None + Change username. + """ + return _credentials.Credentials_set_username(*args, **kwargs) + + def get_password(*args, **kwargs): + """ + S.get_password() -> password + Obtain password. + """ + return _credentials.Credentials_get_password(*args, **kwargs) + + def set_password(*args, **kwargs): + """ + S.set_password(password, obtained=CRED_SPECIFIED) -> None + Change password. + """ + return _credentials.Credentials_set_password(*args, **kwargs) + + def set_domain(*args, **kwargs): + """ + S.set_domain(domain, obtained=CRED_SPECIFIED) -> None + Change domain name. + """ + return _credentials.Credentials_set_domain(*args, **kwargs) + + def get_realm(*args, **kwargs): + """ + S.get_realm() -> realm + Obtain realm name. + """ + return _credentials.Credentials_get_realm(*args, **kwargs) + + def set_realm(*args, **kwargs): + """ + S.set_realm(realm, obtained=CRED_SPECIFIED) -> None + Change realm name. + """ + return _credentials.Credentials_set_realm(*args, **kwargs) + + def parse_string(*args, **kwargs): + """ + S.parse_string(text, obtained=CRED_SPECIFIED) -> None + Parse credentials string. + """ + return _credentials.Credentials_parse_string(*args, **kwargs) + + def get_bind_dn(*args, **kwargs): + """ + S.get_bind_dn() -> bind dn + Obtain bind DN. + """ + return _credentials.Credentials_get_bind_dn(*args, **kwargs) + + def set_bind_dn(*args, **kwargs): + """ + S.set_bind_dn(bind_dn) -> None + Change bind DN. + """ + return _credentials.Credentials_set_bind_dn(*args, **kwargs) + + def set_anonymous(*args, **kwargs): + """ + S.set_anonymous() -> None + Use anonymous credentials. + """ + return _credentials.Credentials_set_anonymous(*args, **kwargs) + + def wrong_password(*args, **kwargs): + """ + S.wrong_password() -> bool + Indicate the returned password was incorrect. + """ + return _credentials.Credentials_wrong_password(*args, **kwargs) + + def set_cmdline_callbacks(*args, **kwargs): + """ + S.set_cmdline_callbacks() -> bool + Use command-line to obtain credentials not explicitly set. + """ + return _credentials.Credentials_set_cmdline_callbacks(*args, **kwargs) + + __swig_destroy__ = _credentials.delete_Credentials +Credentials.get_username = new_instancemethod(_credentials.Credentials_get_username,None,Credentials) +Credentials.set_username = new_instancemethod(_credentials.Credentials_set_username,None,Credentials) +Credentials.get_password = new_instancemethod(_credentials.Credentials_get_password,None,Credentials) +Credentials.set_password = new_instancemethod(_credentials.Credentials_set_password,None,Credentials) +Credentials.get_domain = new_instancemethod(_credentials.Credentials_get_domain,None,Credentials) +Credentials.set_domain = new_instancemethod(_credentials.Credentials_set_domain,None,Credentials) +Credentials.get_realm = new_instancemethod(_credentials.Credentials_get_realm,None,Credentials) +Credentials.set_realm = new_instancemethod(_credentials.Credentials_set_realm,None,Credentials) +Credentials.set_kerberos_state = new_instancemethod(_credentials.Credentials_set_kerberos_state,None,Credentials) +Credentials.parse_string = new_instancemethod(_credentials.Credentials_parse_string,None,Credentials) +Credentials.get_bind_dn = new_instancemethod(_credentials.Credentials_get_bind_dn,None,Credentials) +Credentials.set_bind_dn = new_instancemethod(_credentials.Credentials_set_bind_dn,None,Credentials) +Credentials.set_anonymous = new_instancemethod(_credentials.Credentials_set_anonymous,None,Credentials) +Credentials.get_workstation = new_instancemethod(_credentials.Credentials_get_workstation,None,Credentials) +Credentials.set_workstation = new_instancemethod(_credentials.Credentials_set_workstation,None,Credentials) +Credentials.set_machine_account = new_instancemethod(_credentials.Credentials_set_machine_account,None,Credentials) +Credentials.guess = new_instancemethod(_credentials.Credentials_guess,None,Credentials) +Credentials.is_anonymous = new_instancemethod(_credentials.Credentials_is_anonymous,None,Credentials) +Credentials.get_nt_hash = new_instancemethod(_credentials.Credentials_get_nt_hash,None,Credentials) +Credentials.authentication_requested = new_instancemethod(_credentials.Credentials_authentication_requested,None,Credentials) +Credentials.wrong_password = new_instancemethod(_credentials.Credentials_wrong_password,None,Credentials) +Credentials.set_cmdline_callbacks = new_instancemethod(_credentials.Credentials_set_cmdline_callbacks,None,Credentials) +Credentials_swigregister = _credentials.Credentials_swigregister +Credentials_swigregister(Credentials) + + + diff --git a/source4/auth/credentials/credentials_files.c b/source4/auth/credentials/credentials_files.c new file mode 100644 index 0000000000..6c3bb2531e --- /dev/null +++ b/source4/auth/credentials/credentials_files.c @@ -0,0 +1,432 @@ +/* + Unix SMB/CIFS implementation. + + User credentials handling (as regards on-disk files) + + Copyright (C) Jelmer Vernooij 2005 + Copyright (C) Tim Potter 2001 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/events/events.h" +#include "lib/ldb/include/ldb.h" +#include "librpc/gen_ndr/samr.h" /* for struct samrPassword */ +#include "param/secrets.h" +#include "system/filesys.h" +#include "util/util_ldb.h" +#include "auth/credentials/credentials.h" +#include "auth/credentials/credentials_krb5.h" +#include "param/param.h" +#include "lib/events/events.h" + +/** + * Read a file descriptor, and parse it for a password (eg from a file or stdin) + * + * @param credentials Credentials structure on which to set the password + * @param fd open file descriptor to read the password from + * @param obtained This enum describes how 'specified' this password is + */ + +_PUBLIC_ bool cli_credentials_parse_password_fd(struct cli_credentials *credentials, + int fd, enum credentials_obtained obtained) +{ + char *p; + char pass[128]; + + for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */ + p && p - pass < sizeof(pass);) { + switch (read(fd, p, 1)) { + case 1: + if (*p != '\n' && *p != '\0') { + *++p = '\0'; /* advance p, and null-terminate pass */ + break; + } + /* fall through */ + case 0: + if (p - pass) { + *p = '\0'; /* null-terminate it, just in case... */ + p = NULL; /* then force the loop condition to become false */ + break; + } else { + fprintf(stderr, "Error reading password from file descriptor %d: %s\n", fd, "empty password\n"); + return false; + } + + default: + fprintf(stderr, "Error reading password from file descriptor %d: %s\n", + fd, strerror(errno)); + return false; + } + } + + cli_credentials_set_password(credentials, pass, obtained); + return true; +} + +/** + * Read a named file, and parse it for a password + * + * @param credentials Credentials structure on which to set the password + * @param file a named file to read the password from + * @param obtained This enum describes how 'specified' this password is + */ + +_PUBLIC_ bool cli_credentials_parse_password_file(struct cli_credentials *credentials, const char *file, enum credentials_obtained obtained) +{ + int fd = open(file, O_RDONLY, 0); + bool ret; + + if (fd < 0) { + fprintf(stderr, "Error opening password file %s: %s\n", + file, strerror(errno)); + return false; + } + + ret = cli_credentials_parse_password_fd(credentials, fd, obtained); + + close(fd); + + return ret; +} + +/** + * Read a named file, and parse it for username, domain, realm and password + * + * @param credentials Credentials structure on which to set the password + * @param file a named file to read the details from + * @param obtained This enum describes how 'specified' this password is + */ + +_PUBLIC_ bool cli_credentials_parse_file(struct cli_credentials *cred, const char *file, enum credentials_obtained obtained) +{ + uint16_t len = 0; + char *ptr, *val, *param; + char **lines; + int i, numlines; + + lines = file_lines_load(file, &numlines, NULL); + + if (lines == NULL) + { + /* fail if we can't open the credentials file */ + d_printf("ERROR: Unable to open credentials file!\n"); + return false; + } + + for (i = 0; i < numlines; i++) { + len = strlen(lines[i]); + + if (len == 0) + continue; + + /* break up the line into parameter & value. + * will need to eat a little whitespace possibly */ + param = lines[i]; + if (!(ptr = strchr_m (lines[i], '='))) + continue; + + val = ptr+1; + *ptr = '\0'; + + /* eat leading white space */ + while ((*val!='\0') && ((*val==' ') || (*val=='\t'))) + val++; + + if (strwicmp("password", param) == 0) { + cli_credentials_set_password(cred, val, obtained); + } else if (strwicmp("username", param) == 0) { + cli_credentials_set_username(cred, val, obtained); + } else if (strwicmp("domain", param) == 0) { + cli_credentials_set_domain(cred, val, obtained); + } else if (strwicmp("realm", param) == 0) { + cli_credentials_set_realm(cred, val, obtained); + } + memset(lines[i], 0, len); + } + + talloc_free(lines); + + return true; +} + + +/** + * Fill in credentials for the machine trust account, from the secrets database. + * + * @param cred Credentials structure to fill in + * @retval NTSTATUS error detailing any failure + */ +_PUBLIC_ NTSTATUS cli_credentials_set_secrets(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct ldb_context *ldb, + const char *base, + const char *filter) +{ + TALLOC_CTX *mem_ctx; + + int ldb_ret; + struct ldb_message **msgs; + const char *attrs[] = { + "secret", + "priorSecret", + "samAccountName", + "flatname", + "realm", + "secureChannelType", + "unicodePwd", + "msDS-KeyVersionNumber", + "saltPrincipal", + "privateKeytab", + "krb5Keytab", + "servicePrincipalName", + "ldapBindDn", + NULL + }; + + const char *machine_account; + const char *password; + const char *old_password; + const char *domain; + const char *realm; + enum netr_SchannelType sct; + const char *salt_principal; + const char *keytab; + + /* ok, we are going to get it now, don't recurse back here */ + cred->machine_account_pending = false; + + /* some other parts of the system will key off this */ + cred->machine_account = true; + + mem_ctx = talloc_named(cred, 0, "cli_credentials fetch machine password"); + + if (!ldb) { + /* Local secrets are stored in secrets.ldb */ + ldb = secrets_db_connect(mem_ctx, event_ctx, lp_ctx); + if (!ldb) { + /* set anonymous as the fallback, if the machine account won't work */ + cli_credentials_set_anonymous(cred); + DEBUG(1, ("Could not open secrets.ldb\n")); + talloc_free(mem_ctx); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + } + + /* search for the secret record */ + ldb_ret = gendb_search(ldb, + mem_ctx, ldb_dn_new(mem_ctx, ldb, base), + &msgs, attrs, + "%s", filter); + if (ldb_ret == 0) { + DEBUG(5, ("(normal if no LDAP backend required) Could not find entry to match filter: '%s' base: '%s'\n", + filter, base)); + /* set anonymous as the fallback, if the machine account won't work */ + cli_credentials_set_anonymous(cred); + talloc_free(mem_ctx); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } else if (ldb_ret != 1) { + DEBUG(5, ("Found more than one (%d) entry to match filter: '%s' base: '%s'\n", + ldb_ret, filter, base)); + /* set anonymous as the fallback, if the machine account won't work */ + cli_credentials_set_anonymous(cred); + talloc_free(mem_ctx); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + + password = ldb_msg_find_attr_as_string(msgs[0], "secret", NULL); + old_password = ldb_msg_find_attr_as_string(msgs[0], "priorSecret", NULL); + + machine_account = ldb_msg_find_attr_as_string(msgs[0], "samAccountName", NULL); + + if (!machine_account) { + machine_account = ldb_msg_find_attr_as_string(msgs[0], "servicePrincipalName", NULL); + + if (!machine_account) { + const char *ldap_bind_dn = ldb_msg_find_attr_as_string(msgs[0], "ldapBindDn", NULL); + if (!ldap_bind_dn) { + DEBUG(1, ("Could not find 'samAccountName', 'servicePrincipalName' or 'ldapBindDn' in secrets record: filter: '%s' base: '%s'\n", + filter, base)); + /* set anonymous as the fallback, if the machine account won't work */ + cli_credentials_set_anonymous(cred); + talloc_free(mem_ctx); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + } + } + + salt_principal = ldb_msg_find_attr_as_string(msgs[0], "saltPrincipal", NULL); + cli_credentials_set_salt_principal(cred, salt_principal); + + sct = ldb_msg_find_attr_as_int(msgs[0], "secureChannelType", 0); + if (sct) { + cli_credentials_set_secure_channel_type(cred, sct); + } + + if (!password) { + const struct ldb_val *nt_password_hash = ldb_msg_find_ldb_val(msgs[0], "unicodePwd"); + struct samr_Password hash; + ZERO_STRUCT(hash); + if (nt_password_hash) { + memcpy(hash.hash, nt_password_hash->data, + MIN(nt_password_hash->length, sizeof(hash.hash))); + + cli_credentials_set_nt_hash(cred, &hash, CRED_SPECIFIED); + } else { + cli_credentials_set_password(cred, NULL, CRED_SPECIFIED); + } + } else { + cli_credentials_set_password(cred, password, CRED_SPECIFIED); + } + + + domain = ldb_msg_find_attr_as_string(msgs[0], "flatname", NULL); + if (domain) { + cli_credentials_set_domain(cred, domain, CRED_SPECIFIED); + } + + realm = ldb_msg_find_attr_as_string(msgs[0], "realm", NULL); + if (realm) { + cli_credentials_set_realm(cred, realm, CRED_SPECIFIED); + } + + if (machine_account) { + cli_credentials_set_username(cred, machine_account, CRED_SPECIFIED); + } + + cli_credentials_set_kvno(cred, ldb_msg_find_attr_as_int(msgs[0], "msDS-KeyVersionNumber", 0)); + + /* If there was an external keytab specified by reference in + * the LDB, then use this. Otherwise we will make one up + * (chewing CPU time) from the password */ + keytab = ldb_msg_find_attr_as_string(msgs[0], "krb5Keytab", NULL); + if (keytab) { + cli_credentials_set_keytab_name(cred, event_ctx, lp_ctx, keytab, CRED_SPECIFIED); + } else { + keytab = ldb_msg_find_attr_as_string(msgs[0], "privateKeytab", NULL); + if (keytab) { + keytab = talloc_asprintf(mem_ctx, "FILE:%s", private_path(mem_ctx, lp_ctx, keytab)); + if (keytab) { + cli_credentials_set_keytab_name(cred, event_ctx, lp_ctx, keytab, CRED_SPECIFIED); + } + } + } + talloc_free(mem_ctx); + + return NT_STATUS_OK; +} + +/** + * Fill in credentials for the machine trust account, from the secrets database. + * + * @param cred Credentials structure to fill in + * @retval NTSTATUS error detailing any failure + */ +_PUBLIC_ NTSTATUS cli_credentials_set_machine_account(struct cli_credentials *cred, + struct loadparm_context *lp_ctx) +{ + NTSTATUS status; + char *filter; + /* Bleh, nasty recursion issues: We are setting a machine + * account here, so we don't want the 'pending' flag around + * any more */ + cred->machine_account_pending = false; + filter = talloc_asprintf(cred, SECRETS_PRIMARY_DOMAIN_FILTER, + cli_credentials_get_domain(cred)); + status = cli_credentials_set_secrets(cred, event_context_find(cred), lp_ctx, NULL, + SECRETS_PRIMARY_DOMAIN_DN, + filter); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("Could not find machine account in secrets database: %s", nt_errstr(status))); + } + return status; +} + +/** + * Fill in credentials for the machine trust account, from the secrets database. + * + * @param cred Credentials structure to fill in + * @retval NTSTATUS error detailing any failure + */ +NTSTATUS cli_credentials_set_krbtgt(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx) +{ + NTSTATUS status; + char *filter; + /* Bleh, nasty recursion issues: We are setting a machine + * account here, so we don't want the 'pending' flag around + * any more */ + cred->machine_account_pending = false; + filter = talloc_asprintf(cred, SECRETS_KRBTGT_SEARCH, + cli_credentials_get_realm(cred), + cli_credentials_get_domain(cred)); + status = cli_credentials_set_secrets(cred, event_ctx, lp_ctx, NULL, + SECRETS_PRINCIPALS_DN, + filter); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("Could not find krbtgt (master Kerberos) account in secrets database: %s", nt_errstr(status))); + } + return status; +} + +/** + * Fill in credentials for a particular prinicpal, from the secrets database. + * + * @param cred Credentials structure to fill in + * @retval NTSTATUS error detailing any failure + */ +_PUBLIC_ NTSTATUS cli_credentials_set_stored_principal(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *serviceprincipal) +{ + NTSTATUS status; + char *filter; + /* Bleh, nasty recursion issues: We are setting a machine + * account here, so we don't want the 'pending' flag around + * any more */ + cred->machine_account_pending = false; + filter = talloc_asprintf(cred, SECRETS_PRINCIPAL_SEARCH, + cli_credentials_get_realm(cred), + cli_credentials_get_domain(cred), + serviceprincipal); + status = cli_credentials_set_secrets(cred, event_ctx, lp_ctx, NULL, + SECRETS_PRINCIPALS_DN, filter); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("Could not find %s principal in secrets database: %s", serviceprincipal, nt_errstr(status))); + } + return status; +} + +/** + * Ask that when required, the credentials system will be filled with + * machine trust account, from the secrets database. + * + * @param cred Credentials structure to fill in + * @note This function is used to call the above function after, rather + * than during, popt processing. + * + */ +_PUBLIC_ void cli_credentials_set_machine_account_pending(struct cli_credentials *cred, + struct loadparm_context *lp_ctx) +{ + cred->machine_account_pending = true; + cred->machine_account_pending_lp_ctx = lp_ctx; +} + + diff --git a/source4/auth/credentials/credentials_krb5.c b/source4/auth/credentials/credentials_krb5.c new file mode 100644 index 0000000000..1a2d5faddd --- /dev/null +++ b/source4/auth/credentials/credentials_krb5.c @@ -0,0 +1,762 @@ +/* + Unix SMB/CIFS implementation. + + Handle user credentials (as regards krb5) + + Copyright (C) Jelmer Vernooij 2005 + Copyright (C) Tim Potter 2001 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/kerberos.h" +#include "auth/kerberos/kerberos.h" +#include "auth/credentials/credentials.h" +#include "auth/credentials/credentials_proto.h" +#include "auth/credentials/credentials_krb5.h" +#include "param/param.h" + +_PUBLIC_ int cli_credentials_get_krb5_context(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct smb_krb5_context **smb_krb5_context) +{ + int ret; + if (cred->smb_krb5_context) { + *smb_krb5_context = cred->smb_krb5_context; + return 0; + } + + ret = smb_krb5_init_context(cred, event_ctx, lp_ctx, &cred->smb_krb5_context); + if (ret) { + cred->smb_krb5_context = NULL; + return ret; + } + *smb_krb5_context = cred->smb_krb5_context; + return 0; +} + +/* This needs to be called directly after the cli_credentials_init(), + * otherwise we might have problems with the krb5 context already + * being here. + */ +_PUBLIC_ NTSTATUS cli_credentials_set_krb5_context(struct cli_credentials *cred, + struct smb_krb5_context *smb_krb5_context) +{ + if (!talloc_reference(cred, smb_krb5_context)) { + return NT_STATUS_NO_MEMORY; + } + cred->smb_krb5_context = smb_krb5_context; + return NT_STATUS_OK; +} + +static int cli_credentials_set_from_ccache(struct cli_credentials *cred, + struct ccache_container *ccache, + enum credentials_obtained obtained) +{ + + krb5_principal princ; + krb5_error_code ret; + char *name; + char **realm; + + if (cred->ccache_obtained > obtained) { + return 0; + } + + ret = krb5_cc_get_principal(ccache->smb_krb5_context->krb5_context, + ccache->ccache, &princ); + + if (ret) { + char *err_mess = smb_get_krb5_error_message(ccache->smb_krb5_context->krb5_context, + ret, cred); + DEBUG(1,("failed to get principal from ccache: %s\n", + err_mess)); + talloc_free(err_mess); + return ret; + } + + ret = krb5_unparse_name(ccache->smb_krb5_context->krb5_context, princ, &name); + if (ret) { + char *err_mess = smb_get_krb5_error_message(ccache->smb_krb5_context->krb5_context, ret, cred); + DEBUG(1,("failed to unparse principal from ccache: %s\n", + err_mess)); + talloc_free(err_mess); + return ret; + } + + realm = krb5_princ_realm(ccache->smb_krb5_context->krb5_context, princ); + + cli_credentials_set_principal(cred, name, obtained); + + free(name); + + krb5_free_principal(ccache->smb_krb5_context->krb5_context, princ); + + /* set the ccache_obtained here, as it just got set to UNINITIALISED by the calls above */ + cred->ccache_obtained = obtained; + + return 0; +} + +/* Free a memory ccache */ +static int free_mccache(struct ccache_container *ccc) +{ + krb5_cc_destroy(ccc->smb_krb5_context->krb5_context, ccc->ccache); + + return 0; +} + +/* Free a disk-based ccache */ +static int free_dccache(struct ccache_container *ccc) { + krb5_cc_close(ccc->smb_krb5_context->krb5_context, ccc->ccache); + + return 0; +} + +_PUBLIC_ int cli_credentials_set_ccache(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *name, + enum credentials_obtained obtained) +{ + krb5_error_code ret; + krb5_principal princ; + struct ccache_container *ccc; + if (cred->ccache_obtained > obtained) { + return 0; + } + + ccc = talloc(cred, struct ccache_container); + if (!ccc) { + return ENOMEM; + } + + ret = cli_credentials_get_krb5_context(cred, event_ctx, lp_ctx, + &ccc->smb_krb5_context); + if (ret) { + talloc_free(ccc); + return ret; + } + if (!talloc_reference(ccc, ccc->smb_krb5_context)) { + talloc_free(ccc); + return ENOMEM; + } + + if (name) { + ret = krb5_cc_resolve(ccc->smb_krb5_context->krb5_context, name, &ccc->ccache); + if (ret) { + DEBUG(1,("failed to read krb5 ccache: %s: %s\n", + name, + smb_get_krb5_error_message(ccc->smb_krb5_context->krb5_context, ret, ccc))); + talloc_free(ccc); + return ret; + } + } else { + ret = krb5_cc_default(ccc->smb_krb5_context->krb5_context, &ccc->ccache); + if (ret) { + DEBUG(3,("failed to read default krb5 ccache: %s\n", + smb_get_krb5_error_message(ccc->smb_krb5_context->krb5_context, ret, ccc))); + talloc_free(ccc); + return ret; + } + } + + talloc_set_destructor(ccc, free_dccache); + + ret = krb5_cc_get_principal(ccc->smb_krb5_context->krb5_context, ccc->ccache, &princ); + + if (ret) { + DEBUG(3,("failed to get principal from default ccache: %s\n", + smb_get_krb5_error_message(ccc->smb_krb5_context->krb5_context, ret, ccc))); + talloc_free(ccc); + return ret; + } + + krb5_free_principal(ccc->smb_krb5_context->krb5_context, princ); + + ret = cli_credentials_set_from_ccache(cred, ccc, obtained); + + if (ret) { + return ret; + } + + cred->ccache = ccc; + cred->ccache_obtained = obtained; + talloc_steal(cred, ccc); + + cli_credentials_invalidate_client_gss_creds(cred, cred->ccache_obtained); + return 0; +} + + +static int cli_credentials_new_ccache(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct ccache_container **_ccc) +{ + krb5_error_code ret; + struct ccache_container *ccc = talloc(cred, struct ccache_container); + char *ccache_name; + if (!ccc) { + return ENOMEM; + } + + ccache_name = talloc_asprintf(ccc, "MEMORY:%p", + ccc); + + if (!ccache_name) { + talloc_free(ccc); + return ENOMEM; + } + + ret = cli_credentials_get_krb5_context(cred, event_ctx, lp_ctx, + &ccc->smb_krb5_context); + if (ret) { + talloc_free(ccc); + return ret; + } + if (!talloc_reference(ccc, ccc->smb_krb5_context)) { + talloc_free(ccc); + return ENOMEM; + } + + ret = krb5_cc_resolve(ccc->smb_krb5_context->krb5_context, ccache_name, + &ccc->ccache); + if (ret) { + DEBUG(1,("failed to generate a new krb5 ccache (%s): %s\n", + ccache_name, + smb_get_krb5_error_message(ccc->smb_krb5_context->krb5_context, ret, ccc))); + talloc_free(ccache_name); + talloc_free(ccc); + return ret; + } + + talloc_set_destructor(ccc, free_mccache); + + talloc_free(ccache_name); + + *_ccc = ccc; + + return ret; +} + +_PUBLIC_ int cli_credentials_get_ccache(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct ccache_container **ccc) +{ + krb5_error_code ret; + + if (cred->machine_account_pending) { + cli_credentials_set_machine_account(cred, lp_ctx); + } + + if (cred->ccache_obtained >= cred->ccache_threshold && + cred->ccache_obtained > CRED_UNINITIALISED) { + *ccc = cred->ccache; + return 0; + } + if (cli_credentials_is_anonymous(cred)) { + return EINVAL; + } + + ret = cli_credentials_new_ccache(cred, event_ctx, lp_ctx, ccc); + if (ret) { + return ret; + } + + ret = kinit_to_ccache(cred, cred, (*ccc)->smb_krb5_context, (*ccc)->ccache); + if (ret) { + return ret; + } + + ret = cli_credentials_set_from_ccache(cred, *ccc, + (MAX(MAX(cred->principal_obtained, + cred->username_obtained), + cred->password_obtained))); + + cred->ccache = *ccc; + cred->ccache_obtained = cred->principal_obtained; + if (ret) { + return ret; + } + cli_credentials_invalidate_client_gss_creds(cred, cred->ccache_obtained); + return ret; +} + +void cli_credentials_invalidate_client_gss_creds(struct cli_credentials *cred, + enum credentials_obtained obtained) +{ + /* If the caller just changed the username/password etc, then + * any cached credentials are now invalid */ + if (obtained >= cred->client_gss_creds_obtained) { + if (cred->client_gss_creds_obtained > CRED_UNINITIALISED) { + talloc_unlink(cred, cred->client_gss_creds); + cred->client_gss_creds = NULL; + } + cred->client_gss_creds_obtained = CRED_UNINITIALISED; + } + /* Now that we know that the data is 'this specified', then + * don't allow something less 'known' to be returned as a + * ccache. Ie, if the username is on the commmand line, we + * don't want to later guess to use a file-based ccache */ + if (obtained > cred->client_gss_creds_threshold) { + cred->client_gss_creds_threshold = obtained; + } +} + +_PUBLIC_ void cli_credentials_invalidate_ccache(struct cli_credentials *cred, + enum credentials_obtained obtained) +{ + /* If the caller just changed the username/password etc, then + * any cached credentials are now invalid */ + if (obtained >= cred->ccache_obtained) { + if (cred->ccache_obtained > CRED_UNINITIALISED) { + talloc_unlink(cred, cred->ccache); + cred->ccache = NULL; + } + cred->ccache_obtained = CRED_UNINITIALISED; + } + /* Now that we know that the data is 'this specified', then + * don't allow something less 'known' to be returned as a + * ccache. Ie, if the username is on the commmand line, we + * don't want to later guess to use a file-based ccache */ + if (obtained > cred->ccache_threshold) { + cred->ccache_threshold = obtained; + } + + cli_credentials_invalidate_client_gss_creds(cred, + obtained); +} + +static int free_gssapi_creds(struct gssapi_creds_container *gcc) +{ + OM_uint32 min_stat, maj_stat; + maj_stat = gss_release_cred(&min_stat, &gcc->creds); + return 0; +} + +_PUBLIC_ int cli_credentials_get_client_gss_creds(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct gssapi_creds_container **_gcc) +{ + int ret = 0; + OM_uint32 maj_stat, min_stat; + struct gssapi_creds_container *gcc; + struct ccache_container *ccache; + gss_buffer_desc empty_buffer = GSS_C_EMPTY_BUFFER; + krb5_enctype *etypes = NULL; + + if (cred->client_gss_creds_obtained >= cred->client_gss_creds_threshold && + cred->client_gss_creds_obtained > CRED_UNINITIALISED) { + *_gcc = cred->client_gss_creds; + return 0; + } + + ret = cli_credentials_get_ccache(cred, event_ctx, lp_ctx, + &ccache); + if (ret) { + DEBUG(1, ("Failed to get CCACHE for GSSAPI client: %s\n", error_message(ret))); + return ret; + } + + gcc = talloc(cred, struct gssapi_creds_container); + if (!gcc) { + return ENOMEM; + } + + maj_stat = gss_krb5_import_cred(&min_stat, ccache->ccache, NULL, NULL, + &gcc->creds); + if (maj_stat) { + talloc_free(gcc); + if (min_stat) { + ret = min_stat; + } else { + ret = EINVAL; + } + return ret; + } + + /* + * transfer the enctypes from the smb_krb5_context to the gssapi layer + * + * We use 'our' smb_krb5_context to do the AS-REQ and it is possible + * to configure the enctypes via the krb5.conf. + * + * And the gss_init_sec_context() creates it's own krb5_context and + * the TGS-REQ had all enctypes in it and only the ones configured + * and used for the AS-REQ, so it wasn't possible to disable the usage + * of AES keys. + */ + min_stat = krb5_get_default_in_tkt_etypes(ccache->smb_krb5_context->krb5_context, + &etypes); + if (min_stat == 0) { + OM_uint32 num_ktypes; + + for (num_ktypes = 0; etypes[num_ktypes]; num_ktypes++); + + maj_stat = gss_krb5_set_allowable_enctypes(&min_stat, gcc->creds, + num_ktypes, etypes); + krb5_xfree (etypes); + if (maj_stat) { + talloc_free(gcc); + if (min_stat) { + ret = min_stat; + } else { + ret = EINVAL; + } + return ret; + } + } + + /* don't force GSS_C_CONF_FLAG and GSS_C_INTEG_FLAG */ + maj_stat = gss_set_cred_option(&min_stat, &gcc->creds, + GSS_KRB5_CRED_NO_CI_FLAGS_X, + &empty_buffer); + if (maj_stat) { + talloc_free(gcc); + if (min_stat) { + ret = min_stat; + } else { + ret = EINVAL; + } + return ret; + } + + cred->client_gss_creds_obtained = cred->ccache_obtained; + talloc_set_destructor(gcc, free_gssapi_creds); + cred->client_gss_creds = gcc; + *_gcc = gcc; + return 0; +} + +/** + Set a gssapi cred_id_t into the credentials system. (Client case) + + This grabs the credentials both 'intact' and getting the krb5 + ccache out of it. This routine can be generalised in future for + the case where we deal with GSSAPI mechs other than krb5. + + On sucess, the caller must not free gssapi_cred, as it now belongs + to the credentials system. +*/ + + int cli_credentials_set_client_gss_creds(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + gss_cred_id_t gssapi_cred, + enum credentials_obtained obtained) +{ + int ret; + OM_uint32 maj_stat, min_stat; + struct ccache_container *ccc; + struct gssapi_creds_container *gcc; + if (cred->client_gss_creds_obtained > obtained) { + return 0; + } + + gcc = talloc(cred, struct gssapi_creds_container); + if (!gcc) { + return ENOMEM; + } + + ret = cli_credentials_new_ccache(cred, event_ctx, lp_ctx, &ccc); + if (ret != 0) { + return ret; + } + + maj_stat = gss_krb5_copy_ccache(&min_stat, + gssapi_cred, ccc->ccache); + if (maj_stat) { + if (min_stat) { + ret = min_stat; + } else { + ret = EINVAL; + } + } + + if (ret == 0) { + ret = cli_credentials_set_from_ccache(cred, ccc, obtained); + } + cred->ccache = ccc; + cred->ccache_obtained = obtained; + if (ret == 0) { + gcc->creds = gssapi_cred; + talloc_set_destructor(gcc, free_gssapi_creds); + + /* set the clinet_gss_creds_obtained here, as it just + got set to UNINITIALISED by the calls above */ + cred->client_gss_creds_obtained = obtained; + cred->client_gss_creds = gcc; + } + return ret; +} + +/* Get the keytab (actually, a container containing the krb5_keytab) + * attached to this context. If this hasn't been done or set before, + * it will be generated from the password. + */ +_PUBLIC_ int cli_credentials_get_keytab(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct keytab_container **_ktc) +{ + krb5_error_code ret; + struct keytab_container *ktc; + struct smb_krb5_context *smb_krb5_context; + const char **enctype_strings; + TALLOC_CTX *mem_ctx; + + if (cred->keytab_obtained >= (MAX(cred->principal_obtained, + cred->username_obtained))) { + *_ktc = cred->keytab; + return 0; + } + + if (cli_credentials_is_anonymous(cred)) { + return EINVAL; + } + + ret = cli_credentials_get_krb5_context(cred, event_ctx, lp_ctx, + &smb_krb5_context); + if (ret) { + return ret; + } + + mem_ctx = talloc_new(cred); + if (!mem_ctx) { + return ENOMEM; + } + + enctype_strings = cli_credentials_get_enctype_strings(cred); + + ret = smb_krb5_create_memory_keytab(mem_ctx, cred, + smb_krb5_context, + enctype_strings, &ktc); + if (ret) { + talloc_free(mem_ctx); + return ret; + } + + cred->keytab_obtained = (MAX(cred->principal_obtained, + cred->username_obtained)); + + talloc_steal(cred, ktc); + cred->keytab = ktc; + *_ktc = cred->keytab; + talloc_free(mem_ctx); + return ret; +} + +/* Given the name of a keytab (presumably in the format + * FILE:/etc/krb5.keytab), open it and attach it */ + +_PUBLIC_ int cli_credentials_set_keytab_name(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *keytab_name, + enum credentials_obtained obtained) +{ + krb5_error_code ret; + struct keytab_container *ktc; + struct smb_krb5_context *smb_krb5_context; + TALLOC_CTX *mem_ctx; + + if (cred->keytab_obtained >= obtained) { + return 0; + } + + ret = cli_credentials_get_krb5_context(cred, event_ctx, lp_ctx, &smb_krb5_context); + if (ret) { + return ret; + } + + mem_ctx = talloc_new(cred); + if (!mem_ctx) { + return ENOMEM; + } + + ret = smb_krb5_open_keytab(mem_ctx, smb_krb5_context, + keytab_name, &ktc); + if (ret) { + return ret; + } + + cred->keytab_obtained = obtained; + + talloc_steal(cred, ktc); + cred->keytab = ktc; + talloc_free(mem_ctx); + + return ret; +} + +_PUBLIC_ int cli_credentials_update_keytab(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx) +{ + krb5_error_code ret; + struct keytab_container *ktc; + struct smb_krb5_context *smb_krb5_context; + const char **enctype_strings; + TALLOC_CTX *mem_ctx; + + mem_ctx = talloc_new(cred); + if (!mem_ctx) { + return ENOMEM; + } + + ret = cli_credentials_get_krb5_context(cred, event_ctx, lp_ctx, &smb_krb5_context); + if (ret) { + talloc_free(mem_ctx); + return ret; + } + + enctype_strings = cli_credentials_get_enctype_strings(cred); + + ret = cli_credentials_get_keytab(cred, event_ctx, lp_ctx, &ktc); + if (ret != 0) { + talloc_free(mem_ctx); + return ret; + } + + ret = smb_krb5_update_keytab(mem_ctx, cred, smb_krb5_context, enctype_strings, ktc); + + talloc_free(mem_ctx); + return ret; +} + +/* Get server gss credentials (in gsskrb5, this means the keytab) */ + +_PUBLIC_ int cli_credentials_get_server_gss_creds(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct gssapi_creds_container **_gcc) +{ + int ret = 0; + OM_uint32 maj_stat, min_stat; + struct gssapi_creds_container *gcc; + struct keytab_container *ktc; + struct smb_krb5_context *smb_krb5_context; + TALLOC_CTX *mem_ctx; + krb5_principal princ; + + if (cred->server_gss_creds_obtained >= (MAX(cred->keytab_obtained, + MAX(cred->principal_obtained, + cred->username_obtained)))) { + *_gcc = cred->server_gss_creds; + return 0; + } + + ret = cli_credentials_get_krb5_context(cred, event_ctx, lp_ctx, &smb_krb5_context); + if (ret) { + return ret; + } + + ret = cli_credentials_get_keytab(cred, event_ctx, lp_ctx, &ktc); + if (ret) { + DEBUG(1, ("Failed to get keytab for GSSAPI server: %s\n", error_message(ret))); + return ret; + } + + mem_ctx = talloc_new(cred); + if (!mem_ctx) { + return ENOMEM; + } + + ret = principal_from_credentials(mem_ctx, cred, smb_krb5_context, &princ); + if (ret) { + DEBUG(1,("cli_credentials_get_server_gss_creds: makeing krb5 principal failed (%s)\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + + gcc = talloc(cred, struct gssapi_creds_container); + if (!gcc) { + talloc_free(mem_ctx); + return ENOMEM; + } + + /* This creates a GSSAPI cred_id_t with the principal and keytab set */ + maj_stat = gss_krb5_import_cred(&min_stat, NULL, princ, ktc->keytab, + &gcc->creds); + if (maj_stat) { + if (min_stat) { + ret = min_stat; + } else { + ret = EINVAL; + } + } + if (ret == 0) { + cred->server_gss_creds_obtained = cred->keytab_obtained; + talloc_set_destructor(gcc, free_gssapi_creds); + cred->server_gss_creds = gcc; + *_gcc = gcc; + } + talloc_free(mem_ctx); + return ret; +} + +/** + * Set Kerberos KVNO + */ + +_PUBLIC_ void cli_credentials_set_kvno(struct cli_credentials *cred, + int kvno) +{ + cred->kvno = kvno; +} + +/** + * Return Kerberos KVNO + */ + +_PUBLIC_ int cli_credentials_get_kvno(struct cli_credentials *cred) +{ + return cred->kvno; +} + + +const char **cli_credentials_get_enctype_strings(struct cli_credentials *cred) +{ + /* If this is ever made user-configurable, we need to add code + * to remove/hide the other entries from the generated + * keytab */ + static const char *default_enctypes[] = { + "des-cbc-md5", + "aes256-cts-hmac-sha1-96", + "des3-cbc-sha1", + "arcfour-hmac-md5", + NULL + }; + return default_enctypes; +} + +const char *cli_credentials_get_salt_principal(struct cli_credentials *cred) +{ + return cred->salt_principal; +} + +_PUBLIC_ void cli_credentials_set_salt_principal(struct cli_credentials *cred, const char *principal) +{ + cred->salt_principal = talloc_strdup(cred, principal); +} + + diff --git a/source4/auth/credentials/credentials_krb5.h b/source4/auth/credentials/credentials_krb5.h new file mode 100644 index 0000000000..f672b0ad9a --- /dev/null +++ b/source4/auth/credentials/credentials_krb5.h @@ -0,0 +1,46 @@ +/* + samba -- Unix SMB/CIFS implementation. + + Client credentials structure + + Copyright (C) Jelmer Vernooij 2004-2006 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef __CREDENTIALS_KRB5_H__ +#define __CREDENTIALS_KRB5_H__ + +#include <gssapi/gssapi.h> +#include <krb5.h> + +struct gssapi_creds_container { + gss_cred_id_t creds; +}; + +/* Manually prototyped here to avoid needing gss headers in most callers */ +int cli_credentials_set_client_gss_creds(struct cli_credentials *cred, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + gss_cred_id_t gssapi_cred, + enum credentials_obtained obtained); + +/* Manually prototyped here to avoid needing krb5 headers in most callers */ +krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx, + struct cli_credentials *credentials, + struct smb_krb5_context *smb_krb5_context, + krb5_principal *princ); + +#endif /* __CREDENTIALS_KRB5_H__ */ diff --git a/source4/auth/credentials/credentials_ntlm.c b/source4/auth/credentials/credentials_ntlm.c new file mode 100644 index 0000000000..22e273c35a --- /dev/null +++ b/source4/auth/credentials/credentials_ntlm.c @@ -0,0 +1,269 @@ +/* + Unix SMB/CIFS implementation. + + User credentials handling + + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2005 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "librpc/gen_ndr/samr.h" /* for struct samrPassword */ +#include "lib/crypto/crypto.h" +#include "libcli/auth/libcli_auth.h" +#include "auth/credentials/credentials.h" + +_PUBLIC_ void cli_credentials_get_ntlm_username_domain(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, + const char **username, + const char **domain) +{ + if (cred->principal_obtained > cred->username_obtained) { + *domain = talloc_strdup(mem_ctx, ""); + *username = cli_credentials_get_principal(cred, mem_ctx); + } else { + *domain = cli_credentials_get_domain(cred); + *username = cli_credentials_get_username(cred); + } +} + +_PUBLIC_ NTSTATUS cli_credentials_get_ntlm_response(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, + int *flags, + DATA_BLOB challenge, DATA_BLOB target_info, + DATA_BLOB *_lm_response, DATA_BLOB *_nt_response, + DATA_BLOB *_lm_session_key, DATA_BLOB *_session_key) +{ + const char *user, *domain; + DATA_BLOB lm_response, nt_response; + DATA_BLOB lm_session_key, session_key; + const struct samr_Password *nt_hash; + lm_session_key = data_blob(NULL, 0); + + /* We may already have an NTLM response we prepared earlier. + * This is used for NTLM pass-though authentication */ + if (cred->nt_response.data || cred->lm_response.data) { + *_nt_response = cred->nt_response; + *_lm_response = cred->lm_response; + + if (!cred->lm_response.data) { + *flags = *flags & ~CLI_CRED_LANMAN_AUTH; + } + *_lm_session_key = data_blob(NULL, 0); + *_session_key = data_blob(NULL, 0); + return NT_STATUS_OK; + } + + nt_hash = cli_credentials_get_nt_hash(cred, mem_ctx); + + cli_credentials_get_ntlm_username_domain(cred, mem_ctx, &user, &domain); + + /* If we are sending a username@realm login (see function + * above), then we will not send LM, it will not be + * accepted */ + if (cred->principal_obtained > cred->username_obtained) { + *flags = *flags & ~CLI_CRED_LANMAN_AUTH; + } + + /* Likewise if we are a machine account (avoid protocol downgrade attacks) */ + if (cred->machine_account) { + *flags = *flags & ~CLI_CRED_LANMAN_AUTH; + } + + if (cred->use_kerberos == CRED_MUST_USE_KERBEROS) { + return NT_STATUS_ACCESS_DENIED; + } + + if (!nt_hash) { + static const uint8_t zeros[16]; + /* do nothing - blobs are zero length */ + + /* session key is all zeros */ + session_key = data_blob_talloc(mem_ctx, zeros, 16); + lm_session_key = data_blob_talloc(mem_ctx, zeros, 16); + + lm_response = data_blob(NULL, 0); + nt_response = data_blob(NULL, 0); + + /* not doing NTLM2 without a password */ + *flags &= ~CLI_CRED_NTLM2; + } else if (*flags & CLI_CRED_NTLMv2_AUTH) { + + if (!target_info.length) { + /* be lazy, match win2k - we can't do NTLMv2 without it */ + DEBUG(1, ("Server did not provide 'target information', required for NTLMv2\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + /* TODO: if the remote server is standalone, then we should replace 'domain' + with the server name as supplied above */ + + if (!SMBNTLMv2encrypt_hash(mem_ctx, + user, + domain, + nt_hash->hash, &challenge, + &target_info, + &lm_response, &nt_response, + NULL, &session_key)) { + return NT_STATUS_NO_MEMORY; + } + + /* LM Key is incompatible... */ + *flags &= ~CLI_CRED_LANMAN_AUTH; + } else if (*flags & CLI_CRED_NTLM2) { + struct MD5Context md5_session_nonce_ctx; + uint8_t session_nonce[16]; + uint8_t session_nonce_hash[16]; + uint8_t user_session_key[16]; + + lm_response = data_blob_talloc(mem_ctx, NULL, 24); + generate_random_buffer(lm_response.data, 8); + memset(lm_response.data+8, 0, 16); + + memcpy(session_nonce, challenge.data, 8); + memcpy(&session_nonce[8], lm_response.data, 8); + + MD5Init(&md5_session_nonce_ctx); + MD5Update(&md5_session_nonce_ctx, challenge.data, 8); + MD5Update(&md5_session_nonce_ctx, lm_response.data, 8); + MD5Final(session_nonce_hash, &md5_session_nonce_ctx); + + DEBUG(5, ("NTLMSSP challenge set by NTLM2\n")); + DEBUG(5, ("challenge is: \n")); + dump_data(5, session_nonce_hash, 8); + + nt_response = data_blob_talloc(mem_ctx, NULL, 24); + SMBOWFencrypt(nt_hash->hash, + session_nonce_hash, + nt_response.data); + + session_key = data_blob_talloc(mem_ctx, NULL, 16); + + SMBsesskeygen_ntv1(nt_hash->hash, user_session_key); + hmac_md5(user_session_key, session_nonce, sizeof(session_nonce), session_key.data); + dump_data_pw("NTLM2 session key:\n", session_key.data, session_key.length); + + /* LM Key is incompatible... */ + *flags &= ~CLI_CRED_LANMAN_AUTH; + } else { + uint8_t lm_hash[16]; + nt_response = data_blob_talloc(mem_ctx, NULL, 24); + SMBOWFencrypt(nt_hash->hash, challenge.data, + nt_response.data); + + session_key = data_blob_talloc(mem_ctx, NULL, 16); + SMBsesskeygen_ntv1(nt_hash->hash, session_key.data); + dump_data_pw("NT session key:\n", session_key.data, session_key.length); + + /* lanman auth is insecure, it may be disabled. + We may also not have a password */ + if (*flags & CLI_CRED_LANMAN_AUTH) { + const char *password; + password = cli_credentials_get_password(cred); + if (!password) { + lm_response = nt_response; + } else { + lm_response = data_blob_talloc(mem_ctx, NULL, 24); + if (!SMBencrypt(password,challenge.data, + lm_response.data)) { + /* If the LM password was too long (and therefore the LM hash being + of the first 14 chars only), don't send it. + + We don't have any better options but to send the NT response + */ + data_blob_free(&lm_response); + lm_response = nt_response; + /* LM Key is incompatible with 'long' passwords */ + *flags &= ~CLI_CRED_LANMAN_AUTH; + } else { + E_deshash(password, lm_hash); + lm_session_key = data_blob_talloc(mem_ctx, NULL, 16); + memcpy(lm_session_key.data, lm_hash, 8); + memset(&lm_session_key.data[8], '\0', 8); + + if (!(*flags & CLI_CRED_NTLM_AUTH)) { + session_key = lm_session_key; + } + } + } + } else { + const char *password; + + /* LM Key is incompatible... */ + lm_response = nt_response; + *flags &= ~CLI_CRED_LANMAN_AUTH; + + password = cli_credentials_get_password(cred); + if (password) { + E_deshash(password, lm_hash); + lm_session_key = data_blob_talloc(mem_ctx, NULL, 16); + memcpy(lm_session_key.data, lm_hash, 8); + memset(&lm_session_key.data[8], '\0', 8); + } + } + } + if (_lm_response) { + *_lm_response = lm_response; + } + if (_nt_response) { + *_nt_response = nt_response; + } + if (_lm_session_key) { + *_lm_session_key = lm_session_key; + } + if (_session_key) { + *_session_key = session_key; + } + return NT_STATUS_OK; +} + +_PUBLIC_ bool cli_credentials_set_nt_hash(struct cli_credentials *cred, + const struct samr_Password *nt_hash, + enum credentials_obtained obtained) +{ + if (obtained >= cred->password_obtained) { + cli_credentials_set_password(cred, NULL, obtained); + if (nt_hash) { + cred->nt_hash = talloc(cred, struct samr_Password); + *cred->nt_hash = *nt_hash; + } else { + cred->nt_hash = NULL; + } + return true; + } + + return false; +} + +_PUBLIC_ bool cli_credentials_set_ntlm_response(struct cli_credentials *cred, + const DATA_BLOB *lm_response, + const DATA_BLOB *nt_response, + enum credentials_obtained obtained) +{ + if (obtained >= cred->password_obtained) { + cli_credentials_set_password(cred, NULL, obtained); + if (nt_response) { + cred->nt_response = data_blob_talloc(cred, nt_response->data, nt_response->length); + talloc_steal(cred, cred->nt_response.data); + } + if (nt_response) { + cred->lm_response = data_blob_talloc(cred, lm_response->data, lm_response->length); + } + return true; + } + + return false; +} + diff --git a/source4/auth/credentials/credentials_wrap.c b/source4/auth/credentials/credentials_wrap.c new file mode 100644 index 0000000000..81ba426e45 --- /dev/null +++ b/source4/auth/credentials/credentials_wrap.c @@ -0,0 +1,4370 @@ +/* ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). + * Version 1.3.35 + * + * This file is not intended to be easily readable and contains a number of + * coding conventions designed to improve portability and efficiency. Do not make + * changes to this file unless you know what you are doing--modify the SWIG + * interface file instead. + * ----------------------------------------------------------------------------- */ + +#define SWIGPYTHON +#define SWIG_PYTHON_NO_BUILD_NONE +/* ----------------------------------------------------------------------------- + * This section contains generic SWIG labels for method/variable + * declarations/attributes, and other compiler dependent labels. + * ----------------------------------------------------------------------------- */ + +/* template workaround for compilers that cannot correctly implement the C++ standard */ +#ifndef SWIGTEMPLATEDISAMBIGUATOR +# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) +# define SWIGTEMPLATEDISAMBIGUATOR template +# elif defined(__HP_aCC) +/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ +/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ +# define SWIGTEMPLATEDISAMBIGUATOR template +# else +# define SWIGTEMPLATEDISAMBIGUATOR +# endif +#endif + +/* inline attribute */ +#ifndef SWIGINLINE +# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) +# define SWIGINLINE inline +# else +# define SWIGINLINE +# endif +#endif + +/* attribute recognised by some compilers to avoid 'unused' warnings */ +#ifndef SWIGUNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +# elif defined(__ICC) +# define SWIGUNUSED __attribute__ ((__unused__)) +# else +# define SWIGUNUSED +# endif +#endif + +#ifndef SWIGUNUSEDPARM +# ifdef __cplusplus +# define SWIGUNUSEDPARM(p) +# else +# define SWIGUNUSEDPARM(p) p SWIGUNUSED +# endif +#endif + +/* internal SWIG method */ +#ifndef SWIGINTERN +# define SWIGINTERN static SWIGUNUSED +#endif + +/* internal inline SWIG method */ +#ifndef SWIGINTERNINLINE +# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE +#endif + +/* exporting methods */ +#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) +# ifndef GCC_HASCLASSVISIBILITY +# define GCC_HASCLASSVISIBILITY +# endif +#endif + +#ifndef SWIGEXPORT +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# if defined(STATIC_LINKED) +# define SWIGEXPORT +# else +# define SWIGEXPORT __declspec(dllexport) +# endif +# else +# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) +# define SWIGEXPORT __attribute__ ((visibility("default"))) +# else +# define SWIGEXPORT +# endif +# endif +#endif + +/* calling conventions for Windows */ +#ifndef SWIGSTDCALL +# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# define SWIGSTDCALL __stdcall +# else +# define SWIGSTDCALL +# endif +#endif + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ +#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) +# define _SCL_SECURE_NO_DEPRECATE +#endif + + + +/* Python.h has to appear first */ +#include <Python.h> + +/* ----------------------------------------------------------------------------- + * swigrun.swg + * + * This file contains generic CAPI SWIG runtime support for pointer + * type checking. + * ----------------------------------------------------------------------------- */ + +/* This should only be incremented when either the layout of swig_type_info changes, + or for whatever reason, the runtime changes incompatibly */ +#define SWIG_RUNTIME_VERSION "4" + +/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ +#ifdef SWIG_TYPE_TABLE +# define SWIG_QUOTE_STRING(x) #x +# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) +# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) +#else +# define SWIG_TYPE_TABLE_NAME +#endif + +/* + You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for + creating a static or dynamic library from the swig runtime code. + In 99.9% of the cases, swig just needs to declare them as 'static'. + + But only do this if is strictly necessary, ie, if you have problems + with your compiler or so. +*/ + +#ifndef SWIGRUNTIME +# define SWIGRUNTIME SWIGINTERN +#endif + +#ifndef SWIGRUNTIMEINLINE +# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE +#endif + +/* Generic buffer size */ +#ifndef SWIG_BUFFER_SIZE +# define SWIG_BUFFER_SIZE 1024 +#endif + +/* Flags for pointer conversions */ +#define SWIG_POINTER_DISOWN 0x1 +#define SWIG_CAST_NEW_MEMORY 0x2 + +/* Flags for new pointer objects */ +#define SWIG_POINTER_OWN 0x1 + + +/* + Flags/methods for returning states. + + The swig conversion methods, as ConvertPtr, return and integer + that tells if the conversion was successful or not. And if not, + an error code can be returned (see swigerrors.swg for the codes). + + Use the following macros/flags to set or process the returning + states. + + In old swig versions, you usually write code as: + + if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { + // success code + } else { + //fail code + } + + Now you can be more explicit as: + + int res = SWIG_ConvertPtr(obj,vptr,ty.flags); + if (SWIG_IsOK(res)) { + // success code + } else { + // fail code + } + + that seems to be the same, but now you can also do + + Type *ptr; + int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); + if (SWIG_IsOK(res)) { + // success code + if (SWIG_IsNewObj(res) { + ... + delete *ptr; + } else { + ... + } + } else { + // fail code + } + + I.e., now SWIG_ConvertPtr can return new objects and you can + identify the case and take care of the deallocation. Of course that + requires also to SWIG_ConvertPtr to return new result values, as + + int SWIG_ConvertPtr(obj, ptr,...) { + if (<obj is ok>) { + if (<need new object>) { + *ptr = <ptr to new allocated object>; + return SWIG_NEWOBJ; + } else { + *ptr = <ptr to old object>; + return SWIG_OLDOBJ; + } + } else { + return SWIG_BADOBJ; + } + } + + Of course, returning the plain '0(success)/-1(fail)' still works, but you can be + more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the + swig errors code. + + Finally, if the SWIG_CASTRANK_MODE is enabled, the result code + allows to return the 'cast rank', for example, if you have this + + int food(double) + int fooi(int); + + and you call + + food(1) // cast rank '1' (1 -> 1.0) + fooi(1) // cast rank '0' + + just use the SWIG_AddCast()/SWIG_CheckState() + + + */ +#define SWIG_OK (0) +#define SWIG_ERROR (-1) +#define SWIG_IsOK(r) (r >= 0) +#define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) + +/* The CastRankLimit says how many bits are used for the cast rank */ +#define SWIG_CASTRANKLIMIT (1 << 8) +/* The NewMask denotes the object was created (using new/malloc) */ +#define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) +/* The TmpMask is for in/out typemaps that use temporal objects */ +#define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) +/* Simple returning values */ +#define SWIG_BADOBJ (SWIG_ERROR) +#define SWIG_OLDOBJ (SWIG_OK) +#define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) +#define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) +/* Check, add and del mask methods */ +#define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) +#define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) +#define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) +#define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) +#define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) +#define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) + + +/* Cast-Rank Mode */ +#if defined(SWIG_CASTRANK_MODE) +# ifndef SWIG_TypeRank +# define SWIG_TypeRank unsigned long +# endif +# ifndef SWIG_MAXCASTRANK /* Default cast allowed */ +# define SWIG_MAXCASTRANK (2) +# endif +# define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) +# define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) +SWIGINTERNINLINE int SWIG_AddCast(int r) { + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; +} +SWIGINTERNINLINE int SWIG_CheckState(int r) { + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; +} +#else /* no cast-rank mode */ +# define SWIG_AddCast +# define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) +#endif + + + + +#include <string.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *(*swig_converter_func)(void *, int *); +typedef struct swig_type_info *(*swig_dycast_func)(void **); + +/* Structure to store information on one type */ +typedef struct swig_type_info { + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ +} swig_type_info; + +/* Structure to store a type and conversion function used for casting */ +typedef struct swig_cast_info { + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ +} swig_cast_info; + +/* Structure used to store module information + * Each module generates one structure like this, and the runtime collects + * all of these structures and stores them in a circularly linked list.*/ +typedef struct swig_module_info { + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ +} swig_module_info; + +/* + Compare two type names skipping the space characters, therefore + "char*" == "char *" and "Class<int>" == "Class<int >", etc. + + Return 0 when the two name types are equivalent, as in + strncmp, but skipping ' '. +*/ +SWIGRUNTIME int +SWIG_TypeNameComp(const char *f1, const char *l1, + const char *f2, const char *l2) { + for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); +} + +/* + Check type equivalence in a name list like <name1>|<name2>|... + Return 0 if not equal, 1 if equal +*/ +SWIGRUNTIME int +SWIG_TypeEquiv(const char *nb, const char *tb) { + int equiv = 0; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) ++ne; + } + return equiv; +} + +/* + Check type equivalence in a name list like <name1>|<name2>|... + Return 0 if equal, -1 if nb < tb, 1 if nb > tb +*/ +SWIGRUNTIME int +SWIG_TypeCompare(const char *nb, const char *tb) { + int equiv = 0; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (!equiv && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; + if (*ne) ++ne; + } + return equiv; +} + + +/* think of this as a c++ template<> or a scheme macro */ +#define SWIG_TypeCheck_Template(comparison, ty) \ + if (ty) { \ + swig_cast_info *iter = ty->cast; \ + while (iter) { \ + if (comparison) { \ + if (iter == ty->cast) return iter; \ + /* Move iter to the top of the linked list */ \ + iter->prev->next = iter->next; \ + if (iter->next) \ + iter->next->prev = iter->prev; \ + iter->next = ty->cast; \ + iter->prev = 0; \ + if (ty->cast) ty->cast->prev = iter; \ + ty->cast = iter; \ + return iter; \ + } \ + iter = iter->next; \ + } \ + } \ + return 0 + +/* + Check the typename +*/ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheck(const char *c, swig_type_info *ty) { + SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty); +} + +/* Same as previous function, except strcmp is replaced with a pointer comparison */ +SWIGRUNTIME swig_cast_info * +SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) { + SWIG_TypeCheck_Template(iter->type == from, into); +} + +/* + Cast a pointer up an inheritance hierarchy +*/ +SWIGRUNTIMEINLINE void * +SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); +} + +/* + Dynamic pointer casting. Down an inheritance hierarchy +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; +} + +/* + Return the name associated with this type +*/ +SWIGRUNTIMEINLINE const char * +SWIG_TypeName(const swig_type_info *ty) { + return ty->name; +} + +/* + Return the pretty name associated with this type, + that is an unmangled type name in a form presentable to the user. +*/ +SWIGRUNTIME const char * +SWIG_TypePrettyName(const swig_type_info *type) { + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. We choose + to print the last name, as it is often (?) the most + specific. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s+1; + return last_name; + } + else + return type->name; +} + +/* + Set the clientdata field for a type +*/ +SWIGRUNTIME void +SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; + + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; + } +} +SWIGRUNTIME void +SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; +} + +/* + Search for a swig_type_info structure only by mangled name + Search is a O(log #types) + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_MangledTypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + register size_t l = 0; + register size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + register size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + register int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; +} + +/* + Search for a swig_type_info structure for either a mangled name or a human readable name. + It first searches the mangled names of the types, which is a O(log #types) + If a type is not found it then searches the human readable names, which is O(#types). + + We start searching at module start, and finish searching when start == end. + Note: if start == end at the beginning of the function, we go all the way around + the circular list. +*/ +SWIGRUNTIME swig_type_info * +SWIG_TypeQueryModule(swig_module_info *start, + swig_module_info *end, + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + register size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } + + /* neither found a match */ + return 0; +} + +/* + Pack binary data into a string +*/ +SWIGRUNTIME char * +SWIG_PackData(char *c, void *ptr, size_t sz) { + static const char hex[17] = "0123456789abcdef"; + register const unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; +} + +/* + Unpack binary data from a string +*/ +SWIGRUNTIME const char * +SWIG_UnpackData(const char *c, void *ptr, size_t sz) { + register unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register char d = *(c++); + register unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = ((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = ((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; +} + +/* + Pack 'void *' into a string buffer. +*/ +SWIGRUNTIME char * +SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { + char *r = buff; + if ((2*sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,&ptr,sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r,name); + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sizeof(void *)); +} + +SWIGRUNTIME char * +SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2*sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,ptr,sz); + if (lname) { + strncpy(r,name,lname+1); + } else { + *r = 0; + } + return buff; +} + +SWIGRUNTIME const char * +SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + memset(ptr,0,sz); + return name; + } else { + return 0; + } + } + return SWIG_UnpackData(++c,ptr,sz); +} + +#ifdef __cplusplus +} +#endif + +/* Errors in SWIG */ +#define SWIG_UnknownError -1 +#define SWIG_IOError -2 +#define SWIG_RuntimeError -3 +#define SWIG_IndexError -4 +#define SWIG_TypeError -5 +#define SWIG_DivisionByZero -6 +#define SWIG_OverflowError -7 +#define SWIG_SyntaxError -8 +#define SWIG_ValueError -9 +#define SWIG_SystemError -10 +#define SWIG_AttributeError -11 +#define SWIG_MemoryError -12 +#define SWIG_NullReferenceError -13 + + + + +/* Add PyOS_snprintf for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) +# define PyOS_snprintf _snprintf +# else +# define PyOS_snprintf snprintf +# endif +#endif + +/* A crude PyString_FromFormat implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 + +#ifndef SWIG_PYBUFFER_SIZE +# define SWIG_PYBUFFER_SIZE 1024 +#endif + +static PyObject * +PyString_FromFormat(const char *fmt, ...) { + va_list ap; + char buf[SWIG_PYBUFFER_SIZE * 2]; + int res; + va_start(ap, fmt); + res = vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); +} +#endif + +/* Add PyObject_Del for old Pythons */ +#if PY_VERSION_HEX < 0x01060000 +# define PyObject_Del(op) PyMem_DEL((op)) +#endif +#ifndef PyObject_DEL +# define PyObject_DEL PyObject_Del +#endif + +/* A crude PyExc_StopIteration exception for old Pythons */ +#if PY_VERSION_HEX < 0x02020000 +# ifndef PyExc_StopIteration +# define PyExc_StopIteration PyExc_RuntimeError +# endif +# ifndef PyObject_GenericGetAttr +# define PyObject_GenericGetAttr 0 +# endif +#endif +/* Py_NotImplemented is defined in 2.1 and up. */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef Py_NotImplemented +# define Py_NotImplemented PyExc_RuntimeError +# endif +#endif + + +/* A crude PyString_AsStringAndSize implementation for old Pythons */ +#if PY_VERSION_HEX < 0x02010000 +# ifndef PyString_AsStringAndSize +# define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} +# endif +#endif + +/* PySequence_Size for old Pythons */ +#if PY_VERSION_HEX < 0x02000000 +# ifndef PySequence_Size +# define PySequence_Size PySequence_Length +# endif +#endif + + +/* PyBool_FromLong for old Pythons */ +#if PY_VERSION_HEX < 0x02030000 +static +PyObject *PyBool_FromLong(long ok) +{ + PyObject *result = ok ? Py_True : Py_False; + Py_INCREF(result); + return result; +} +#endif + +/* Py_ssize_t for old Pythons */ +/* This code is as recommended by: */ +/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ +#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) +typedef int Py_ssize_t; +# define PY_SSIZE_T_MAX INT_MAX +# define PY_SSIZE_T_MIN INT_MIN +#endif + +/* ----------------------------------------------------------------------------- + * error manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIME PyObject* +SWIG_Python_ErrorType(int code) { + PyObject* type = 0; + switch(code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; +} + + +SWIGRUNTIME void +SWIG_Python_AddErrorMsg(const char* mesg) +{ + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + + if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyErr_Clear(); + Py_XINCREF(type); + PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); + Py_DECREF(old_str); + Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } +} + + + +#if defined(SWIG_PYTHON_NO_THREADS) +# if defined(SWIG_PYTHON_THREADS) +# undef SWIG_PYTHON_THREADS +# endif +#endif +#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ +# if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) +# if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ +# define SWIG_PYTHON_USE_GIL +# endif +# endif +# if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ +# ifndef SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() +# endif +# ifdef __cplusplus /* C++ code */ + class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } + }; + class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { PyEval_RestoreThread(save); status = false; }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } + }; +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block +# define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow +# define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() +# else /* C code */ +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() +# define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() +# define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) +# endif +# else /* Old thread way, not implemented, user must provide it */ +# if !defined(SWIG_PYTHON_INITIALIZE_THREADS) +# define SWIG_PYTHON_INITIALIZE_THREADS +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_END_BLOCK) +# define SWIG_PYTHON_THREAD_END_BLOCK +# endif +# if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# endif +# if !defined(SWIG_PYTHON_THREAD_END_ALLOW) +# define SWIG_PYTHON_THREAD_END_ALLOW +# endif +# endif +#else /* No thread support */ +# define SWIG_PYTHON_INITIALIZE_THREADS +# define SWIG_PYTHON_THREAD_BEGIN_BLOCK +# define SWIG_PYTHON_THREAD_END_BLOCK +# define SWIG_PYTHON_THREAD_BEGIN_ALLOW +# define SWIG_PYTHON_THREAD_END_ALLOW +#endif + +/* ----------------------------------------------------------------------------- + * Python API portion that goes into the runtime + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* cc-mode */ +#endif +#endif + +/* ----------------------------------------------------------------------------- + * Constant declarations + * ----------------------------------------------------------------------------- */ + +/* Constant Types */ +#define SWIG_PY_POINTER 4 +#define SWIG_PY_BINARY 5 + +/* Constant information structure */ +typedef struct swig_const_info { + int type; + char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; +} swig_const_info; + +#ifdef __cplusplus +#if 0 +{ /* cc-mode */ +#endif +} +#endif + + +/* ----------------------------------------------------------------------------- + * See the LICENSE file for information on copyright, usage and redistribution + * of SWIG, and the README file for authors - http://www.swig.org/release.html. + * + * pyrun.swg + * + * This file contains the runtime support for Python modules + * and includes code for managing global variables and pointer + * type checking. + * + * ----------------------------------------------------------------------------- */ + +/* Common SWIG API */ + +/* for raw pointers */ +#define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) +#define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) +#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) +#define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) +#define swig_owntype int + +/* for raw packed data */ +#define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + +/* for class or struct pointers */ +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) + +/* for C or C++ function pointers */ +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) + +/* for C++ member pointers, ie, member methods */ +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) + + +/* Runtime API */ + +#define SWIG_GetModule(clientdata) SWIG_Python_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) +#define SWIG_NewClientData(obj) PySwigClientData_New(obj) + +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail + + +/* Runtime API implementation */ + +/* Error manipulation */ + +SWIGINTERN void +SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +SWIGINTERN void +SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, (char *) msg); + SWIG_PYTHON_THREAD_END_BLOCK; +} + +#define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) + +/* Set a constant value */ + +SWIGINTERN void +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { + PyDict_SetItemString(d, (char*) name, obj); + Py_DECREF(obj); +} + +/* Append a value to the result obj */ + +SWIGINTERN PyObject* +SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { +#if !defined(SWIG_PYTHON_OUTPUT_TUPLE) + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + PyList_SetItem(result, 0, o2); + } + PyList_Append(result,obj); + Py_DECREF(obj); + } + return result; +#else + PyObject* o2; + PyObject* o3; + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyTuple_Check(result)) { + o2 = result; + result = PyTuple_New(1); + PyTuple_SET_ITEM(result, 0, o2); + } + o3 = PyTuple_New(1); + PyTuple_SET_ITEM(o3, 0, obj); + o2 = result; + result = PySequence_Concat(o2, o3); + Py_DECREF(o2); + Py_DECREF(o3); + } + return result; +#endif +} + +/* Unpack the argument tuple */ + +SWIGINTERN int +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) +{ + if (!args) { + if (!min && !max) { + return 1; + } else { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; + } + } + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; + } else { + register Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + register int i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } +} + +/* A functor is a function object with one single object argument */ +#if PY_VERSION_HEX >= 0x02020000 +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); +#else +#define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); +#endif + +/* + Helper for static pointer initialization for both C and C++ code, for example + static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); +*/ +#ifdef __cplusplus +#define SWIG_STATIC_POINTER(var) var +#else +#define SWIG_STATIC_POINTER(var) var = 0; if (!var) var +#endif + +/* ----------------------------------------------------------------------------- + * Pointer declarations + * ----------------------------------------------------------------------------- */ + +/* Flags for new pointer objects */ +#define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) +#define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) + +#define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* cc-mode */ +#endif +#endif + +/* How to access Py_None */ +#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) +# ifndef SWIG_PYTHON_NO_BUILD_NONE +# ifndef SWIG_PYTHON_BUILD_NONE +# define SWIG_PYTHON_BUILD_NONE +# endif +# endif +#endif + +#ifdef SWIG_PYTHON_BUILD_NONE +# ifdef Py_None +# undef Py_None +# define Py_None SWIG_Py_None() +# endif +SWIGRUNTIMEINLINE PyObject * +_SWIG_Py_None(void) +{ + PyObject *none = Py_BuildValue((char*)""); + Py_DECREF(none); + return none; +} +SWIGRUNTIME PyObject * +SWIG_Py_None(void) +{ + static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); + return none; +} +#endif + +/* The python void return value */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) +{ + PyObject *none = Py_None; + Py_INCREF(none); + return none; +} + +/* PySwigClientData */ + +typedef struct { + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; +} PySwigClientData; + +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) +{ + PySwigClientData *data = (PySwigClientData *)ty->clientdata; + return data ? data->implicitconv : 0; +} + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_ExceptionType(swig_type_info *desc) { + PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); +} + + +SWIGRUNTIME PySwigClientData * +PySwigClientData_New(PyObject* obj) +{ + if (!obj) { + return 0; + } else { + PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData)); + /* the klass element */ + data->klass = obj; + Py_INCREF(data->klass); + /* the newraw method and newargs arguments used to create a new raw instance */ + if (PyClass_Check(obj)) { + data->newraw = 0; + data->newargs = obj; + Py_INCREF(obj); + } else { +#if (PY_VERSION_HEX < 0x02020000) + data->newraw = 0; +#else + data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); +#endif + if (data->newraw) { + Py_INCREF(data->newraw); + data->newargs = PyTuple_New(1); + PyTuple_SetItem(data->newargs, 0, obj); + } else { + data->newargs = obj; + } + Py_INCREF(data->newargs); + } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + int flags; + Py_INCREF(data->destroy); + flags = PyCFunction_GET_FLAGS(data->destroy); +#ifdef METH_O + data->delargs = !(flags & (METH_O)); +#else + data->delargs = 0; +#endif + } else { + data->delargs = 0; + } + data->implicitconv = 0; + return data; + } +} + +SWIGRUNTIME void +PySwigClientData_Del(PySwigClientData* data) +{ + Py_XDECREF(data->newraw); + Py_XDECREF(data->newargs); + Py_XDECREF(data->destroy); +} + +/* =============== PySwigObject =====================*/ + +typedef struct { + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; +} PySwigObject; + +SWIGRUNTIME PyObject * +PySwigObject_long(PySwigObject *v) +{ + return PyLong_FromVoidPtr(v->ptr); +} + +SWIGRUNTIME PyObject * +PySwigObject_format(const char* fmt, PySwigObject *v) +{ + PyObject *res = NULL; + PyObject *args = PyTuple_New(1); + if (args) { + if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) { + PyObject *ofmt = PyString_FromString(fmt); + if (ofmt) { + res = PyString_Format(ofmt,args); + Py_DECREF(ofmt); + } + Py_DECREF(args); + } + } + return res; +} + +SWIGRUNTIME PyObject * +PySwigObject_oct(PySwigObject *v) +{ + return PySwigObject_format("%o",v); +} + +SWIGRUNTIME PyObject * +PySwigObject_hex(PySwigObject *v) +{ + return PySwigObject_format("%x",v); +} + +SWIGRUNTIME PyObject * +#ifdef METH_NOARGS +PySwigObject_repr(PySwigObject *v) +#else +PySwigObject_repr(PySwigObject *v, PyObject *args) +#endif +{ + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *hex = PySwigObject_hex(v); + PyObject *repr = PyString_FromFormat("<Swig Object of type '%s' at 0x%s>", name, PyString_AsString(hex)); + Py_DECREF(hex); + if (v->next) { +#ifdef METH_NOARGS + PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next); +#else + PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args); +#endif + PyString_ConcatAndDel(&repr,nrep); + } + return repr; +} + +SWIGRUNTIME int +PySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) +{ +#ifdef METH_NOARGS + PyObject *repr = PySwigObject_repr(v); +#else + PyObject *repr = PySwigObject_repr(v, NULL); +#endif + if (repr) { + fputs(PyString_AsString(repr), fp); + Py_DECREF(repr); + return 0; + } else { + return 1; + } +} + +SWIGRUNTIME PyObject * +PySwigObject_str(PySwigObject *v) +{ + char result[SWIG_BUFFER_SIZE]; + return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? + PyString_FromString(result) : 0; +} + +SWIGRUNTIME int +PySwigObject_compare(PySwigObject *v, PySwigObject *w) +{ + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); +} + +SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); + +SWIGRUNTIME PyTypeObject* +PySwigObject_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); + return type; +} + +SWIGRUNTIMEINLINE int +PySwigObject_Check(PyObject *op) { + return ((op)->ob_type == PySwigObject_type()) + || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0); +} + +SWIGRUNTIME PyObject * +PySwigObject_New(void *ptr, swig_type_info *ty, int own); + +SWIGRUNTIME void +PySwigObject_dealloc(PyObject *v) +{ + PySwigObject *sobj = (PySwigObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; + if (data->delargs) { + /* we need to create a temporal object to carry the destroy operation */ + PyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0); + res = SWIG_Python_CallFunctor(destroy, tmp); + Py_DECREF(tmp); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + Py_XDECREF(res); + } +#if !defined(SWIG_PYTHON_SILENT_MEMLEAK) + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + } +#endif + } + Py_XDECREF(next); + PyObject_DEL(v); +} + +SWIGRUNTIME PyObject* +PySwigObject_append(PyObject* v, PyObject* next) +{ + PySwigObject *sobj = (PySwigObject *) v; +#ifndef METH_O + PyObject *tmp = 0; + if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; + next = tmp; +#endif + if (!PySwigObject_Check(next)) { + return NULL; + } + sobj->next = next; + Py_INCREF(next); + return SWIG_Py_Void(); +} + +SWIGRUNTIME PyObject* +#ifdef METH_NOARGS +PySwigObject_next(PyObject* v) +#else +PySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + PySwigObject *sobj = (PySwigObject *) v; + if (sobj->next) { + Py_INCREF(sobj->next); + return sobj->next; + } else { + return SWIG_Py_Void(); + } +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +PySwigObject_disown(PyObject *v) +#else +PySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + PySwigObject *sobj = (PySwigObject *)v; + sobj->own = 0; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +#ifdef METH_NOARGS +PySwigObject_acquire(PyObject *v) +#else +PySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +#endif +{ + PySwigObject *sobj = (PySwigObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +PySwigObject_own(PyObject *v, PyObject *args) +{ + PyObject *val = 0; +#if (PY_VERSION_HEX < 0x02020000) + if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) +#else + if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) +#endif + { + return NULL; + } + else + { + PySwigObject *sobj = (PySwigObject *)v; + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { +#ifdef METH_NOARGS + if (PyObject_IsTrue(val)) { + PySwigObject_acquire(v); + } else { + PySwigObject_disown(v); + } +#else + if (PyObject_IsTrue(val)) { + PySwigObject_acquire(v,args); + } else { + PySwigObject_disown(v,args); + } +#endif + } + return obj; + } +} + +#ifdef METH_O +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)PySwigObject_append, METH_O, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)PySwigObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_NOARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#else +static PyMethodDef +swigobject_methods[] = { + {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, + {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, + {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, + {(char *)"append", (PyCFunction)PySwigObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, + {(char *)"next", (PyCFunction)PySwigObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, + {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_VARARGS, (char *)"returns object representation"}, + {0, 0, 0, 0} +}; +#endif + +#if PY_VERSION_HEX < 0x02020000 +SWIGINTERN PyObject * +PySwigObject_getattr(PySwigObject *sobj,char *name) +{ + return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); +} +#endif + +SWIGRUNTIME PyTypeObject* +_PySwigObject_type(void) { + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; + + static PyNumberMethods PySwigObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + (binaryfunc)0, /*nb_divide*/ + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + (coercion)0, /*nb_coerce*/ + (unaryfunc)PySwigObject_long, /*nb_int*/ + (unaryfunc)PySwigObject_long, /*nb_long*/ + (unaryfunc)0, /*nb_float*/ + (unaryfunc)PySwigObject_oct, /*nb_oct*/ + (unaryfunc)PySwigObject_hex, /*nb_hex*/ +#if PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ +#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ +#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ + 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ +#endif + }; + + static PyTypeObject pyswigobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + (char *)"PySwigObject", /* tp_name */ + sizeof(PySwigObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PySwigObject_dealloc, /* tp_dealloc */ + (printfunc)PySwigObject_print, /* tp_print */ +#if PY_VERSION_HEX < 0x02020000 + (getattrfunc)PySwigObject_getattr, /* tp_getattr */ +#else + (getattrfunc)0, /* tp_getattr */ +#endif + (setattrfunc)0, /* tp_setattr */ + (cmpfunc)PySwigObject_compare, /* tp_compare */ + (reprfunc)PySwigObject_repr, /* tp_repr */ + &PySwigObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)PySwigObject_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + pyswigobject_type = tmp; + pyswigobject_type.ob_type = &PyType_Type; + type_init = 1; + } + return &pyswigobject_type; +} + +SWIGRUNTIME PyObject * +PySwigObject_New(void *ptr, swig_type_info *ty, int own) +{ + PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; + } + return (PyObject *)sobj; +} + +/* ----------------------------------------------------------------------------- + * Implements a simple Swig Packed type, and use it instead of string + * ----------------------------------------------------------------------------- */ + +typedef struct { + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; +} PySwigPacked; + +SWIGRUNTIME int +PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) +{ + char result[SWIG_BUFFER_SIZE]; + fputs("<Swig Packed ", fp); + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + fputs("at ", fp); + fputs(result, fp); + } + fputs(v->ty->name,fp); + fputs(">", fp); + return 0; +} + +SWIGRUNTIME PyObject * +PySwigPacked_repr(PySwigPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name); + } else { + return PyString_FromFormat("<Swig Packed %s>", v->ty->name); + } +} + +SWIGRUNTIME PyObject * +PySwigPacked_str(PySwigPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ + return PyString_FromFormat("%s%s", result, v->ty->name); + } else { + return PyString_FromString(v->ty->name); + } +} + +SWIGRUNTIME int +PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w) +{ + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); +} + +SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); + +SWIGRUNTIME PyTypeObject* +PySwigPacked_type(void) { + static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); + return type; +} + +SWIGRUNTIMEINLINE int +PySwigPacked_Check(PyObject *op) { + return ((op)->ob_type == _PySwigPacked_type()) + || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0); +} + +SWIGRUNTIME void +PySwigPacked_dealloc(PyObject *v) +{ + if (PySwigPacked_Check(v)) { + PySwigPacked *sobj = (PySwigPacked *) v; + free(sobj->pack); + } + PyObject_DEL(v); +} + +SWIGRUNTIME PyTypeObject* +_PySwigPacked_type(void) { + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; + static PyTypeObject pyswigpacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + (char *)"PySwigPacked", /* tp_name */ + sizeof(PySwigPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PySwigPacked_dealloc, /* tp_dealloc */ + (printfunc)PySwigPacked_print, /* tp_print */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ + (cmpfunc)PySwigPacked_compare, /* tp_compare */ + (reprfunc)PySwigPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)PySwigPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + pyswigpacked_type = tmp; + pyswigpacked_type.ob_type = &PyType_Type; + type_init = 1; + } + return &pyswigpacked_type; +} + +SWIGRUNTIME PyObject * +PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty) +{ + PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_DEL((PyObject *) sobj); + sobj = 0; + } + } + return (PyObject *) sobj; +} + +SWIGRUNTIME swig_type_info * +PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size) +{ + if (PySwigPacked_Check(obj)) { + PySwigPacked *sobj = (PySwigPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } +} + +/* ----------------------------------------------------------------------------- + * pointers/data manipulation + * ----------------------------------------------------------------------------- */ + +SWIGRUNTIMEINLINE PyObject * +_SWIG_This(void) +{ + return PyString_FromString("this"); +} + +SWIGRUNTIME PyObject * +SWIG_This(void) +{ + static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); + return swig_this; +} + +/* #define SWIG_PYTHON_SLOW_GETSET_THIS */ + +SWIGRUNTIME PySwigObject * +SWIG_Python_GetSwigThis(PyObject *pyobj) +{ + if (PySwigObject_Check(pyobj)) { + return (PySwigObject *) pyobj; + } else { + PyObject *obj = 0; +#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); + } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + } else { +#ifdef PyWeakref_CheckProxy + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } +#endif + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } + } + } +#else + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } +#endif + if (obj && !PySwigObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + PySwigObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (PySwigObject *)obj; + } +} + +/* Acquire a pointer value */ + +SWIGRUNTIME int +SWIG_Python_AcquirePtr(PyObject *obj, int own) { + if (own == SWIG_POINTER_OWN) { + PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; + } + } + return 0; +} + +/* Convert a pointer value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { + if (!obj) return SWIG_ERROR; + if (obj == Py_None) { + if (ptr) *ptr = 0; + return SWIG_OK; + } else { + PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) { + sobj = (PySwigObject *)sobj->next; + } else { + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; + } + } + break; + } + } + } else { + if (ptr) *ptr = vptr; + break; + } + } + if (sobj) { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + return SWIG_OK; + } else { + int res = SWIG_ERROR; + if (flags & SWIG_POINTER_IMPLICIT_CONV) { + PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + Py_DECREF(impconv); + } + } + } + } + return res; + } + } +} + +/* Convert a function ptr value */ + +SWIGRUNTIME int +SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); + } else { + void *vptr = 0; + + /* here we get the method pointer for callbacks */ + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) { + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; + if (!desc) return SWIG_ERROR; + } + if (ty) { + swig_cast_info *tc = SWIG_TypeCheck(desc,ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } + } else { + *ptr = vptr; + } + return SWIG_OK; + } +} + +/* Convert a packed value value */ + +SWIGRUNTIME int +SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; + } + } + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * Create a new pointer object + * ----------------------------------------------------------------------------- */ + +/* + Create a new instance object, whitout calling __init__, and set the + 'this' attribute. +*/ + +SWIGRUNTIME PyObject* +SWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this) +{ +#if (PY_VERSION_HEX >= 0x02020000) + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); + if (inst) { +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + PyDict_SetItem(dict, SWIG_This(), swig_this); + } + } +#else + PyObject *key = SWIG_This(); + PyObject_SetAttr(inst, key, swig_this); +#endif + } + } else { + PyObject *dict = PyDict_New(); + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + } + return inst; +#else +#if (PY_VERSION_HEX >= 0x02010000) + PyObject *inst; + PyObject *dict = PyDict_New(); + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + return (PyObject *) inst; +#else + PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); + if (inst == NULL) { + return NULL; + } + inst->in_class = (PyClassObject *)data->newargs; + Py_INCREF(inst->in_class); + inst->in_dict = PyDict_New(); + if (inst->in_dict == NULL) { + Py_DECREF(inst); + return NULL; + } +#ifdef Py_TPFLAGS_HAVE_WEAKREFS + inst->in_weakreflist = NULL; +#endif +#ifdef Py_TPFLAGS_GC + PyObject_GC_Init(inst); +#endif + PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); + return (PyObject *) inst; +#endif +#endif +} + +SWIGRUNTIME void +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) +{ + PyObject *dict; +#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + PyDict_SetItem(dict, SWIG_This(), swig_this); + return; + } +#endif + dict = PyObject_GetAttrString(inst, (char*)"__dict__"); + PyDict_SetItem(dict, SWIG_This(), swig_this); + Py_DECREF(dict); +} + + +SWIGINTERN PyObject * +SWIG_Python_InitShadowInstance(PyObject *args) { + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { + return NULL; + } else { + PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + PySwigObject_append((PyObject*) sthis, obj[1]); + } else { + SWIG_Python_SetSwigThis(obj[0], obj[1]); + } + return SWIG_Py_Void(); + } +} + +/* Create a new pointer object */ + +SWIGRUNTIME PyObject * +SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { + if (!ptr) { + return SWIG_Py_Void(); + } else { + int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + PyObject *robj = PySwigObject_New(ptr, type, own); + PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0; + if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + if (inst) { + Py_DECREF(robj); + robj = inst; + } + } + return robj; + } +} + +/* Create a new packed object */ + +SWIGRUNTIMEINLINE PyObject * +SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { + return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); +} + +/* -----------------------------------------------------------------------------* + * Get type list + * -----------------------------------------------------------------------------*/ + +#ifdef SWIG_LINK_RUNTIME +void *SWIG_ReturnGlobalTypeList(void *); +#endif + +SWIGRUNTIME swig_module_info * +SWIG_Python_GetModule(void) { + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { +#ifdef SWIG_LINK_RUNTIME + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); +#else + type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, + (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } +#endif + } + return (swig_module_info *) type_pointer; +} + +#if PY_MAJOR_VERSION < 2 +/* PyModule_AddObject function was introduced in Python 2.0. The following function + is copied out of Python/modsupport.c in python version 2.3.4 */ +SWIGINTERN int +PyModule_AddObject(PyObject *m, char *name, PyObject *o) +{ + PyObject *dict; + if (!PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs module as first arg"); + return SWIG_ERROR; + } + if (!o) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs non-NULL value"); + return SWIG_ERROR; + } + + dict = PyModule_GetDict(m); + if (dict == NULL) { + /* Internal error -- modules must have a dict! */ + PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", + PyModule_GetName(m)); + return SWIG_ERROR; + } + if (PyDict_SetItemString(dict, name, o)) + return SWIG_ERROR; + Py_DECREF(o); + return SWIG_OK; +} +#endif + +SWIGRUNTIME void +SWIG_Python_DestroyModule(void *vptr) +{ + swig_module_info *swig_module = (swig_module_info *) vptr; + swig_type_info **types = swig_module->types; + size_t i; + for (i =0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + PySwigClientData *data = (PySwigClientData *) ty->clientdata; + if (data) PySwigClientData_Del(data); + } + } + Py_DECREF(SWIG_This()); +} + +SWIGRUNTIME void +SWIG_Python_SetModule(swig_module_info *swig_module) { + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ + + PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, + swig_empty_runtime_method_table); + PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); + if (pointer && module) { + PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); + } else { + Py_XDECREF(pointer); + } +} + +/* The python cached type query */ +SWIGRUNTIME PyObject * +SWIG_Python_TypeCache(void) { + static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); + return cache; +} + +SWIGRUNTIME swig_type_info * +SWIG_Python_TypeQuery(const char *type) +{ + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = PyString_FromString(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { + descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); + } else { + swig_module_info *swig_module = SWIG_Python_GetModule(); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { + obj = PyCObject_FromVoidPtr(descriptor, NULL); + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } + } + Py_DECREF(key); + return descriptor; +} + +/* + For backward compatibility only +*/ +#define SWIG_POINTER_EXCEPTION 0 +#define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) +#define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) + +SWIGRUNTIME int +SWIG_Python_AddErrMesg(const char* mesg, int infront) +{ + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str)); + } else { + PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); + } + Py_DECREF(old_str); + } + return 1; + } else { + return 0; + } +} + +SWIGRUNTIME int +SWIG_Python_ArgFail(int argnum) +{ + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } +} + +SWIGRUNTIMEINLINE const char * +PySwigObject_GetDesc(PyObject *self) +{ + PySwigObject *v = (PySwigObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : (char*)""; +} + +SWIGRUNTIME void +SWIG_Python_TypeError(const char *type, PyObject *obj) +{ + if (type) { +#if defined(SWIG_COBJECT_TYPES) + if (obj && PySwigObject_Check(obj)) { + const char *otype = (const char *) PySwigObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received", + type, otype); + return; + } + } else +#endif + { + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + const char *cstr = str ? PyString_AsString(str) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + Py_XDECREF(str); + return; + } + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } +} + + +/* Convert a pointer value, signal an exception on a type mismatch */ +SWIGRUNTIME void * +SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); + if (flags & SWIG_POINTER_EXCEPTION) { + SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); + SWIG_Python_ArgFail(argnum); + } + } + return result; +} + + +#ifdef __cplusplus +#if 0 +{ /* cc-mode */ +#endif +} +#endif + + + +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) + +#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else + + + +/* -------- TYPES TABLE (BEGIN) -------- */ + +#define SWIGTYPE_p_NTSTATUS swig_types[0] +#define SWIGTYPE_p_TALLOC_CTX swig_types[1] +#define SWIGTYPE_p_char swig_types[2] +#define SWIGTYPE_p_cli_credentials swig_types[3] +#define SWIGTYPE_p_int swig_types[4] +#define SWIGTYPE_p_loadparm_context swig_types[5] +#define SWIGTYPE_p_loadparm_service swig_types[6] +#define SWIGTYPE_p_long_long swig_types[7] +#define SWIGTYPE_p_param_context swig_types[8] +#define SWIGTYPE_p_param_opt swig_types[9] +#define SWIGTYPE_p_param_section swig_types[10] +#define SWIGTYPE_p_short swig_types[11] +#define SWIGTYPE_p_signed_char swig_types[12] +#define SWIGTYPE_p_unsigned_char swig_types[13] +#define SWIGTYPE_p_unsigned_int swig_types[14] +#define SWIGTYPE_p_unsigned_long_long swig_types[15] +#define SWIGTYPE_p_unsigned_short swig_types[16] +static swig_type_info *swig_types[18]; +static swig_module_info swig_module = {swig_types, 17, 0, 0, 0, 0}; +#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) +#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) + +/* -------- TYPES TABLE (END) -------- */ + +#if (PY_VERSION_HEX <= 0x02000000) +# if !defined(SWIG_PYTHON_CLASSIC) +# error "This python version requires swig to be run with the '-classic' option" +# endif +#endif +#if (PY_VERSION_HEX <= 0x02020000) +# error "This python version requires swig to be run with the '-nomodern' option" +#endif +#if (PY_VERSION_HEX <= 0x02020000) +# error "This python version requires swig to be run with the '-nomodernargs' option" +#endif +#ifndef METH_O +# error "This python version requires swig to be run with the '-nofastunpack' option" +#endif +#ifdef SWIG_TypeQuery +# undef SWIG_TypeQuery +#endif +#define SWIG_TypeQuery SWIG_Python_TypeQuery + +/*----------------------------------------------- + @(target):= _credentials.so + ------------------------------------------------*/ +#define SWIG_init init_credentials + +#define SWIG_name "_credentials" + +#define SWIGVERSION 0x010335 +#define SWIG_VERSION SWIGVERSION + + +#define SWIG_as_voidptr(a) (void *)((const void *)(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) + + + +/* Include headers */ +#include <stdint.h> +#include <stdbool.h> + +#include "includes.h" +#include "auth/credentials/credentials.h" +#include "param/param.h" +#include "lib/cmdline/credentials.h" +typedef struct cli_credentials cli_credentials; + + + #define SWIG_From_long PyInt_FromLong + + +SWIGINTERNINLINE PyObject * +SWIG_From_int (int value) +{ + return SWIG_From_long (value); +} + + +#include "librpc/gen_ndr/samr.h" /* for struct samr_Password */ + +SWIGINTERN cli_credentials *new_cli_credentials(){ + return cli_credentials_init(NULL); + } + +SWIGINTERN swig_type_info* +SWIG_pchar_descriptor(void) +{ + static int init = 0; + static swig_type_info* info = 0; + if (!init) { + info = SWIG_TypeQuery("_p_char"); + init = 1; + } + return info; +} + + +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtrAndSize(const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + return pchar_descriptor ? + SWIG_NewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); + } else { + return PyString_FromStringAndSize(carray, (int)(size)); + } + } else { + return SWIG_Py_Void(); + } +} + + +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtr(const char *cptr) +{ + return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); +} + + +SWIGINTERN int +SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) +{ + if (PyString_Check(obj)) { + char *cstr; Py_ssize_t len; + PyString_AsStringAndSize(obj, &cstr, &len); + if (cptr) { + if (alloc) { + /* + In python the user should not be able to modify the inner + string representation. To warranty that, if you define + SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string + buffer is always returned. + + The default behavior is just to return the pointer value, + so, be careful. + */ +#if defined(SWIG_PYTHON_SAFE_CSTRINGS) + if (*alloc != SWIG_OLDOBJ) +#else + if (*alloc == SWIG_NEWOBJ) +#endif + { + *cptr = (char *)memcpy((char *)malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); + *alloc = SWIG_NEWOBJ; + } + else { + *cptr = cstr; + *alloc = SWIG_OLDOBJ; + } + } else { + *cptr = PyString_AsString(obj); + } + } + if (psize) *psize = len + 1; + return SWIG_OK; + } else { + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + } + return SWIG_TypeError; +} + + + + + +#include <limits.h> +#if !defined(SWIG_NO_LLONG_MAX) +# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) +# define LLONG_MAX __LONG_LONG_MAX__ +# define LLONG_MIN (-LLONG_MAX - 1LL) +# define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) +# endif +#endif + + +SWIGINTERN int +SWIG_AsVal_double (PyObject *obj, double *val) +{ + int res = SWIG_TypeError; + if (PyFloat_Check(obj)) { + if (val) *val = PyFloat_AsDouble(obj); + return SWIG_OK; + } else if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else if (PyLong_Check(obj)) { + double v = PyLong_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + double d = PyFloat_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = d; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); + } else { + PyErr_Clear(); + } + } + } +#endif + return res; +} + + +#include <float.h> + + +#include <math.h> + + +SWIGINTERNINLINE int +SWIG_CanCastAsInteger(double *d, double min, double max) { + double x = *d; + if ((min <= x && x <= max)) { + double fx = floor(x); + double cx = ceil(x); + double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ + if ((errno == EDOM) || (errno == ERANGE)) { + errno = 0; + } else { + double summ, reps, diff; + if (rd < x) { + diff = x - rd; + } else if (rd > x) { + diff = rd - x; + } else { + return 1; + } + summ = rd + x; + reps = diff/summ; + if (reps < 8*DBL_EPSILON) { + *d = rd; + return 1; + } + } + } + return 0; +} + + +SWIGINTERN int +SWIG_AsVal_long (PyObject *obj, long* val) +{ + if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else if (PyLong_Check(obj)) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + long v = PyInt_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + double d; + int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); + if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { + if (val) *val = (long)(d); + return res; + } + } + } +#endif + return SWIG_TypeError; +} + + +SWIGINTERN int +SWIG_AsVal_int (PyObject * obj, int *val) +{ + long v; + int res = SWIG_AsVal_long (obj, &v); + if (SWIG_IsOK(res)) { + if ((v < INT_MIN || v > INT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (int)(v); + } + } + return res; +} + + +SWIGINTERNINLINE PyObject* + SWIG_From_bool (bool value) +{ + return PyBool_FromLong(value ? 1 : 0); +} + +SWIGINTERN void delete_cli_credentials(cli_credentials *self){ talloc_free(self); } + +struct cli_credentials *cli_credentials_from_py_object(PyObject *py_obj) +{ + struct cli_credentials *ret; + + if (py_obj == Py_None) { + return cli_credentials_init_anon(NULL); + } + + if (SWIG_ConvertPtr(py_obj, (void *)&ret, SWIGTYPE_p_cli_credentials, 0 | 0 ) < 0) { + return NULL; + } + return ret; +} + + +#ifdef __cplusplus +extern "C" { +#endif +SWIGINTERN PyObject *_wrap_new_Credentials(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + cli_credentials *result = 0 ; + + if (!SWIG_Python_UnpackTuple(args,"new_Credentials",0,0,0)) SWIG_fail; + result = (cli_credentials *)new_cli_credentials(); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_cli_credentials, SWIG_POINTER_NEW | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_get_username(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *result = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_username",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_get_username" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (char *)cli_credentials_get_username(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_username(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *arg2 = (char *) 0 ; + enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "value",(char *) "obtained", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_username",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_username" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_set_username" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = (char *)(buf2); + } + if (obj2) { + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Credentials_set_username" "', argument " "3"" of type '" "enum credentials_obtained""'"); + } + arg3 = (enum credentials_obtained)(val3); + } + result = (bool)cli_credentials_set_username(arg1,(char const *)arg2,arg3); + resultobj = SWIG_From_bool((bool)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_get_password(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *result = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_password",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_get_password" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (char *)cli_credentials_get_password(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_password(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *arg2 = (char *) 0 ; + enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "val",(char *) "obtained", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_password",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_password" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_set_password" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = (char *)(buf2); + } + if (obj2) { + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Credentials_set_password" "', argument " "3"" of type '" "enum credentials_obtained""'"); + } + arg3 = (enum credentials_obtained)(val3); + } + result = (bool)cli_credentials_set_password(arg1,(char const *)arg2,arg3); + resultobj = SWIG_From_bool((bool)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_get_domain(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *result = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_domain",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_get_domain" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (char *)cli_credentials_get_domain(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_domain(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *arg2 = (char *) 0 ; + enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "val",(char *) "obtained", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_domain",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_domain" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_set_domain" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = (char *)(buf2); + } + if (obj2) { + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Credentials_set_domain" "', argument " "3"" of type '" "enum credentials_obtained""'"); + } + arg3 = (enum credentials_obtained)(val3); + } + result = (bool)cli_credentials_set_domain(arg1,(char const *)arg2,arg3); + resultobj = SWIG_From_bool((bool)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_get_realm(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *result = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_realm",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_get_realm" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (char *)cli_credentials_get_realm(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_realm(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *arg2 = (char *) 0 ; + enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "val",(char *) "obtained", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_realm",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_realm" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_set_realm" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = (char *)(buf2); + } + if (obj2) { + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Credentials_set_realm" "', argument " "3"" of type '" "enum credentials_obtained""'"); + } + arg3 = (enum credentials_obtained)(val3); + } + result = (bool)cli_credentials_set_realm(arg1,(char const *)arg2,arg3); + resultobj = SWIG_From_bool((bool)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_kerberos_state(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + enum credentials_use_kerberos arg2 ; + void *argp1 = 0 ; + int res1 = 0 ; + int val2 ; + int ecode2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "use_kerberos", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:Credentials_set_kerberos_state",kwnames,&obj0,&obj1)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_kerberos_state" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + ecode2 = SWIG_AsVal_int(obj1, &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Credentials_set_kerberos_state" "', argument " "2"" of type '" "enum credentials_use_kerberos""'"); + } + arg2 = (enum credentials_use_kerberos)(val2); + } + cli_credentials_set_kerberos_state(arg1,arg2); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_parse_string(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *arg2 = (char *) 0 ; + enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "text",(char *) "obtained", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_parse_string",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_parse_string" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_parse_string" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = (char *)(buf2); + } + if (obj2) { + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Credentials_parse_string" "', argument " "3"" of type '" "enum credentials_obtained""'"); + } + arg3 = (enum credentials_obtained)(val3); + } + cli_credentials_parse_string(arg1,(char const *)arg2,arg3); + resultobj = SWIG_Py_Void(); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_get_bind_dn(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *result = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_bind_dn",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_get_bind_dn" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (char *)cli_credentials_get_bind_dn(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_bind_dn(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *arg2 = (char *) 0 ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "bind_dn", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:Credentials_set_bind_dn",kwnames,&obj0,&obj1)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_bind_dn" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_set_bind_dn" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = (char *)(buf2); + } + result = (bool)cli_credentials_set_bind_dn(arg1,(char const *)arg2); + resultobj = SWIG_From_bool((bool)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_anonymous(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_set_anonymous",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_anonymous" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + cli_credentials_set_anonymous(arg1); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_get_workstation(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *result = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_workstation",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_get_workstation" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (char *)cli_credentials_get_workstation(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_workstation(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + char *arg2 = (char *) 0 ; + enum credentials_obtained arg3 = (enum credentials_obtained) CRED_SPECIFIED ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + int val3 ; + int ecode3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "workstation",(char *) "obtained", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OOO:Credentials_set_workstation",kwnames,&obj0,&obj1,&obj2)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_workstation" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_set_workstation" "', argument " "2"" of type '" "char const *""'"); + } + arg2 = (char *)(buf2); + } + if (obj2) { + ecode3 = SWIG_AsVal_int(obj2, &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Credentials_set_workstation" "', argument " "3"" of type '" "enum credentials_obtained""'"); + } + arg3 = (enum credentials_obtained)(val3); + } + result = (bool)cli_credentials_set_workstation(arg1,(char const *)arg2,arg3); + resultobj = SWIG_From_bool((bool)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; +fail: + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_machine_account(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + struct loadparm_context *arg2 = (struct loadparm_context *) 0 ; + NTSTATUS result; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "lp_ctx", NULL + }; + + arg1 = NULL; + arg2 = loadparm_init(NULL); + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:Credentials_set_machine_account",kwnames,&obj0,&obj1)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_machine_account" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_loadparm_context, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_set_machine_account" "', argument " "2"" of type '" "struct loadparm_context *""'"); + } + arg2 = (struct loadparm_context *)(argp2); + } + result = cli_credentials_set_machine_account(arg1,arg2); + resultobj = SWIG_NewPointerObj((NTSTATUS *)memcpy((NTSTATUS *)malloc(sizeof(NTSTATUS)),&result,sizeof(NTSTATUS)), SWIGTYPE_p_NTSTATUS, SWIG_POINTER_OWN | 0 ); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_guess(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + struct loadparm_context *arg2 = (struct loadparm_context *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp2 = 0 ; + int res2 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + char * kwnames[] = { + (char *) "self",(char *) "lp_ctx", NULL + }; + + arg1 = NULL; + arg2 = loadparm_init(NULL); + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|OO:Credentials_guess",kwnames,&obj0,&obj1)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_guess" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + if (obj1) { + res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_loadparm_context, 0 | 0 ); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Credentials_guess" "', argument " "2"" of type '" "struct loadparm_context *""'"); + } + arg2 = (struct loadparm_context *)(argp2); + } + cli_credentials_guess(arg1,arg2); + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_is_anonymous(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_is_anonymous",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_is_anonymous" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (bool)cli_credentials_is_anonymous(arg1); + resultobj = SWIG_From_bool((bool)(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_get_nt_hash(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + TALLOC_CTX *arg2 = (TALLOC_CTX *) 0 ; + struct samr_Password *result = 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + arg2 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_get_nt_hash",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_get_nt_hash" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (struct samr_Password *)cli_credentials_get_nt_hash(arg1,arg2); + resultobj = PyString_FromStringAndSize((char *)result->hash, 16); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_authentication_requested(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_authentication_requested",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_authentication_requested" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (bool)cli_credentials_authentication_requested(arg1); + resultobj = SWIG_From_bool((bool)(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_wrong_password(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_wrong_password",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_wrong_password" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (bool)cli_credentials_wrong_password(arg1); + resultobj = SWIG_From_bool((bool)(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_Credentials_set_cmdline_callbacks(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + bool result; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:Credentials_set_cmdline_callbacks",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Credentials_set_cmdline_callbacks" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + result = (bool)cli_credentials_set_cmdline_callbacks(arg1); + resultobj = SWIG_From_bool((bool)(result)); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *_wrap_delete_Credentials(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) { + PyObject *resultobj = 0; + cli_credentials *arg1 = (cli_credentials *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject * obj0 = 0 ; + char * kwnames[] = { + (char *) "self", NULL + }; + + arg1 = NULL; + if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)"|O:delete_Credentials",kwnames,&obj0)) SWIG_fail; + if (obj0) { + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_cli_credentials, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_Credentials" "', argument " "1"" of type '" "cli_credentials *""'"); + } + arg1 = (cli_credentials *)(argp1); + } + delete_cli_credentials(arg1); + + resultobj = SWIG_Py_Void(); + return resultobj; +fail: + return NULL; +} + + +SWIGINTERN PyObject *Credentials_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *obj; + if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_cli_credentials, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject *Credentials_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + return SWIG_Python_InitShadowInstance(args); +} + +static PyMethodDef SwigMethods[] = { + { (char *)"new_Credentials", (PyCFunction)_wrap_new_Credentials, METH_NOARGS, NULL}, + { (char *)"Credentials_get_username", (PyCFunction) _wrap_Credentials_get_username, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.get_username() -> username\n" + "Obtain username.\n" + ""}, + { (char *)"Credentials_set_username", (PyCFunction) _wrap_Credentials_set_username, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_username(name, obtained=CRED_SPECIFIED) -> None\n" + "Change username.\n" + ""}, + { (char *)"Credentials_get_password", (PyCFunction) _wrap_Credentials_get_password, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.get_password() -> password\n" + "Obtain password.\n" + ""}, + { (char *)"Credentials_set_password", (PyCFunction) _wrap_Credentials_set_password, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_password(password, obtained=CRED_SPECIFIED) -> None\n" + "Change password.\n" + ""}, + { (char *)"Credentials_get_domain", (PyCFunction) _wrap_Credentials_get_domain, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_set_domain", (PyCFunction) _wrap_Credentials_set_domain, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_domain(domain, obtained=CRED_SPECIFIED) -> None\n" + "Change domain name.\n" + ""}, + { (char *)"Credentials_get_realm", (PyCFunction) _wrap_Credentials_get_realm, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.get_realm() -> realm\n" + "Obtain realm name.\n" + ""}, + { (char *)"Credentials_set_realm", (PyCFunction) _wrap_Credentials_set_realm, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_realm(realm, obtained=CRED_SPECIFIED) -> None\n" + "Change realm name.\n" + ""}, + { (char *)"Credentials_set_kerberos_state", (PyCFunction) _wrap_Credentials_set_kerberos_state, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_parse_string", (PyCFunction) _wrap_Credentials_parse_string, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.parse_string(text, obtained=CRED_SPECIFIED) -> None\n" + "Parse credentials string.\n" + ""}, + { (char *)"Credentials_get_bind_dn", (PyCFunction) _wrap_Credentials_get_bind_dn, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.get_bind_dn() -> bind dn\n" + "Obtain bind DN.\n" + ""}, + { (char *)"Credentials_set_bind_dn", (PyCFunction) _wrap_Credentials_set_bind_dn, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_bind_dn(bind_dn) -> None\n" + "Change bind DN.\n" + ""}, + { (char *)"Credentials_set_anonymous", (PyCFunction) _wrap_Credentials_set_anonymous, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_anonymous() -> None\n" + "Use anonymous credentials.\n" + ""}, + { (char *)"Credentials_get_workstation", (PyCFunction) _wrap_Credentials_get_workstation, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_set_workstation", (PyCFunction) _wrap_Credentials_set_workstation, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_set_machine_account", (PyCFunction) _wrap_Credentials_set_machine_account, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_guess", (PyCFunction) _wrap_Credentials_guess, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_is_anonymous", (PyCFunction) _wrap_Credentials_is_anonymous, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_get_nt_hash", (PyCFunction) _wrap_Credentials_get_nt_hash, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_authentication_requested", (PyCFunction) _wrap_Credentials_authentication_requested, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_wrong_password", (PyCFunction) _wrap_Credentials_wrong_password, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.wrong_password() -> bool\n" + "Indicate the returned password was incorrect.\n" + ""}, + { (char *)"Credentials_set_cmdline_callbacks", (PyCFunction) _wrap_Credentials_set_cmdline_callbacks, METH_VARARGS | METH_KEYWORDS, (char *)"\n" + "S.set_cmdline_callbacks() -> bool\n" + "Use command-line to obtain credentials not explicitly set.\n" + ""}, + { (char *)"delete_Credentials", (PyCFunction) _wrap_delete_Credentials, METH_VARARGS | METH_KEYWORDS, NULL}, + { (char *)"Credentials_swigregister", Credentials_swigregister, METH_VARARGS, NULL}, + { (char *)"Credentials_swiginit", Credentials_swiginit, METH_VARARGS, NULL}, + { NULL, NULL, 0, NULL } +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ + +static swig_type_info _swigt__p_NTSTATUS = {"_p_NTSTATUS", "NTSTATUS *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_TALLOC_CTX = {"_p_TALLOC_CTX", "TALLOC_CTX *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_cli_credentials = {"_p_cli_credentials", "struct cli_credentials *|cli_credentials *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_int = {"_p_int", "intptr_t *|int *|int_least32_t *|int_fast32_t *|int32_t *|int_fast16_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_loadparm_context = {"_p_loadparm_context", "struct loadparm_context *|loadparm_context *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_loadparm_service = {"_p_loadparm_service", "struct loadparm_service *|loadparm_service *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_long_long = {"_p_long_long", "int_least64_t *|int_fast64_t *|int64_t *|long long *|intmax_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_param_context = {"_p_param_context", "struct param_context *|param *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_param_opt = {"_p_param_opt", "struct param_opt *|param_opt *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_param_section = {"_p_param_section", "struct param_section *|param_section *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_short = {"_p_short", "short *|int_least16_t *|int16_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_signed_char = {"_p_signed_char", "signed char *|int_least8_t *|int_fast8_t *|int8_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_char = {"_p_unsigned_char", "unsigned char *|uint_least8_t *|uint_fast8_t *|uint8_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "uintptr_t *|uint_least32_t *|uint_fast32_t *|uint32_t *|unsigned int *|uint_fast16_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_long_long = {"_p_unsigned_long_long", "uint_least64_t *|uint_fast64_t *|uint64_t *|unsigned long long *|uintmax_t *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_unsigned_short = {"_p_unsigned_short", "unsigned short *|uint_least16_t *|uint16_t *", 0, 0, (void*)0, 0}; + +static swig_type_info *swig_type_initial[] = { + &_swigt__p_NTSTATUS, + &_swigt__p_TALLOC_CTX, + &_swigt__p_char, + &_swigt__p_cli_credentials, + &_swigt__p_int, + &_swigt__p_loadparm_context, + &_swigt__p_loadparm_service, + &_swigt__p_long_long, + &_swigt__p_param_context, + &_swigt__p_param_opt, + &_swigt__p_param_section, + &_swigt__p_short, + &_swigt__p_signed_char, + &_swigt__p_unsigned_char, + &_swigt__p_unsigned_int, + &_swigt__p_unsigned_long_long, + &_swigt__p_unsigned_short, +}; + +static swig_cast_info _swigc__p_NTSTATUS[] = { {&_swigt__p_NTSTATUS, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_TALLOC_CTX[] = { {&_swigt__p_TALLOC_CTX, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_cli_credentials[] = { {&_swigt__p_cli_credentials, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_loadparm_context[] = { {&_swigt__p_loadparm_context, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_loadparm_service[] = { {&_swigt__p_loadparm_service, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_long_long[] = { {&_swigt__p_long_long, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_param_context[] = { {&_swigt__p_param_context, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_param_opt[] = { {&_swigt__p_param_opt, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_param_section[] = { {&_swigt__p_param_section, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_short[] = { {&_swigt__p_short, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_signed_char[] = { {&_swigt__p_signed_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_char[] = { {&_swigt__p_unsigned_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_long_long[] = { {&_swigt__p_unsigned_long_long, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_unsigned_short[] = { {&_swigt__p_unsigned_short, 0, 0, 0},{0, 0, 0, 0}}; + +static swig_cast_info *swig_cast_initial[] = { + _swigc__p_NTSTATUS, + _swigc__p_TALLOC_CTX, + _swigc__p_char, + _swigc__p_cli_credentials, + _swigc__p_int, + _swigc__p_loadparm_context, + _swigc__p_loadparm_service, + _swigc__p_long_long, + _swigc__p_param_context, + _swigc__p_param_opt, + _swigc__p_param_section, + _swigc__p_short, + _swigc__p_signed_char, + _swigc__p_unsigned_char, + _swigc__p_unsigned_int, + _swigc__p_unsigned_long_long, + _swigc__p_unsigned_short, +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ + +static swig_const_info swig_const_table[] = { +{0, 0, 0, 0.0, 0, 0}}; + +#ifdef __cplusplus +} +#endif +/* ----------------------------------------------------------------------------- + * Type initialization: + * This problem is tough by the requirement that no dynamic + * memory is used. Also, since swig_type_info structures store pointers to + * swig_cast_info structures and swig_cast_info structures store pointers back + * to swig_type_info structures, we need some lookup code at initialization. + * The idea is that swig generates all the structures that are needed. + * The runtime then collects these partially filled structures. + * The SWIG_InitializeModule function takes these initial arrays out of + * swig_module, and does all the lookup, filling in the swig_module.types + * array with the correct data and linking the correct swig_cast_info + * structures together. + * + * The generated swig_type_info structures are assigned staticly to an initial + * array. We just loop through that array, and handle each type individually. + * First we lookup if this type has been already loaded, and if so, use the + * loaded structure instead of the generated one. Then we have to fill in the + * cast linked list. The cast data is initially stored in something like a + * two-dimensional array. Each row corresponds to a type (there are the same + * number of rows as there are in the swig_type_initial array). Each entry in + * a column is one of the swig_cast_info structures for that type. + * The cast_initial array is actually an array of arrays, because each row has + * a variable number of columns. So to actually build the cast linked list, + * we find the array of casts associated with the type, and loop through it + * adding the casts to the list. The one last trick we need to do is making + * sure the type pointer in the swig_cast_info struct is correct. + * + * First off, we lookup the cast->type name to see if it is already loaded. + * There are three cases to handle: + * 1) If the cast->type has already been loaded AND the type we are adding + * casting info to has not been loaded (it is in this module), THEN we + * replace the cast->type pointer with the type pointer that has already + * been loaded. + * 2) If BOTH types (the one we are adding casting info to, and the + * cast->type) are loaded, THEN the cast info has already been loaded by + * the previous module so we just ignore it. + * 3) Finally, if cast->type has not already been loaded, then we add that + * swig_cast_info to the linked list (because the cast->type) pointer will + * be correct. + * ----------------------------------------------------------------------------- */ + +#ifdef __cplusplus +extern "C" { +#if 0 +} /* c-mode */ +#endif +#endif + +#if 0 +#define SWIGRUNTIME_DEBUG +#endif + + +SWIGRUNTIME void +SWIG_InitializeModule(void *clientdata) { + size_t i; + swig_module_info *module_head, *iter; + int found, init; + + clientdata = clientdata; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next==0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; + } else { + init = 0; + } + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + module_head = &swig_module; + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + found=0; + iter=module_head; + do { + if (iter==&swig_module) { + found=1; + break; + } + iter=iter->next; + } while (iter!= module_head); + + /* if the is found in the list, then all is done and we may leave */ + if (found) return; + /* otherwise we must add out module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpeters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: size %d\n", swig_module.size); +#endif + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } + } else { + type = swig_module.type_initial[i]; + } + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; + } + swig_module.types[i] = 0; + +#ifdef SWIGRUNTIME_DEBUG + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n",j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); +#endif +} + +/* This function will propagate the clientdata field of type to +* any new swig_type_info structures that have been added into the list +* of equivalent types. It is like calling +* SWIG_TypeClientData(type, clientdata) a second time. +*/ +SWIGRUNTIME void +SWIG_PropagateClientData(void) { + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } + } + } +} + +#ifdef __cplusplus +#if 0 +{ + /* c-mode */ +#endif +} +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + + /* Python-specific SWIG API */ +#define SWIG_newvarlink() SWIG_Python_newvarlink() +#define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) +#define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) + + /* ----------------------------------------------------------------------------- + * global variable support code. + * ----------------------------------------------------------------------------- */ + + typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; + } swig_globalvar; + + typedef struct swig_varlinkobject { + PyObject_HEAD + swig_globalvar *vars; + } swig_varlinkobject; + + SWIGINTERN PyObject * + swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { + return PyString_FromString("<Swig global variables>"); + } + + SWIGINTERN PyObject * + swig_varlink_str(swig_varlinkobject *v) { + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + PyString_ConcatAndDel(&str,PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str,PyString_FromString(")")); + return str; + } + + SWIGINTERN int + swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { + PyObject *str = swig_varlink_str(v); + fprintf(fp,"Swig global variables "); + fprintf(fp,"%s\n", PyString_AsString(str)); + Py_DECREF(str); + return 0; + } + + SWIGINTERN void + swig_varlink_dealloc(swig_varlinkobject *v) { + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } + } + + SWIGINTERN PyObject * + swig_varlink_getattr(swig_varlinkobject *v, char *n) { + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->get_attr)(); + break; + } + var = var->next; + } + if (res == NULL && !PyErr_Occurred()) { + PyErr_SetString(PyExc_NameError,"Unknown C global variable"); + } + return res; + } + + SWIGINTERN int + swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->set_attr)(p); + break; + } + var = var->next; + } + if (res == 1 && !PyErr_Occurred()) { + PyErr_SetString(PyExc_NameError,"Unknown C global variable"); + } + return res; + } + + SWIGINTERN PyTypeObject* + swig_varlink_type(void) { + static char varlink__doc__[] = "Swig var link object"; + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp + = { + PyObject_HEAD_INIT(NULL) + 0, /* Number of items in variable part (ob_size) */ + (char *)"swigvarlink", /* Type name (tp_name) */ + sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ + 0, /* Itemsize (tp_itemsize) */ + (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ + (printfunc) swig_varlink_print, /* Print (tp_print) */ + (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ + (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ +#if PY_VERSION_HEX >= 0x02020000 + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ +#endif +#if PY_VERSION_HEX >= 0x02030000 + 0, /* tp_del */ +#endif +#ifdef COUNT_ALLOCS + 0,0,0,0 /* tp_alloc -> tp_next */ +#endif + }; + varlink_type = tmp; + varlink_type.ob_type = &PyType_Type; + type_init = 1; + } + return &varlink_type; + } + + /* Create a variable linking object for use later */ + SWIGINTERN PyObject * + SWIG_Python_newvarlink(void) { + swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject*) result); + } + + SWIGINTERN void + SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name)+1; + gv->name = (char *)malloc(size); + if (gv->name) { + strncpy(gv->name,name,size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; + } + } + v->vars = gv; + } + + SWIGINTERN PyObject * + SWIG_globals(void) { + static PyObject *_SWIG_globals = 0; + if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); + return _SWIG_globals; + } + + /* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + + /* Install Constants */ + SWIGINTERN void + SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + PyObject *obj = 0; + size_t i; + for (i = 0; constants[i].type; ++i) { + switch(constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + Py_DECREF(obj); + } + } + } + + /* -----------------------------------------------------------------------------*/ + /* Fix SwigMethods to carry the callback ptrs when needed */ + /* -----------------------------------------------------------------------------*/ + + SWIGINTERN void + SWIG_Python_FixMethods(PyMethodDef *methods, + swig_const_info *const_table, + swig_type_info **types, + swig_type_info **types_initial) { + size_t i; + for (i = 0; methods[i].ml_name; ++i) { + const char *c = methods[i].ml_doc; + if (c && (c = strstr(c, "swig_ptr: "))) { + int j; + swig_const_info *ci = 0; + const char *name = c + 10; + for (j = 0; const_table[j].type; ++j) { + if (strncmp(const_table[j].name, name, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } + } + if (ci) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; + char *ndoc = (char*)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + strncpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + strncpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } + } + } + } + } + +#ifdef __cplusplus +} +#endif + +/* -----------------------------------------------------------------------------* + * Partial Init method + * -----------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" +#endif +SWIGEXPORT void SWIG_init(void) { + PyObject *m, *d; + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + + m = Py_InitModule((char *) SWIG_name, SwigMethods); + d = PyModule_GetDict(m); + + SWIG_InitializeModule(0); + SWIG_InstallConstants(d,swig_const_table); + + + SWIG_Python_SetConstant(d, "AUTO_USE_KERBEROS",SWIG_From_int((int)(CRED_AUTO_USE_KERBEROS))); + SWIG_Python_SetConstant(d, "DONT_USE_KERBEROS",SWIG_From_int((int)(CRED_DONT_USE_KERBEROS))); + SWIG_Python_SetConstant(d, "MUST_USE_KERBEROS",SWIG_From_int((int)(CRED_MUST_USE_KERBEROS))); +} + diff --git a/source4/auth/credentials/tests/bindings.py b/source4/auth/credentials/tests/bindings.py new file mode 100644 index 0000000000..30120b3a60 --- /dev/null +++ b/source4/auth/credentials/tests/bindings.py @@ -0,0 +1,98 @@ +#!/usr/bin/python + +# Unix SMB/CIFS implementation. +# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +"""Tests for the Credentials Python bindings. + +Note that this just tests the bindings work. It does not intend to test +the functionality, that's already done in other tests. +""" + +import unittest +from samba import credentials + +class CredentialsTests(unittest.TestCase): + def setUp(self): + self.creds = credentials.Credentials() + + def test_set_username(self): + self.creds.set_username("somebody") + self.assertEquals("somebody", self.creds.get_username()) + + def test_set_password(self): + self.creds.set_password("S3CreT") + self.assertEquals("S3CreT", self.creds.get_password()) + + def test_set_domain(self): + self.creds.set_domain("ABMAS") + self.assertEquals("ABMAS", self.creds.get_domain()) + + def test_set_realm(self): + self.creds.set_realm("myrealm") + self.assertEquals("MYREALM", self.creds.get_realm()) + + def test_parse_string_anon(self): + self.creds.parse_string("%") + self.assertEquals("", self.creds.get_username()) + self.assertEquals(None, self.creds.get_password()) + + def test_parse_string_user_pw_domain(self): + self.creds.parse_string("dom\\someone%secr") + self.assertEquals("someone", self.creds.get_username()) + self.assertEquals("secr", self.creds.get_password()) + self.assertEquals("DOM", self.creds.get_domain()) + + def test_bind_dn(self): + self.assertEquals(None, self.creds.get_bind_dn()) + self.creds.set_bind_dn("dc=foo,cn=bar") + self.assertEquals("dc=foo,cn=bar", self.creds.get_bind_dn()) + + def test_is_anon(self): + self.creds.set_username("") + self.assertTrue(self.creds.is_anonymous()) + self.creds.set_username("somebody") + self.assertFalse(self.creds.is_anonymous()) + self.creds.set_anonymous() + self.assertTrue(self.creds.is_anonymous()) + + def test_workstation(self): + # FIXME: This is uninitialised, it should be None + #self.assertEquals(None, self.creds.get_workstation()) + self.creds.set_workstation("myworksta") + self.assertEquals("myworksta", self.creds.get_workstation()) + + def test_get_nt_hash(self): + self.creds.set_password("geheim") + self.assertEquals('\xc2\xae\x1f\xe6\xe6H\x84cRE>\x81o*\xeb\x93', + self.creds.get_nt_hash()) + + def test_guess(self): + # Just check the method is there and doesn't raise an exception + self.creds.guess() + + def test_set_cmdline_callbacks(self): + self.creds.set_cmdline_callbacks() + + def test_authentication_requested(self): + self.creds.set_username("") + self.assertFalse(self.creds.authentication_requested()) + self.creds.set_username("somebody") + self.assertTrue(self.creds.authentication_requested()) + + def test_wrong_password(self): + self.assertFalse(self.creds.wrong_password()) diff --git a/source4/auth/credentials/tests/simple.c b/source4/auth/credentials/tests/simple.c new file mode 100644 index 0000000000..c059878318 --- /dev/null +++ b/source4/auth/credentials/tests/simple.c @@ -0,0 +1,120 @@ +/* + Unix SMB/CIFS implementation. + Samba utility functions + Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/credentials/credentials.h" +#include "torture/torture.h" + +static bool test_init(struct torture_context *tctx) +{ + struct cli_credentials *creds = cli_credentials_init(tctx); + + cli_credentials_set_domain(creds, "bla", CRED_SPECIFIED); + + torture_assert_str_equal(tctx, "BLA", cli_credentials_get_domain(creds), + "domain"); + + cli_credentials_set_username(creds, "someuser", CRED_SPECIFIED); + + torture_assert_str_equal(tctx, "someuser", + cli_credentials_get_username(creds), + "username"); + + cli_credentials_set_password(creds, "p4ssw0rd", CRED_SPECIFIED); + + torture_assert_str_equal(tctx, "p4ssw0rd", + cli_credentials_get_password(creds), + "password"); + + return true; +} + +static bool test_init_anonymous(struct torture_context *tctx) +{ + struct cli_credentials *creds = cli_credentials_init_anon(tctx); + + torture_assert_str_equal(tctx, cli_credentials_get_domain(creds), + "", "domain"); + + torture_assert_str_equal(tctx, cli_credentials_get_username(creds), + "", "username"); + + torture_assert(tctx, cli_credentials_get_password(creds) == NULL, + "password"); + + return true; +} + +static bool test_parse_string(struct torture_context *tctx) +{ + struct cli_credentials *creds = cli_credentials_init_anon(tctx); + + /* anonymous */ + cli_credentials_parse_string(creds, "%", CRED_SPECIFIED); + + torture_assert_str_equal(tctx, cli_credentials_get_domain(creds), + "", "domain"); + + torture_assert_str_equal(tctx, cli_credentials_get_username(creds), + "", "username"); + + torture_assert(tctx, cli_credentials_get_password(creds) == NULL, + "password"); + + /* username + password */ + cli_credentials_parse_string(creds, "somebody%secret", + CRED_SPECIFIED); + + torture_assert_str_equal(tctx, cli_credentials_get_domain(creds), + "", "domain"); + + torture_assert_str_equal(tctx, cli_credentials_get_username(creds), + "somebody", "username"); + + torture_assert_str_equal(tctx, cli_credentials_get_password(creds), + "secret", "password"); + + /* principal */ + cli_credentials_parse_string(creds, "prin@styx", + CRED_SPECIFIED); + + torture_assert_str_equal(tctx, cli_credentials_get_realm(creds), + "STYX", "realm"); + + torture_assert_str_equal(tctx, + cli_credentials_get_principal(creds, tctx), + "prin@styx", "principal"); + + return true; +} + +struct torture_suite *torture_local_credentials(TALLOC_CTX *mem_ctx) +{ + struct torture_suite *suite = torture_suite_create(mem_ctx, + "CREDENTIALS"); + + torture_suite_add_simple_test(suite, "init", test_init); + torture_suite_add_simple_test(suite, "init anonymous", + test_init_anonymous); + torture_suite_add_simple_test(suite, "parse_string", + test_parse_string); + + return suite; +} + diff --git a/source4/auth/gensec/config.m4 b/source4/auth/gensec/config.m4 new file mode 100644 index 0000000000..b945afeea0 --- /dev/null +++ b/source4/auth/gensec/config.m4 @@ -0,0 +1,2 @@ +SMB_ENABLE(gensec_krb5, $HAVE_KRB5) +SMB_ENABLE(gensec_gssapi, $HAVE_KRB5) diff --git a/source4/auth/gensec/config.mk b/source4/auth/gensec/config.mk new file mode 100644 index 0000000000..f08ff2638a --- /dev/null +++ b/source4/auth/gensec/config.mk @@ -0,0 +1,87 @@ +################################# +# Start SUBSYSTEM gensec +[LIBRARY::gensec] +PUBLIC_DEPENDENCIES = \ + CREDENTIALS LIBSAMBA-UTIL LIBCRYPTO ASN1_UTIL samba-socket LIBPACKET +# End SUBSYSTEM gensec +################################# + +PC_FILES += $(gensecsrcdir)/gensec.pc + +gensec_VERSION = 0.0.1 +gensec_SOVERSION = 0 +gensec_OBJ_FILES = $(addprefix $(gensecsrcdir)/, gensec.o socket.o) + +PUBLIC_HEADERS += $(gensecsrcdir)/gensec.h + +$(eval $(call proto_header_template,$(gensecsrcdir)/gensec_proto.h,$(gensec_OBJ_FILES:.o=.c))) + +################################################ +# Start MODULE gensec_krb5 +[MODULE::gensec_krb5] +SUBSYSTEM = gensec +INIT_FUNCTION = gensec_krb5_init +PRIVATE_DEPENDENCIES = CREDENTIALS KERBEROS auth_session auth_sam +# End MODULE gensec_krb5 +################################################ + +gensec_krb5_OBJ_FILES = $(addprefix $(gensecsrcdir)/, gensec_krb5.o) + +################################################ +# Start MODULE gensec_gssapi +[MODULE::gensec_gssapi] +SUBSYSTEM = gensec +INIT_FUNCTION = gensec_gssapi_init +PRIVATE_DEPENDENCIES = HEIMDAL_GSSAPI CREDENTIALS KERBEROS +# End MODULE gensec_gssapi +################################################ + +gensec_gssapi_OBJ_FILES = $(addprefix $(gensecsrcdir)/, gensec_gssapi.o) + +################################################ +# Start MODULE cyrus_sasl +[MODULE::cyrus_sasl] +SUBSYSTEM = gensec +INIT_FUNCTION = gensec_sasl_init +PRIVATE_DEPENDENCIES = CREDENTIALS SASL +# End MODULE cyrus_sasl +################################################ + +cyrus_sasl_OBJ_FILES = $(addprefix $(gensecsrcdir)/, cyrus_sasl.o) + +################################################ +# Start MODULE gensec_spnego +[MODULE::gensec_spnego] +SUBSYSTEM = gensec +INIT_FUNCTION = gensec_spnego_init +PRIVATE_DEPENDENCIES = ASN1_UTIL CREDENTIALS +# End MODULE gensec_spnego +################################################ + +gensec_spnego_OBJ_FILES = $(addprefix $(gensecsrcdir)/, spnego.o spnego_parse.o) + +$(eval $(call proto_header_template,$(gensecsrcdir)/spnego_proto.h,$(gensec_spnego_OBJ_FILES:.o=.c))) + +################################################ +# Start MODULE gensec_schannel +[MODULE::gensec_schannel] +SUBSYSTEM = gensec +INIT_FUNCTION = gensec_schannel_init +PRIVATE_DEPENDENCIES = SCHANNELDB NDR_SCHANNEL CREDENTIALS LIBNDR +OUTPUT_TYPE = MERGED_OBJ +# End MODULE gensec_schannel +################################################ + +gensec_schannel_OBJ_FILES = $(addprefix $(gensecsrcdir)/, schannel.o schannel_sign.o) +$(eval $(call proto_header_template,$(gensecsrcdir)/schannel_proto.h,$(gensec_schannel_OBJ_FILES:.o=.c))) + +################################################ +# Start SUBSYSTEM SCHANNELDB +[SUBSYSTEM::SCHANNELDB] +PRIVATE_DEPENDENCIES = LDB_WRAP SAMDB +# End SUBSYSTEM SCHANNELDB +################################################ + +SCHANNELDB_OBJ_FILES = $(addprefix $(gensecsrcdir)/, schannel_state.o) +$(eval $(call proto_header_template,$(gensecsrcdir)/schannel_state.h,$(SCHANNELDB_OBJ_FILES:.o=.c))) + diff --git a/source4/auth/gensec/cyrus_sasl.c b/source4/auth/gensec/cyrus_sasl.c new file mode 100644 index 0000000000..06a7b8a382 --- /dev/null +++ b/source4/auth/gensec/cyrus_sasl.c @@ -0,0 +1,432 @@ +/* + Unix SMB/CIFS implementation. + + Connect GENSEC to an external SASL lib + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" +#include "lib/socket/socket.h" +#include <sasl/sasl.h> + +struct gensec_sasl_state { + sasl_conn_t *conn; + int step; +}; + +static NTSTATUS sasl_nt_status(int sasl_ret) +{ + switch (sasl_ret) { + case SASL_CONTINUE: + return NT_STATUS_MORE_PROCESSING_REQUIRED; + case SASL_NOMEM: + return NT_STATUS_NO_MEMORY; + case SASL_BADPARAM: + case SASL_NOMECH: + return NT_STATUS_INVALID_PARAMETER; + case SASL_BADMAC: + return NT_STATUS_ACCESS_DENIED; + case SASL_OK: + return NT_STATUS_OK; + default: + return NT_STATUS_UNSUCCESSFUL; + } +} + +static int gensec_sasl_get_user(void *context, int id, + const char **result, unsigned *len) +{ + struct gensec_security *gensec_security = talloc_get_type(context, struct gensec_security); + const char *username = cli_credentials_get_username(gensec_get_credentials(gensec_security)); + if (id != SASL_CB_USER && id != SASL_CB_AUTHNAME) { + return SASL_FAIL; + } + + *result = username; + return SASL_OK; +} + +static int gensec_sasl_get_realm(void *context, int id, + const char **availrealms, + const char **result) +{ + struct gensec_security *gensec_security = talloc_get_type(context, struct gensec_security); + const char *realm = cli_credentials_get_realm(gensec_get_credentials(gensec_security)); + int i; + if (id != SASL_CB_GETREALM) { + return SASL_FAIL; + } + + for (i=0; availrealms && availrealms[i]; i++) { + if (strcasecmp_m(realm, availrealms[i]) == 0) { + result[i] = availrealms[i]; + return SASL_OK; + } + } + /* None of the realms match, so lets not specify one */ + *result = ""; + return SASL_OK; +} + +static int gensec_sasl_get_password(sasl_conn_t *conn, void *context, int id, + sasl_secret_t **psecret) +{ + struct gensec_security *gensec_security = talloc_get_type(context, struct gensec_security); + const char *password = cli_credentials_get_password(gensec_get_credentials(gensec_security)); + + sasl_secret_t *secret; + if (!password) { + *psecret = NULL; + return SASL_OK; + } + secret = talloc_size(gensec_security, sizeof(sasl_secret_t)+strlen(password)); + if (!secret) { + return SASL_NOMEM; + } + secret->len = strlen(password); + safe_strcpy((char*)secret->data, password, secret->len+1); + *psecret = secret; + return SASL_OK; +} + +static int gensec_sasl_dispose(struct gensec_sasl_state *gensec_sasl_state) +{ + sasl_dispose(&gensec_sasl_state->conn); + return 0; +} + +static NTSTATUS gensec_sasl_client_start(struct gensec_security *gensec_security) +{ + struct gensec_sasl_state *gensec_sasl_state; + const char *service = gensec_get_target_service(gensec_security); + const char *target_name = gensec_get_target_hostname(gensec_security); + struct socket_address *local_socket_addr = gensec_get_my_addr(gensec_security); + struct socket_address *remote_socket_addr = gensec_get_peer_addr(gensec_security); + char *local_addr = NULL; + char *remote_addr = NULL; + int sasl_ret; + + sasl_callback_t *callbacks; + + gensec_sasl_state = talloc(gensec_security, struct gensec_sasl_state); + if (!gensec_sasl_state) { + return NT_STATUS_NO_MEMORY; + } + + callbacks = talloc_array(gensec_sasl_state, sasl_callback_t, 5); + callbacks[0].id = SASL_CB_USER; + callbacks[0].proc = gensec_sasl_get_user; + callbacks[0].context = gensec_security; + + callbacks[1].id = SASL_CB_AUTHNAME; + callbacks[1].proc = gensec_sasl_get_user; + callbacks[1].context = gensec_security; + + callbacks[2].id = SASL_CB_GETREALM; + callbacks[2].proc = gensec_sasl_get_realm; + callbacks[2].context = gensec_security; + + callbacks[3].id = SASL_CB_PASS; + callbacks[3].proc = gensec_sasl_get_password; + callbacks[3].context = gensec_security; + + callbacks[4].id = SASL_CB_LIST_END; + callbacks[4].proc = NULL; + callbacks[4].context = NULL; + + gensec_security->private_data = gensec_sasl_state; + + if (local_socket_addr) { + local_addr = talloc_asprintf(gensec_sasl_state, + "%s;%d", + local_socket_addr->addr, + local_socket_addr->port); + } + + if (remote_socket_addr) { + remote_addr = talloc_asprintf(gensec_sasl_state, + "%s;%d", + remote_socket_addr->addr, + remote_socket_addr->port); + } + gensec_sasl_state->step = 0; + + sasl_ret = sasl_client_new(service, + target_name, + local_addr, remote_addr, callbacks, 0, + &gensec_sasl_state->conn); + + if (sasl_ret == SASL_OK || sasl_ret == SASL_CONTINUE) { + sasl_security_properties_t props; + talloc_set_destructor(gensec_sasl_state, gensec_sasl_dispose); + + ZERO_STRUCT(props); + if (gensec_security->want_features & GENSEC_FEATURE_SIGN) { + props.min_ssf = 1; + } + if (gensec_security->want_features & GENSEC_FEATURE_SEAL) { + props.min_ssf = 40; + } + + props.max_ssf = UINT_MAX; + props.maxbufsize = 65536; + sasl_ret = sasl_setprop(gensec_sasl_state->conn, SASL_SEC_PROPS, &props); + if (sasl_ret != SASL_OK) { + return sasl_nt_status(sasl_ret); + } + + } else { + DEBUG(1, ("GENSEC SASL: client_new failed: %s\n", sasl_errdetail(gensec_sasl_state->conn))); + } + return sasl_nt_status(sasl_ret); +} + +static NTSTATUS gensec_sasl_update(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct gensec_sasl_state *gensec_sasl_state = talloc_get_type(gensec_security->private_data, + struct gensec_sasl_state); + int sasl_ret; + const char *out_data; + unsigned int out_len; + + if (gensec_sasl_state->step == 0) { + const char *mech; + sasl_ret = sasl_client_start(gensec_sasl_state->conn, gensec_security->ops->sasl_name, + NULL, &out_data, &out_len, &mech); + } else { + sasl_ret = sasl_client_step(gensec_sasl_state->conn, + (char*)in.data, in.length, NULL, + &out_data, &out_len); + } + if (sasl_ret == SASL_OK || sasl_ret == SASL_CONTINUE) { + *out = data_blob_talloc(out_mem_ctx, out_data, out_len); + } else { + DEBUG(1, ("GENSEC SASL: step %d update failed: %s\n", gensec_sasl_state->step, + sasl_errdetail(gensec_sasl_state->conn))); + } + gensec_sasl_state->step++; + return sasl_nt_status(sasl_ret); +} + +static NTSTATUS gensec_sasl_unwrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed) +{ + struct gensec_sasl_state *gensec_sasl_state = talloc_get_type(gensec_security->private_data, + struct gensec_sasl_state); + const char *out_data; + unsigned int out_len; + + int sasl_ret = sasl_decode(gensec_sasl_state->conn, + (char*)in->data, in->length, &out_data, + &out_len); + if (sasl_ret == SASL_OK) { + *out = data_blob_talloc(out_mem_ctx, out_data, out_len); + *len_processed = in->length; + } else { + DEBUG(1, ("GENSEC SASL: unwrap failed: %s\n", sasl_errdetail(gensec_sasl_state->conn))); + } + return sasl_nt_status(sasl_ret); + +} + +static NTSTATUS gensec_sasl_wrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed) +{ + struct gensec_sasl_state *gensec_sasl_state = talloc_get_type(gensec_security->private_data, + struct gensec_sasl_state); + const char *out_data; + unsigned int out_len; + + int sasl_ret = sasl_encode(gensec_sasl_state->conn, + (char*)in->data, in->length, &out_data, + &out_len); + if (sasl_ret == SASL_OK) { + *out = data_blob_talloc(out_mem_ctx, out_data, out_len); + *len_processed = in->length; + } else { + DEBUG(1, ("GENSEC SASL: wrap failed: %s\n", sasl_errdetail(gensec_sasl_state->conn))); + } + return sasl_nt_status(sasl_ret); +} + +/* Try to figure out what features we actually got on the connection */ +static bool gensec_sasl_have_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + struct gensec_sasl_state *gensec_sasl_state = talloc_get_type(gensec_security->private_data, + struct gensec_sasl_state); + sasl_ssf_t ssf; + int sasl_ret = sasl_getprop(gensec_sasl_state->conn, SASL_SSF, + (const void**)&ssf); + if (sasl_ret != SASL_OK) { + return false; + } + if (feature & GENSEC_FEATURE_SIGN) { + if (ssf == 0) { + return false; + } + if (ssf >= 1) { + return true; + } + } + if (feature & GENSEC_FEATURE_SEAL) { + if (ssf <= 1) { + return false; + } + if (ssf > 1) { + return true; + } + } + return false; +} + +/* This could in theory work with any SASL mech */ +static const struct gensec_security_ops gensec_sasl_security_ops = { + .name = "sasl-DIGEST-MD5", + .sasl_name = "DIGEST-MD5", + .client_start = gensec_sasl_client_start, + .update = gensec_sasl_update, + .wrap_packets = gensec_sasl_wrap_packets, + .unwrap_packets = gensec_sasl_unwrap_packets, + .have_feature = gensec_sasl_have_feature, + .enabled = true, + .priority = GENSEC_SASL +}; + +int gensec_sasl_log(void *context, + int sasl_log_level, + const char *message) +{ + int debug_level; + switch (sasl_log_level) { + case SASL_LOG_NONE: + debug_level = 0; + break; + case SASL_LOG_ERR: + debug_level = 1; + break; + case SASL_LOG_FAIL: + debug_level = 2; + break; + case SASL_LOG_WARN: + debug_level = 3; + break; + case SASL_LOG_NOTE: + debug_level = 5; + break; + case SASL_LOG_DEBUG: + debug_level = 10; + break; + case SASL_LOG_TRACE: + debug_level = 11; + break; +#if DEBUG_PASSWORD + case SASL_LOG_PASS: + debug_level = 100; + break; +#endif + default: + debug_level = 0; + break; + } + DEBUG(debug_level, ("gensec_sasl: %s\n", message)); + + return SASL_OK; +} + +NTSTATUS gensec_sasl_init(void) +{ + NTSTATUS ret; + int sasl_ret; +#if 0 + int i; + const char **sasl_mechs; +#endif + + static const sasl_callback_t callbacks[] = { + { + .id = SASL_CB_LOG, + .proc = gensec_sasl_log, + .context = NULL, + }, + { + .id = SASL_CB_LIST_END, + .proc = gensec_sasl_log, + .context = NULL, + } + }; + sasl_ret = sasl_client_init(callbacks); + + if (sasl_ret == SASL_NOMECH) { + /* Nothing to do here */ + return NT_STATUS_OK; + } + + if (sasl_ret != SASL_OK) { + return sasl_nt_status(sasl_ret); + } + + /* For now, we just register DIGEST-MD5 */ +#if 1 + ret = gensec_register(&gensec_sasl_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_sasl_security_ops.name)); + return ret; + } +#else + sasl_mechs = sasl_global_listmech(); + for (i = 0; sasl_mechs && sasl_mechs[i]; i++) { + const struct gensec_security_ops *oldmech; + struct gensec_security_ops *newmech; + oldmech = gensec_security_by_sasl_name(NULL, sasl_mechs[i]); + if (oldmech) { + continue; + } + newmech = talloc(talloc_autofree_context(), struct gensec_security_ops); + if (!newmech) { + return NT_STATUS_NO_MEMORY; + } + *newmech = gensec_sasl_security_ops; + newmech->sasl_name = talloc_strdup(newmech, sasl_mechs[i]); + newmech->name = talloc_asprintf(newmech, "sasl-%s", sasl_mechs[i]); + if (!newmech->sasl_name || !newmech->name) { + return NT_STATUS_NO_MEMORY; + } + + ret = gensec_register(newmech); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_sasl_security_ops.name)); + return ret; + } + } +#endif + return NT_STATUS_OK; +} diff --git a/source4/auth/gensec/gensec.c b/source4/auth/gensec/gensec.c new file mode 100644 index 0000000000..0edb34d740 --- /dev/null +++ b/source4/auth/gensec/gensec.c @@ -0,0 +1,1281 @@ +/* + Unix SMB/CIFS implementation. + + Generic Authentication Interface + + Copyright (C) Andrew Tridgell 2003 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2006 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "lib/events/events.h" +#include "librpc/rpc/dcerpc.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" +#include "param/param.h" + +/* the list of currently registered GENSEC backends */ +static struct gensec_security_ops **generic_security_ops; +static int gensec_num_backends; + +/* Return all the registered mechs. Don't modify the return pointer, + * but you may talloc_reference it if convient */ +_PUBLIC_ struct gensec_security_ops **gensec_security_all(void) +{ + return generic_security_ops; +} + +/* Sometimes we want to force only kerberos, sometimes we want to + * force it's avoidance. The old list could be either + * gensec_security_all(), or from cli_credentials_gensec_list() (ie, + * an existing list we have trimmed down) */ + +_PUBLIC_ struct gensec_security_ops **gensec_use_kerberos_mechs(TALLOC_CTX *mem_ctx, + struct gensec_security_ops **old_gensec_list, + struct cli_credentials *creds) +{ + struct gensec_security_ops **new_gensec_list; + int i, j, num_mechs_in; + enum credentials_use_kerberos use_kerberos = CRED_AUTO_USE_KERBEROS; + + if (creds) { + use_kerberos = cli_credentials_get_kerberos_state(creds); + } + + if (use_kerberos == CRED_AUTO_USE_KERBEROS) { + if (!talloc_reference(mem_ctx, old_gensec_list)) { + return NULL; + } + return old_gensec_list; + } + + for (num_mechs_in=0; old_gensec_list && old_gensec_list[num_mechs_in]; num_mechs_in++) { + /* noop */ + } + + new_gensec_list = talloc_array(mem_ctx, struct gensec_security_ops *, num_mechs_in + 1); + if (!new_gensec_list) { + return NULL; + } + + j = 0; + for (i=0; old_gensec_list && old_gensec_list[i]; i++) { + int oid_idx; + for (oid_idx = 0; old_gensec_list[i]->oid && old_gensec_list[i]->oid[oid_idx]; oid_idx++) { + if (strcmp(old_gensec_list[i]->oid[oid_idx], GENSEC_OID_SPNEGO) == 0) { + new_gensec_list[j] = old_gensec_list[i]; + j++; + break; + } + } + switch (use_kerberos) { + case CRED_DONT_USE_KERBEROS: + if (old_gensec_list[i]->kerberos == false) { + new_gensec_list[j] = old_gensec_list[i]; + j++; + } + break; + case CRED_MUST_USE_KERBEROS: + if (old_gensec_list[i]->kerberos == true) { + new_gensec_list[j] = old_gensec_list[i]; + j++; + } + break; + default: + /* Can't happen or invalid parameter */ + return NULL; + } + } + new_gensec_list[j] = NULL; + + return new_gensec_list; +} + +struct gensec_security_ops **gensec_security_mechs(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx) +{ + struct gensec_security_ops **backends; + backends = gensec_security_all(); + if (!gensec_security) { + if (!talloc_reference(mem_ctx, backends)) { + return NULL; + } + return backends; + } else { + struct cli_credentials *creds = gensec_get_credentials(gensec_security); + if (!creds) { + if (!talloc_reference(mem_ctx, backends)) { + return NULL; + } + return backends; + } + return gensec_use_kerberos_mechs(mem_ctx, backends, creds); + } +} + +static const struct gensec_security_ops *gensec_security_by_authtype(struct gensec_security *gensec_security, + uint8_t auth_type) +{ + int i; + struct gensec_security_ops **backends; + const struct gensec_security_ops *backend; + TALLOC_CTX *mem_ctx = talloc_new(gensec_security); + if (!mem_ctx) { + return NULL; + } + backends = gensec_security_mechs(gensec_security, mem_ctx); + for (i=0; backends && backends[i]; i++) { + if (backends[i]->auth_type == auth_type) { + backend = backends[i]; + talloc_free(mem_ctx); + return backend; + } + } + talloc_free(mem_ctx); + + return NULL; +} + +const struct gensec_security_ops *gensec_security_by_oid(struct gensec_security *gensec_security, + const char *oid_string) +{ + int i, j; + struct gensec_security_ops **backends; + const struct gensec_security_ops *backend; + TALLOC_CTX *mem_ctx = talloc_new(gensec_security); + if (!mem_ctx) { + return NULL; + } + backends = gensec_security_mechs(gensec_security, mem_ctx); + for (i=0; backends && backends[i]; i++) { + if (backends[i]->oid) { + for (j=0; backends[i]->oid[j]; j++) { + if (backends[i]->oid[j] && + (strcmp(backends[i]->oid[j], oid_string) == 0)) { + backend = backends[i]; + talloc_free(mem_ctx); + return backend; + } + } + } + } + talloc_free(mem_ctx); + + return NULL; +} + +const struct gensec_security_ops *gensec_security_by_sasl_name(struct gensec_security *gensec_security, + const char *sasl_name) +{ + int i; + struct gensec_security_ops **backends; + const struct gensec_security_ops *backend; + TALLOC_CTX *mem_ctx = talloc_new(gensec_security); + if (!mem_ctx) { + return NULL; + } + backends = gensec_security_mechs(gensec_security, mem_ctx); + for (i=0; backends && backends[i]; i++) { + if (backends[i]->sasl_name + && (strcmp(backends[i]->sasl_name, sasl_name) == 0)) { + backend = backends[i]; + talloc_free(mem_ctx); + return backend; + } + } + talloc_free(mem_ctx); + + return NULL; +} + +static const struct gensec_security_ops *gensec_security_by_name(struct gensec_security *gensec_security, + const char *name) +{ + int i; + struct gensec_security_ops **backends; + const struct gensec_security_ops *backend; + TALLOC_CTX *mem_ctx = talloc_new(gensec_security); + if (!mem_ctx) { + return NULL; + } + backends = gensec_security_mechs(gensec_security, mem_ctx); + for (i=0; backends && backends[i]; i++) { + if (backends[i]->name + && (strcmp(backends[i]->name, name) == 0)) { + backend = backends[i]; + talloc_free(mem_ctx); + return backend; + } + } + talloc_free(mem_ctx); + return NULL; +} + +/** + * Return a unique list of security subsystems from those specified in + * the list of SASL names. + * + * Use the list of enabled GENSEC mechanisms from the credentials + * attached to the gensec_security, and return in our preferred order. + */ + +const struct gensec_security_ops **gensec_security_by_sasl_list(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const char **sasl_names) +{ + const struct gensec_security_ops **backends_out; + struct gensec_security_ops **backends; + int i, k, sasl_idx; + int num_backends_out = 0; + + if (!sasl_names) { + return NULL; + } + + backends = gensec_security_mechs(gensec_security, mem_ctx); + + backends_out = talloc_array(mem_ctx, const struct gensec_security_ops *, 1); + if (!backends_out) { + return NULL; + } + backends_out[0] = NULL; + + /* Find backends in our preferred order, by walking our list, + * then looking in the supplied list */ + for (i=0; backends && backends[i]; i++) { + for (sasl_idx = 0; sasl_names[sasl_idx]; sasl_idx++) { + if (!backends[i]->sasl_name || + !(strcmp(backends[i]->sasl_name, + sasl_names[sasl_idx]) == 0)) { + continue; + } + + for (k=0; backends_out[k]; k++) { + if (backends_out[k] == backends[i]) { + break; + } + } + + if (k < num_backends_out) { + /* already in there */ + continue; + } + + backends_out = talloc_realloc(mem_ctx, backends_out, + const struct gensec_security_ops *, + num_backends_out + 2); + if (!backends_out) { + return NULL; + } + + backends_out[num_backends_out] = backends[i]; + num_backends_out++; + backends_out[num_backends_out] = NULL; + } + } + return backends_out; +} + +/** + * Return a unique list of security subsystems from those specified in + * the OID list. That is, where two OIDs refer to the same module, + * return that module only once. + * + * Use the list of enabled GENSEC mechanisms from the credentials + * attached to the gensec_security, and return in our preferred order. + */ + +const struct gensec_security_ops_wrapper *gensec_security_by_oid_list(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const char **oid_strings, + const char *skip) +{ + struct gensec_security_ops_wrapper *backends_out; + struct gensec_security_ops **backends; + int i, j, k, oid_idx; + int num_backends_out = 0; + + if (!oid_strings) { + return NULL; + } + + backends = gensec_security_mechs(gensec_security, gensec_security); + + backends_out = talloc_array(mem_ctx, struct gensec_security_ops_wrapper, 1); + if (!backends_out) { + return NULL; + } + backends_out[0].op = NULL; + backends_out[0].oid = NULL; + + /* Find backends in our preferred order, by walking our list, + * then looking in the supplied list */ + for (i=0; backends && backends[i]; i++) { + if (!backends[i]->oid) { + continue; + } + for (oid_idx = 0; oid_strings[oid_idx]; oid_idx++) { + if (strcmp(oid_strings[oid_idx], skip) == 0) { + continue; + } + + for (j=0; backends[i]->oid[j]; j++) { + if (!backends[i]->oid[j] || + !(strcmp(backends[i]->oid[j], + oid_strings[oid_idx]) == 0)) { + continue; + } + + for (k=0; backends_out[k].op; k++) { + if (backends_out[k].op == backends[i]) { + break; + } + } + + if (k < num_backends_out) { + /* already in there */ + continue; + } + + backends_out = talloc_realloc(mem_ctx, backends_out, + struct gensec_security_ops_wrapper, + num_backends_out + 2); + if (!backends_out) { + return NULL; + } + + backends_out[num_backends_out].op = backends[i]; + backends_out[num_backends_out].oid = backends[i]->oid[j]; + num_backends_out++; + backends_out[num_backends_out].op = NULL; + backends_out[num_backends_out].oid = NULL; + } + } + } + return backends_out; +} + +/** + * Return OIDS from the security subsystems listed + */ + +const char **gensec_security_oids_from_ops(TALLOC_CTX *mem_ctx, + struct gensec_security_ops **ops, + const char *skip) +{ + int i; + int j = 0; + int k; + const char **oid_list; + if (!ops) { + return NULL; + } + oid_list = talloc_array(mem_ctx, const char *, 1); + if (!oid_list) { + return NULL; + } + + for (i=0; ops && ops[i]; i++) { + if (!ops[i]->oid) { + continue; + } + + for (k = 0; ops[i]->oid[k]; k++) { + if (skip && strcmp(skip, ops[i]->oid[k])==0) { + } else { + oid_list = talloc_realloc(mem_ctx, oid_list, const char *, j + 2); + if (!oid_list) { + return NULL; + } + oid_list[j] = ops[i]->oid[k]; + j++; + } + } + } + oid_list[j] = NULL; + return oid_list; +} + + +/** + * Return OIDS from the security subsystems listed + */ + +const char **gensec_security_oids_from_ops_wrapped(TALLOC_CTX *mem_ctx, + const struct gensec_security_ops_wrapper *wops) +{ + int i; + int j = 0; + int k; + const char **oid_list; + if (!wops) { + return NULL; + } + oid_list = talloc_array(mem_ctx, const char *, 1); + if (!oid_list) { + return NULL; + } + + for (i=0; wops[i].op; i++) { + if (!wops[i].op->oid) { + continue; + } + + for (k = 0; wops[i].op->oid[k]; k++) { + oid_list = talloc_realloc(mem_ctx, oid_list, const char *, j + 2); + if (!oid_list) { + return NULL; + } + oid_list[j] = wops[i].op->oid[k]; + j++; + } + } + oid_list[j] = NULL; + return oid_list; +} + + +/** + * Return all the security subsystems currently enabled on a GENSEC context. + * + * This is taken from a list attached to the cli_credentials, and + * skips the OID in 'skip'. (Typically the SPNEGO OID) + * + */ + +const char **gensec_security_oids(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const char *skip) +{ + struct gensec_security_ops **ops + = gensec_security_mechs(gensec_security, mem_ctx); + return gensec_security_oids_from_ops(mem_ctx, ops, skip); +} + + + +/** + Start the GENSEC system, returning a context pointer. + @param mem_ctx The parent TALLOC memory context. + @param gensec_security Returned GENSEC context pointer. + @note The mem_ctx is only a parent and may be NULL. +*/ +static NTSTATUS gensec_start(TALLOC_CTX *mem_ctx, + struct event_context *ev, + struct loadparm_context *lp_ctx, + struct messaging_context *msg, + struct gensec_security **gensec_security) +{ + if (ev == NULL) { + DEBUG(0, ("No event context available!\n")); + return NT_STATUS_INTERNAL_ERROR; + } + + (*gensec_security) = talloc(mem_ctx, struct gensec_security); + NT_STATUS_HAVE_NO_MEMORY(*gensec_security); + + (*gensec_security)->ops = NULL; + + ZERO_STRUCT((*gensec_security)->target); + ZERO_STRUCT((*gensec_security)->peer_addr); + ZERO_STRUCT((*gensec_security)->my_addr); + + (*gensec_security)->subcontext = false; + (*gensec_security)->want_features = 0; + + (*gensec_security)->event_ctx = ev; + (*gensec_security)->msg_ctx = msg; + (*gensec_security)->lp_ctx = lp_ctx; + + return NT_STATUS_OK; +} + +/** + * Start a GENSEC subcontext, with a copy of the properties of the parent + * @param mem_ctx The parent TALLOC memory context. + * @param parent The parent GENSEC context + * @param gensec_security Returned GENSEC context pointer. + * @note Used by SPNEGO in particular, for the actual implementation mechanism + */ + +_PUBLIC_ NTSTATUS gensec_subcontext_start(TALLOC_CTX *mem_ctx, + struct gensec_security *parent, + struct gensec_security **gensec_security) +{ + (*gensec_security) = talloc(mem_ctx, struct gensec_security); + NT_STATUS_HAVE_NO_MEMORY(*gensec_security); + + (**gensec_security) = *parent; + (*gensec_security)->ops = NULL; + (*gensec_security)->private_data = NULL; + + (*gensec_security)->subcontext = true; + (*gensec_security)->event_ctx = parent->event_ctx; + (*gensec_security)->msg_ctx = parent->msg_ctx; + (*gensec_security)->lp_ctx = parent->lp_ctx; + + return NT_STATUS_OK; +} + +/** + Start the GENSEC system, in client mode, returning a context pointer. + @param mem_ctx The parent TALLOC memory context. + @param gensec_security Returned GENSEC context pointer. + @note The mem_ctx is only a parent and may be NULL. +*/ +_PUBLIC_ NTSTATUS gensec_client_start(TALLOC_CTX *mem_ctx, + struct gensec_security **gensec_security, + struct event_context *ev, + struct loadparm_context *lp_ctx) +{ + NTSTATUS status; + + status = gensec_start(mem_ctx, ev, lp_ctx, NULL, gensec_security); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + (*gensec_security)->gensec_role = GENSEC_CLIENT; + + return status; +} + +/** + Start the GENSEC system, in server mode, returning a context pointer. + @param mem_ctx The parent TALLOC memory context. + @param gensec_security Returned GENSEC context pointer. + @note The mem_ctx is only a parent and may be NULL. +*/ +_PUBLIC_ NTSTATUS gensec_server_start(TALLOC_CTX *mem_ctx, + struct event_context *ev, + struct loadparm_context *lp_ctx, + struct messaging_context *msg, + struct gensec_security **gensec_security) +{ + NTSTATUS status; + + if (!ev) { + DEBUG(0,("gensec_server_start: no event context given!\n")); + return NT_STATUS_INTERNAL_ERROR; + } + + if (!msg) { + DEBUG(0,("gensec_server_start: no messaging context given!\n")); + return NT_STATUS_INTERNAL_ERROR; + } + + status = gensec_start(mem_ctx, ev, lp_ctx, msg, gensec_security); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + (*gensec_security)->gensec_role = GENSEC_SERVER; + + return status; +} + +static NTSTATUS gensec_start_mech(struct gensec_security *gensec_security) +{ + NTSTATUS status; + DEBUG(5, ("Starting GENSEC %smechanism %s\n", + gensec_security->subcontext ? "sub" : "", + gensec_security->ops->name)); + switch (gensec_security->gensec_role) { + case GENSEC_CLIENT: + if (gensec_security->ops->client_start) { + status = gensec_security->ops->client_start(gensec_security); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(2, ("Failed to start GENSEC client mech %s: %s\n", + gensec_security->ops->name, nt_errstr(status))); + } + return status; + } + break; + case GENSEC_SERVER: + if (gensec_security->ops->server_start) { + status = gensec_security->ops->server_start(gensec_security); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("Failed to start GENSEC server mech %s: %s\n", + gensec_security->ops->name, nt_errstr(status))); + } + return status; + } + break; + } + return NT_STATUS_INVALID_PARAMETER; +} + +/** + * Start a GENSEC sub-mechanism by DCERPC allocated 'auth type' number + * @param gensec_security GENSEC context pointer. + * @param auth_type DCERPC auth type + * @param auth_level DCERPC auth level + */ + +_PUBLIC_ NTSTATUS gensec_start_mech_by_authtype(struct gensec_security *gensec_security, + uint8_t auth_type, uint8_t auth_level) +{ + gensec_security->ops = gensec_security_by_authtype(gensec_security, auth_type); + if (!gensec_security->ops) { + DEBUG(3, ("Could not find GENSEC backend for auth_type=%d\n", (int)auth_type)); + return NT_STATUS_INVALID_PARAMETER; + } + gensec_want_feature(gensec_security, GENSEC_FEATURE_DCE_STYLE); + gensec_want_feature(gensec_security, GENSEC_FEATURE_ASYNC_REPLIES); + if (auth_level == DCERPC_AUTH_LEVEL_INTEGRITY) { + gensec_want_feature(gensec_security, GENSEC_FEATURE_SIGN); + } else if (auth_level == DCERPC_AUTH_LEVEL_PRIVACY) { + gensec_want_feature(gensec_security, GENSEC_FEATURE_SIGN); + gensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL); + } else if (auth_level == DCERPC_AUTH_LEVEL_CONNECT) { + /* Default features */ + } else { + DEBUG(2,("auth_level %d not supported in DCE/RPC authentication\n", + auth_level)); + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_start_mech(gensec_security); +} + +_PUBLIC_ const char *gensec_get_name_by_authtype(uint8_t authtype) +{ + const struct gensec_security_ops *ops; + ops = gensec_security_by_authtype(NULL, authtype); + if (ops) { + return ops->name; + } + return NULL; +} + + +_PUBLIC_ const char *gensec_get_name_by_oid(const char *oid_string) +{ + const struct gensec_security_ops *ops; + ops = gensec_security_by_oid(NULL, oid_string); + if (ops) { + return ops->name; + } + return oid_string; +} + + +/** + * Start a GENSEC sub-mechanism with a specifed mechansim structure, used in SPNEGO + * + */ + +NTSTATUS gensec_start_mech_by_ops(struct gensec_security *gensec_security, + const struct gensec_security_ops *ops) +{ + gensec_security->ops = ops; + return gensec_start_mech(gensec_security); +} + +/** + * Start a GENSEC sub-mechanism by OID, used in SPNEGO + * + * @note This should also be used when you wish to just start NLTMSSP (for example), as it uses a + * well-known #define to hook it in. + */ + +_PUBLIC_ NTSTATUS gensec_start_mech_by_oid(struct gensec_security *gensec_security, + const char *mech_oid) +{ + gensec_security->ops = gensec_security_by_oid(gensec_security, mech_oid); + if (!gensec_security->ops) { + DEBUG(3, ("Could not find GENSEC backend for oid=%s\n", mech_oid)); + return NT_STATUS_INVALID_PARAMETER; + } + return gensec_start_mech(gensec_security); +} + +/** + * Start a GENSEC sub-mechanism by a well know SASL name + * + */ + +_PUBLIC_ NTSTATUS gensec_start_mech_by_sasl_name(struct gensec_security *gensec_security, + const char *sasl_name) +{ + gensec_security->ops = gensec_security_by_sasl_name(gensec_security, sasl_name); + if (!gensec_security->ops) { + DEBUG(3, ("Could not find GENSEC backend for sasl_name=%s\n", sasl_name)); + return NT_STATUS_INVALID_PARAMETER; + } + return gensec_start_mech(gensec_security); +} + +/** + * Start a GENSEC sub-mechanism with the preferred option from a SASL name list + * + */ + +_PUBLIC_ NTSTATUS gensec_start_mech_by_sasl_list(struct gensec_security *gensec_security, + const char **sasl_names) +{ + NTSTATUS nt_status = NT_STATUS_INVALID_PARAMETER; + TALLOC_CTX *mem_ctx = talloc_new(gensec_security); + const struct gensec_security_ops **ops; + int i; + if (!mem_ctx) { + return NT_STATUS_NO_MEMORY; + } + ops = gensec_security_by_sasl_list(gensec_security, mem_ctx, sasl_names); + if (!ops || !*ops) { + DEBUG(3, ("Could not find GENSEC backend for any of sasl_name = %s\n", + str_list_join(mem_ctx, + sasl_names, ' '))); + talloc_free(mem_ctx); + return NT_STATUS_INVALID_PARAMETER; + } + for (i=0; ops[i]; i++) { + nt_status = gensec_start_mech_by_ops(gensec_security, ops[i]); + if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_INVALID_PARAMETER)) { + break; + } + } + talloc_free(mem_ctx); + return nt_status; +} + +/** + * Start a GENSEC sub-mechanism by an internal name + * + */ + +_PUBLIC_ NTSTATUS gensec_start_mech_by_name(struct gensec_security *gensec_security, + const char *name) +{ + gensec_security->ops = gensec_security_by_name(gensec_security, name); + if (!gensec_security->ops) { + DEBUG(3, ("Could not find GENSEC backend for name=%s\n", name)); + return NT_STATUS_INVALID_PARAMETER; + } + return gensec_start_mech(gensec_security); +} + +/* + wrappers for the gensec function pointers +*/ +_PUBLIC_ NTSTATUS gensec_unseal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + if (!gensec_security->ops->unseal_packet) { + return NT_STATUS_NOT_IMPLEMENTED; + } + if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_security->ops->unseal_packet(gensec_security, mem_ctx, + data, length, + whole_pdu, pdu_length, + sig); +} + +_PUBLIC_ NTSTATUS gensec_check_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + if (!gensec_security->ops->check_packet) { + return NT_STATUS_NOT_IMPLEMENTED; + } + if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_security->ops->check_packet(gensec_security, mem_ctx, data, length, whole_pdu, pdu_length, sig); +} + +_PUBLIC_ NTSTATUS gensec_seal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + if (!gensec_security->ops->seal_packet) { + return NT_STATUS_NOT_IMPLEMENTED; + } + if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_security->ops->seal_packet(gensec_security, mem_ctx, data, length, whole_pdu, pdu_length, sig); +} + +_PUBLIC_ NTSTATUS gensec_sign_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + if (!gensec_security->ops->sign_packet) { + return NT_STATUS_NOT_IMPLEMENTED; + } + if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_security->ops->sign_packet(gensec_security, mem_ctx, data, length, whole_pdu, pdu_length, sig); +} + +_PUBLIC_ size_t gensec_sig_size(struct gensec_security *gensec_security, size_t data_size) +{ + if (!gensec_security->ops->sig_size) { + return 0; + } + if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + return 0; + } + + return gensec_security->ops->sig_size(gensec_security, data_size); +} + +size_t gensec_max_wrapped_size(struct gensec_security *gensec_security) +{ + if (!gensec_security->ops->max_wrapped_size) { + return (1 << 17); + } + + return gensec_security->ops->max_wrapped_size(gensec_security); +} + +size_t gensec_max_input_size(struct gensec_security *gensec_security) +{ + if (!gensec_security->ops->max_input_size) { + return (1 << 17) - gensec_sig_size(gensec_security, 1 << 17); + } + + return gensec_security->ops->max_input_size(gensec_security); +} + +_PUBLIC_ NTSTATUS gensec_wrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + if (!gensec_security->ops->wrap) { + return NT_STATUS_NOT_IMPLEMENTED; + } + return gensec_security->ops->wrap(gensec_security, mem_ctx, in, out); +} + +_PUBLIC_ NTSTATUS gensec_unwrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + if (!gensec_security->ops->unwrap) { + return NT_STATUS_NOT_IMPLEMENTED; + } + return gensec_security->ops->unwrap(gensec_security, mem_ctx, in, out); +} + +_PUBLIC_ NTSTATUS gensec_session_key(struct gensec_security *gensec_security, + DATA_BLOB *session_key) +{ + if (!gensec_security->ops->session_key) { + return NT_STATUS_NOT_IMPLEMENTED; + } + if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SESSION_KEY)) { + return NT_STATUS_NO_USER_SESSION_KEY; + } + + return gensec_security->ops->session_key(gensec_security, session_key); +} + +/** + * Return the credentials of a logged on user, including session keys + * etc. + * + * Only valid after a successful authentication + * + * May only be called once per authentication. + * + */ + +_PUBLIC_ NTSTATUS gensec_session_info(struct gensec_security *gensec_security, + struct auth_session_info **session_info) +{ + if (!gensec_security->ops->session_info) { + return NT_STATUS_NOT_IMPLEMENTED; + } + return gensec_security->ops->session_info(gensec_security, session_info); +} + +/** + * Next state function for the GENSEC state machine + * + * @param gensec_security GENSEC State + * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on + * @param in The request, as a DATA_BLOB + * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx + * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, + * or NT_STATUS_OK if the user is authenticated. + */ + +_PUBLIC_ NTSTATUS gensec_update(struct gensec_security *gensec_security, TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + return gensec_security->ops->update(gensec_security, out_mem_ctx, in, out); +} + +static void gensec_update_async_timed_handler(struct event_context *ev, struct timed_event *te, + struct timeval t, void *ptr) +{ + struct gensec_update_request *req = talloc_get_type(ptr, struct gensec_update_request); + req->status = req->gensec_security->ops->update(req->gensec_security, req, req->in, &req->out); + req->callback.fn(req, req->callback.private_data); +} + +/** + * Next state function for the GENSEC state machine async version + * + * @param gensec_security GENSEC State + * @param in The request, as a DATA_BLOB + * @param callback The function that will be called when the operation is + * finished, it should return gensec_update_recv() to get output + * @param private_data A private pointer that will be passed to the callback function + */ + +_PUBLIC_ void gensec_update_send(struct gensec_security *gensec_security, const DATA_BLOB in, + void (*callback)(struct gensec_update_request *req, void *private_data), + void *private_data) +{ + struct gensec_update_request *req = NULL; + struct timed_event *te = NULL; + + req = talloc(gensec_security, struct gensec_update_request); + if (!req) goto failed; + req->gensec_security = gensec_security; + req->in = in; + req->out = data_blob(NULL, 0); + req->callback.fn = callback; + req->callback.private_data = private_data; + + te = event_add_timed(gensec_security->event_ctx, req, + timeval_zero(), + gensec_update_async_timed_handler, req); + if (!te) goto failed; + + return; + +failed: + talloc_free(req); + callback(NULL, private_data); +} + +/** + * Next state function for the GENSEC state machine + * + * @param req GENSEC update request state + * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on + * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx + * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, + * or NT_STATUS_OK if the user is authenticated. + */ +_PUBLIC_ NTSTATUS gensec_update_recv(struct gensec_update_request *req, TALLOC_CTX *out_mem_ctx, DATA_BLOB *out) +{ + NTSTATUS status; + + NT_STATUS_HAVE_NO_MEMORY(req); + + *out = req->out; + talloc_steal(out_mem_ctx, out->data); + status = req->status; + + talloc_free(req); + return status; +} + +/** + * Set the requirement for a certain feature on the connection + * + */ + +_PUBLIC_ void gensec_want_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + gensec_security->want_features |= feature; +} + +/** + * Check the requirement for a certain feature on the connection + * + */ + +_PUBLIC_ bool gensec_have_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + if (!gensec_security->ops->have_feature) { + return false; + } + + /* We might 'have' features that we don't 'want', because the + * other end demanded them, or we can't neotiate them off */ + return gensec_security->ops->have_feature(gensec_security, feature); +} + +/** + * Associate a credentials structure with a GENSEC context - talloc_reference()s it to the context + * + */ + +_PUBLIC_ NTSTATUS gensec_set_credentials(struct gensec_security *gensec_security, struct cli_credentials *credentials) +{ + gensec_security->credentials = talloc_reference(gensec_security, credentials); + NT_STATUS_HAVE_NO_MEMORY(gensec_security->credentials); + gensec_want_feature(gensec_security, cli_credentials_get_gensec_features(gensec_security->credentials)); + return NT_STATUS_OK; +} + +/** + * Return the credentials structure associated with a GENSEC context + * + */ + +_PUBLIC_ struct cli_credentials *gensec_get_credentials(struct gensec_security *gensec_security) +{ + if (!gensec_security) { + return NULL; + } + return gensec_security->credentials; +} + +/** + * Set the target service (such as 'http' or 'host') on a GENSEC context - ensures it is talloc()ed + * + */ + +_PUBLIC_ NTSTATUS gensec_set_target_service(struct gensec_security *gensec_security, const char *service) +{ + gensec_security->target.service = talloc_strdup(gensec_security, service); + if (!gensec_security->target.service) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +_PUBLIC_ const char *gensec_get_target_service(struct gensec_security *gensec_security) +{ + if (gensec_security->target.service) { + return gensec_security->target.service; + } + + return "host"; +} + +/** + * Set the target hostname (suitable for kerberos resolutation) on a GENSEC context - ensures it is talloc()ed + * + */ + +_PUBLIC_ NTSTATUS gensec_set_target_hostname(struct gensec_security *gensec_security, const char *hostname) +{ + gensec_security->target.hostname = talloc_strdup(gensec_security, hostname); + if (hostname && !gensec_security->target.hostname) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +_PUBLIC_ const char *gensec_get_target_hostname(struct gensec_security *gensec_security) +{ + /* We allow the target hostname to be overriden for testing purposes */ + const char *target_hostname = lp_parm_string(gensec_security->lp_ctx, NULL, "gensec", "target_hostname"); + if (target_hostname) { + return target_hostname; + } + + if (gensec_security->target.hostname) { + return gensec_security->target.hostname; + } + + /* We could add use the 'set sockaddr' call, and do a reverse + * lookup, but this would be both insecure (compromising the + * way kerberos works) and add DNS timeouts */ + return NULL; +} + +/** + * Set (and talloc_reference) local and peer socket addresses onto a socket context on the GENSEC context + * + * This is so that kerberos can include these addresses in + * cryptographic tokens, to avoid certain attacks. + */ + +_PUBLIC_ NTSTATUS gensec_set_my_addr(struct gensec_security *gensec_security, struct socket_address *my_addr) +{ + gensec_security->my_addr = my_addr; + if (my_addr && !talloc_reference(gensec_security, my_addr)) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +_PUBLIC_ NTSTATUS gensec_set_peer_addr(struct gensec_security *gensec_security, struct socket_address *peer_addr) +{ + gensec_security->peer_addr = peer_addr; + if (peer_addr && !talloc_reference(gensec_security, peer_addr)) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +struct socket_address *gensec_get_my_addr(struct gensec_security *gensec_security) +{ + if (gensec_security->my_addr) { + return gensec_security->my_addr; + } + + /* We could add a 'set sockaddr' call, and do a lookup. This + * would avoid needing to do system calls if nothing asks. */ + return NULL; +} + +_PUBLIC_ struct socket_address *gensec_get_peer_addr(struct gensec_security *gensec_security) +{ + if (gensec_security->peer_addr) { + return gensec_security->peer_addr; + } + + /* We could add a 'set sockaddr' call, and do a lookup. This + * would avoid needing to do system calls if nothing asks. + * However, this is not appropriate for the peer addres on + * datagram sockets */ + return NULL; +} + + + +/** + * Set the target principal (assuming it it known, say from the SPNEGO reply) + * - ensures it is talloc()ed + * + */ + +NTSTATUS gensec_set_target_principal(struct gensec_security *gensec_security, const char *principal) +{ + gensec_security->target.principal = talloc_strdup(gensec_security, principal); + if (!gensec_security->target.principal) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +const char *gensec_get_target_principal(struct gensec_security *gensec_security) +{ + if (gensec_security->target.principal) { + return gensec_security->target.principal; + } + + return NULL; +} + +/* + register a GENSEC backend. + + The 'name' can be later used by other backends to find the operations + structure for this backend. +*/ +NTSTATUS gensec_register(const struct gensec_security_ops *ops) +{ + if (!lp_parm_bool(global_loadparm, NULL, "gensec", ops->name, ops->enabled)) { + DEBUG(2,("gensec subsystem %s is disabled\n", ops->name)); + return NT_STATUS_OK; + } + + if (gensec_security_by_name(NULL, ops->name) != NULL) { + /* its already registered! */ + DEBUG(0,("GENSEC backend '%s' already registered\n", + ops->name)); + return NT_STATUS_OBJECT_NAME_COLLISION; + } + + generic_security_ops = talloc_realloc(talloc_autofree_context(), + generic_security_ops, + struct gensec_security_ops *, + gensec_num_backends+2); + if (!generic_security_ops) { + return NT_STATUS_NO_MEMORY; + } + + generic_security_ops[gensec_num_backends] = discard_const_p(struct gensec_security_ops, ops); + gensec_num_backends++; + generic_security_ops[gensec_num_backends] = NULL; + + DEBUG(3,("GENSEC backend '%s' registered\n", + ops->name)); + + return NT_STATUS_OK; +} + +/* + return the GENSEC interface version, and the size of some critical types + This can be used by backends to either detect compilation errors, or provide + multiple implementations for different smbd compilation options in one module +*/ +const struct gensec_critical_sizes *gensec_interface_version(void) +{ + static const struct gensec_critical_sizes critical_sizes = { + GENSEC_INTERFACE_VERSION, + sizeof(struct gensec_security_ops), + sizeof(struct gensec_security), + }; + + return &critical_sizes; +} + +static int sort_gensec(struct gensec_security_ops **gs1, struct gensec_security_ops **gs2) { + return (*gs2)->priority - (*gs1)->priority; +} + +/* + initialise the GENSEC subsystem +*/ +_PUBLIC_ NTSTATUS gensec_init(struct loadparm_context *lp_ctx) +{ + static bool initialized = false; + extern NTSTATUS gensec_sasl_init(void); + extern NTSTATUS gensec_krb5_init(void); + extern NTSTATUS gensec_schannel_init(void); + extern NTSTATUS gensec_spnego_init(void); + extern NTSTATUS gensec_gssapi_init(void); + extern NTSTATUS gensec_ntlmssp_init(void); + + init_module_fn static_init[] = { STATIC_gensec_MODULES }; + init_module_fn *shared_init; + + if (initialized) return NT_STATUS_OK; + initialized = true; + + shared_init = load_samba_modules(NULL, lp_ctx, "gensec"); + + run_init_functions(static_init); + run_init_functions(shared_init); + + talloc_free(shared_init); + + qsort(generic_security_ops, gensec_num_backends, sizeof(*generic_security_ops), QSORT_CAST sort_gensec); + + return NT_STATUS_OK; +} diff --git a/source4/auth/gensec/gensec.h b/source4/auth/gensec/gensec.h new file mode 100644 index 0000000000..2830297ffe --- /dev/null +++ b/source4/auth/gensec/gensec.h @@ -0,0 +1,296 @@ +/* + Unix SMB/CIFS implementation. + + Generic Authentication Interface + + Copyright (C) Andrew Tridgell 2003 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef __GENSEC_H__ +#define __GENSEC_H__ + +#define GENSEC_OID_NTLMSSP "1.3.6.1.4.1.311.2.2.10" +#define GENSEC_OID_SPNEGO "1.3.6.1.5.5.2" +#define GENSEC_OID_KERBEROS5 "1.2.840.113554.1.2.2" +#define GENSEC_OID_KERBEROS5_OLD "1.2.840.48018.1.2.2" +#define GENSEC_OID_KERBEROS5_USER2USER "1.2.840.113554.1.2.2.3" + +enum gensec_priority { + GENSEC_SPNEGO = 90, + GENSEC_GSSAPI = 80, + GENSEC_KRB5 = 70, + GENSEC_SCHANNEL = 60, + GENSEC_NTLMSSP = 50, + GENSEC_SASL = 20, + GENSEC_OTHER = 0 +}; + +struct gensec_security; +struct gensec_target { + const char *principal; + const char *hostname; + const char *service; +}; + +#define GENSEC_FEATURE_SESSION_KEY 0x00000001 +#define GENSEC_FEATURE_SIGN 0x00000002 +#define GENSEC_FEATURE_SEAL 0x00000004 +#define GENSEC_FEATURE_DCE_STYLE 0x00000008 +#define GENSEC_FEATURE_ASYNC_REPLIES 0x00000010 +#define GENSEC_FEATURE_DATAGRAM_MODE 0x00000020 +#define GENSEC_FEATURE_SIGN_PKT_HEADER 0x00000040 +#define GENSEC_FEATURE_NEW_SPNEGO 0x00000080 + +/* GENSEC mode */ +enum gensec_role +{ + GENSEC_SERVER, + GENSEC_CLIENT +}; + +struct auth_session_info; +struct cli_credentials; + +struct gensec_update_request { + struct gensec_security *gensec_security; + void *private_data; + DATA_BLOB in; + DATA_BLOB out; + NTSTATUS status; + struct { + void (*fn)(struct gensec_update_request *req, void *private_data); + void *private_data; + } callback; +}; + +struct gensec_security_ops { + const char *name; + const char *sasl_name; + uint8_t auth_type; /* 0 if not offered on DCE-RPC */ + const char **oid; /* NULL if not offered by SPNEGO */ + NTSTATUS (*client_start)(struct gensec_security *gensec_security); + NTSTATUS (*server_start)(struct gensec_security *gensec_security); + /** + Determine if a packet has the right 'magic' for this mechanism + */ + NTSTATUS (*magic)(struct gensec_security *gensec_security, + const DATA_BLOB *first_packet); + NTSTATUS (*update)(struct gensec_security *gensec_security, TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out); + NTSTATUS (*seal_packet)(struct gensec_security *gensec_security, TALLOC_CTX *sig_mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig); + NTSTATUS (*sign_packet)(struct gensec_security *gensec_security, TALLOC_CTX *sig_mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig); + size_t (*sig_size)(struct gensec_security *gensec_security, size_t data_size); + size_t (*max_input_size)(struct gensec_security *gensec_security); + size_t (*max_wrapped_size)(struct gensec_security *gensec_security); + NTSTATUS (*check_packet)(struct gensec_security *gensec_security, TALLOC_CTX *sig_mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig); + NTSTATUS (*unseal_packet)(struct gensec_security *gensec_security, TALLOC_CTX *sig_mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig); + NTSTATUS (*wrap)(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out); + NTSTATUS (*unwrap)(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out); + NTSTATUS (*wrap_packets)(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed); + NTSTATUS (*unwrap_packets)(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed); + NTSTATUS (*packet_full_request)(struct gensec_security *gensec_security, + DATA_BLOB blob, size_t *size); + NTSTATUS (*session_key)(struct gensec_security *gensec_security, DATA_BLOB *session_key); + NTSTATUS (*session_info)(struct gensec_security *gensec_security, + struct auth_session_info **session_info); + bool (*have_feature)(struct gensec_security *gensec_security, + uint32_t feature); + bool enabled; + bool kerberos; + enum gensec_priority priority; +}; + +struct gensec_security_ops_wrapper { + const struct gensec_security_ops *op; + const char *oid; +}; + +#define GENSEC_INTERFACE_VERSION 0 + +struct gensec_security { + const struct gensec_security_ops *ops; + struct loadparm_context *lp_ctx; + void *private_data; + struct cli_credentials *credentials; + struct gensec_target target; + enum gensec_role gensec_role; + bool subcontext; + uint32_t want_features; + struct event_context *event_ctx; + struct messaging_context *msg_ctx; /* only valid as server */ + struct socket_address *my_addr, *peer_addr; +}; + +/* this structure is used by backends to determine the size of some critical types */ +struct gensec_critical_sizes { + int interface_version; + int sizeof_gensec_security_ops; + int sizeof_gensec_security; +}; + +/* Socket wrapper */ + +struct gensec_security; +struct socket_context; + +NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, + struct socket_context *current_socket, + struct event_context *ev, + void (*recv_handler)(void *, uint16_t), + void *recv_private, + struct socket_context **new_socket); +/* These functions are for use here only (public because SPNEGO must + * use them for recursion) */ +NTSTATUS gensec_wrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed); +/* These functions are for use here only (public because SPNEGO must + * use them for recursion) */ +NTSTATUS gensec_unwrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed); + +/* These functions are for use here only (public because SPNEGO must + * use them for recursion) */ +NTSTATUS gensec_packet_full_request(struct gensec_security *gensec_security, + DATA_BLOB blob, size_t *size); + +struct loadparm_context; + +NTSTATUS gensec_subcontext_start(TALLOC_CTX *mem_ctx, + struct gensec_security *parent, + struct gensec_security **gensec_security); +NTSTATUS gensec_client_start(TALLOC_CTX *mem_ctx, + struct gensec_security **gensec_security, + struct event_context *ev, + struct loadparm_context *lp_ctx); +NTSTATUS gensec_start_mech_by_sasl_list(struct gensec_security *gensec_security, + const char **sasl_names); +NTSTATUS gensec_update(struct gensec_security *gensec_security, TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out); +void gensec_update_send(struct gensec_security *gensec_security, const DATA_BLOB in, + void (*callback)(struct gensec_update_request *req, void *private_data), + void *private_data); +NTSTATUS gensec_update_recv(struct gensec_update_request *req, TALLOC_CTX *out_mem_ctx, DATA_BLOB *out); +void gensec_want_feature(struct gensec_security *gensec_security, + uint32_t feature); +bool gensec_have_feature(struct gensec_security *gensec_security, + uint32_t feature); +NTSTATUS gensec_set_credentials(struct gensec_security *gensec_security, struct cli_credentials *credentials); +NTSTATUS gensec_set_target_service(struct gensec_security *gensec_security, const char *service); +const char *gensec_get_target_service(struct gensec_security *gensec_security); +NTSTATUS gensec_set_target_hostname(struct gensec_security *gensec_security, const char *hostname); +const char *gensec_get_target_hostname(struct gensec_security *gensec_security); +NTSTATUS gensec_session_key(struct gensec_security *gensec_security, + DATA_BLOB *session_key); +NTSTATUS gensec_start_mech_by_oid(struct gensec_security *gensec_security, + const char *mech_oid); +const char *gensec_get_name_by_oid(const char *oid_string); +struct cli_credentials *gensec_get_credentials(struct gensec_security *gensec_security); +struct socket_address *gensec_get_peer_addr(struct gensec_security *gensec_security); +NTSTATUS gensec_init(struct loadparm_context *lp_ctx); +NTSTATUS gensec_unseal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig); +NTSTATUS gensec_check_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig); +size_t gensec_sig_size(struct gensec_security *gensec_security, size_t data_size); +NTSTATUS gensec_seal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig); +NTSTATUS gensec_sign_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig); +NTSTATUS gensec_start_mech_by_authtype(struct gensec_security *gensec_security, + uint8_t auth_type, uint8_t auth_level); +const char *gensec_get_name_by_authtype(uint8_t authtype); +NTSTATUS gensec_server_start(TALLOC_CTX *mem_ctx, + struct event_context *ev, + struct loadparm_context *lp_ctx, + struct messaging_context *msg, + struct gensec_security **gensec_security); +NTSTATUS gensec_session_info(struct gensec_security *gensec_security, + struct auth_session_info **session_info); +NTSTATUS auth_nt_status_squash(NTSTATUS nt_status); +struct creds_CredentialState; +NTSTATUS dcerpc_schannel_creds(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + struct creds_CredentialState **creds); +NTSTATUS gensec_set_peer_addr(struct gensec_security *gensec_security, struct socket_address *peer_addr); +NTSTATUS gensec_set_my_addr(struct gensec_security *gensec_security, struct socket_address *my_addr); + +NTSTATUS gensec_start_mech_by_name(struct gensec_security *gensec_security, + const char *name); + +NTSTATUS gensec_unwrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out); +NTSTATUS gensec_wrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out); + +struct gensec_security_ops **gensec_security_all(void); +struct gensec_security_ops **gensec_use_kerberos_mechs(TALLOC_CTX *mem_ctx, + struct gensec_security_ops **old_gensec_list, + struct cli_credentials *creds); + +NTSTATUS gensec_start_mech_by_sasl_name(struct gensec_security *gensec_security, + const char *sasl_name); + + +#endif /* __GENSEC_H__ */ diff --git a/source4/auth/gensec/gensec.pc.in b/source4/auth/gensec/gensec.pc.in new file mode 100644 index 0000000000..faf772ae73 --- /dev/null +++ b/source4/auth/gensec/gensec.pc.in @@ -0,0 +1,11 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ +modulesdir=${prefix}/modules/gensec + +Name: gensec +Description: Generic Security Library +Version: 0.0.1 +Libs: -L${libdir} -lgensec +Cflags: -I${includedir} -DHAVE_IMMEDIATE_STRUCTURES=1 diff --git a/source4/auth/gensec/gensec_gssapi.c b/source4/auth/gensec/gensec_gssapi.c new file mode 100644 index 0000000000..1334e799ae --- /dev/null +++ b/source4/auth/gensec/gensec_gssapi.c @@ -0,0 +1,1522 @@ +/* + Unix SMB/CIFS implementation. + + Kerberos backend for GENSEC + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + Copyright (C) Stefan Metzmacher <metze@samba.org> 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/events/events.h" +#include "system/kerberos.h" +#include "auth/kerberos/kerberos.h" +#include "librpc/gen_ndr/krb5pac.h" +#include "auth/auth.h" +#include "lib/ldb/include/ldb.h" +#include "auth/auth_sam.h" +#include "librpc/rpc/dcerpc.h" +#include "auth/credentials/credentials.h" +#include "auth/credentials/credentials_krb5.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" +#include "param/param.h" +#include "auth/session_proto.h" +#include <gssapi/gssapi.h> +#include <gssapi/gssapi_krb5.h> +#include "auth/gensec/gensec_gssapi.h" + +static size_t gensec_gssapi_max_input_size(struct gensec_security *gensec_security); +static size_t gensec_gssapi_max_wrapped_size(struct gensec_security *gensec_security); + +static char *gssapi_error_string(TALLOC_CTX *mem_ctx, + OM_uint32 maj_stat, OM_uint32 min_stat, + const gss_OID mech) +{ + OM_uint32 disp_min_stat, disp_maj_stat; + gss_buffer_desc maj_error_message; + gss_buffer_desc min_error_message; + char *maj_error_string, *min_error_string; + OM_uint32 msg_ctx = 0; + + char *ret; + + maj_error_message.value = NULL; + min_error_message.value = NULL; + maj_error_message.length = 0; + min_error_message.length = 0; + + disp_maj_stat = gss_display_status(&disp_min_stat, maj_stat, GSS_C_GSS_CODE, + mech, &msg_ctx, &maj_error_message); + disp_maj_stat = gss_display_status(&disp_min_stat, min_stat, GSS_C_MECH_CODE, + mech, &msg_ctx, &min_error_message); + + maj_error_string = talloc_strndup(mem_ctx, (char *)maj_error_message.value, maj_error_message.length); + + min_error_string = talloc_strndup(mem_ctx, (char *)min_error_message.value, min_error_message.length); + + ret = talloc_asprintf(mem_ctx, "%s: %s", maj_error_string, min_error_string); + + talloc_free(maj_error_string); + talloc_free(min_error_string); + + gss_release_buffer(&disp_min_stat, &maj_error_message); + gss_release_buffer(&disp_min_stat, &min_error_message); + + return ret; +} + + +static int gensec_gssapi_destructor(struct gensec_gssapi_state *gensec_gssapi_state) +{ + OM_uint32 maj_stat, min_stat; + + if (gensec_gssapi_state->delegated_cred_handle != GSS_C_NO_CREDENTIAL) { + maj_stat = gss_release_cred(&min_stat, + &gensec_gssapi_state->delegated_cred_handle); + } + + if (gensec_gssapi_state->gssapi_context != GSS_C_NO_CONTEXT) { + maj_stat = gss_delete_sec_context (&min_stat, + &gensec_gssapi_state->gssapi_context, + GSS_C_NO_BUFFER); + } + + if (gensec_gssapi_state->server_name != GSS_C_NO_NAME) { + maj_stat = gss_release_name(&min_stat, &gensec_gssapi_state->server_name); + } + if (gensec_gssapi_state->client_name != GSS_C_NO_NAME) { + maj_stat = gss_release_name(&min_stat, &gensec_gssapi_state->client_name); + } + + if (gensec_gssapi_state->lucid) { + gss_krb5_free_lucid_sec_context(&min_stat, gensec_gssapi_state->lucid); + } + + return 0; +} + +static NTSTATUS gensec_gssapi_init_lucid(struct gensec_gssapi_state *gensec_gssapi_state) +{ + OM_uint32 maj_stat, min_stat; + + if (gensec_gssapi_state->lucid) { + return NT_STATUS_OK; + } + + maj_stat = gss_krb5_export_lucid_sec_context(&min_stat, + &gensec_gssapi_state->gssapi_context, + 1, + (void **)&gensec_gssapi_state->lucid); + if (maj_stat != GSS_S_COMPLETE) { + DEBUG(0,("gensec_gssapi_init_lucid: %s\n", + gssapi_error_string(gensec_gssapi_state, + maj_stat, min_stat, + gensec_gssapi_state->gss_oid))); + return NT_STATUS_INTERNAL_ERROR; + } + + if (gensec_gssapi_state->lucid->version != 1) { + DEBUG(0,("gensec_gssapi_init_lucid: lucid version[%d] != 1\n", + gensec_gssapi_state->lucid->version)); + gss_krb5_free_lucid_sec_context(&min_stat, gensec_gssapi_state->lucid); + gensec_gssapi_state->lucid = NULL; + return NT_STATUS_INTERNAL_ERROR; + } + + return NT_STATUS_OK; +} + +static NTSTATUS gensec_gssapi_start(struct gensec_security *gensec_security) +{ + struct gensec_gssapi_state *gensec_gssapi_state; + krb5_error_code ret; + struct gsskrb5_send_to_kdc send_to_kdc; + + gensec_gssapi_state = talloc(gensec_security, struct gensec_gssapi_state); + if (!gensec_gssapi_state) { + return NT_STATUS_NO_MEMORY; + } + + gensec_gssapi_state->gss_exchange_count = 0; + gensec_gssapi_state->max_wrap_buf_size + = lp_parm_int(gensec_security->lp_ctx, NULL, "gensec_gssapi", "max wrap buf size", 65536); + + gensec_gssapi_state->sasl = false; + gensec_gssapi_state->sasl_state = STAGE_GSS_NEG; + + gensec_security->private_data = gensec_gssapi_state; + + gensec_gssapi_state->gssapi_context = GSS_C_NO_CONTEXT; + gensec_gssapi_state->server_name = GSS_C_NO_NAME; + gensec_gssapi_state->client_name = GSS_C_NO_NAME; + gensec_gssapi_state->lucid = NULL; + + /* TODO: Fill in channel bindings */ + gensec_gssapi_state->input_chan_bindings = GSS_C_NO_CHANNEL_BINDINGS; + + gensec_gssapi_state->want_flags = 0; + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec_gssapi", "mutual", true)) { + gensec_gssapi_state->want_flags |= GSS_C_MUTUAL_FLAG; + } + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec_gssapi", "delegation", true)) { + gensec_gssapi_state->want_flags |= GSS_C_DELEG_FLAG; + } + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec_gssapi", "replay", true)) { + gensec_gssapi_state->want_flags |= GSS_C_REPLAY_FLAG; + } + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec_gssapi", "sequence", true)) { + gensec_gssapi_state->want_flags |= GSS_C_SEQUENCE_FLAG; + } + + gensec_gssapi_state->got_flags = 0; + + gensec_gssapi_state->session_key = data_blob(NULL, 0); + gensec_gssapi_state->pac = data_blob(NULL, 0); + + gensec_gssapi_state->delegated_cred_handle = GSS_C_NO_CREDENTIAL; + gensec_gssapi_state->sig_size = 0; + + talloc_set_destructor(gensec_gssapi_state, gensec_gssapi_destructor); + + if (gensec_security->want_features & GENSEC_FEATURE_SIGN) { + gensec_gssapi_state->want_flags |= GSS_C_INTEG_FLAG; + } + if (gensec_security->want_features & GENSEC_FEATURE_SEAL) { + gensec_gssapi_state->want_flags |= GSS_C_CONF_FLAG; + } + if (gensec_security->want_features & GENSEC_FEATURE_DCE_STYLE) { + gensec_gssapi_state->want_flags |= GSS_C_DCE_STYLE; + } + + gensec_gssapi_state->gss_oid = GSS_C_NULL_OID; + + send_to_kdc.func = smb_krb5_send_and_recv_func; + send_to_kdc.ptr = gensec_security->event_ctx; + + ret = gsskrb5_set_send_to_kdc(&send_to_kdc); + if (ret) { + DEBUG(1,("gensec_krb5_start: gsskrb5_set_send_to_kdc failed\n")); + talloc_free(gensec_gssapi_state); + return NT_STATUS_INTERNAL_ERROR; + } + if (lp_realm(gensec_security->lp_ctx) && *lp_realm(gensec_security->lp_ctx)) { + char *upper_realm = strupper_talloc(gensec_gssapi_state, lp_realm(gensec_security->lp_ctx)); + if (!upper_realm) { + DEBUG(1,("gensec_krb5_start: could not uppercase realm: %s\n", lp_realm(gensec_security->lp_ctx))); + talloc_free(gensec_gssapi_state); + return NT_STATUS_NO_MEMORY; + } + ret = gsskrb5_set_default_realm(upper_realm); + talloc_free(upper_realm); + if (ret) { + DEBUG(1,("gensec_krb5_start: gsskrb5_set_default_realm failed\n")); + talloc_free(gensec_gssapi_state); + return NT_STATUS_INTERNAL_ERROR; + } + } + + /* don't do DNS lookups of any kind, it might/will fail for a netbios name */ + ret = gsskrb5_set_dns_canonicalize(lp_parm_bool(gensec_security->lp_ctx, NULL, "krb5", "set_dns_canonicalize", false)); + if (ret) { + DEBUG(1,("gensec_krb5_start: gsskrb5_set_dns_canonicalize failed\n")); + talloc_free(gensec_gssapi_state); + return NT_STATUS_INTERNAL_ERROR; + } + + ret = smb_krb5_init_context(gensec_gssapi_state, + gensec_security->event_ctx, + gensec_security->lp_ctx, + &gensec_gssapi_state->smb_krb5_context); + if (ret) { + DEBUG(1,("gensec_krb5_start: krb5_init_context failed (%s)\n", + error_message(ret))); + talloc_free(gensec_gssapi_state); + return NT_STATUS_INTERNAL_ERROR; + } + return NT_STATUS_OK; +} + +static NTSTATUS gensec_gssapi_server_start(struct gensec_security *gensec_security) +{ + NTSTATUS nt_status; + int ret; + struct gensec_gssapi_state *gensec_gssapi_state; + struct cli_credentials *machine_account; + struct gssapi_creds_container *gcc; + + nt_status = gensec_gssapi_start(gensec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + + machine_account = gensec_get_credentials(gensec_security); + + if (!machine_account) { + DEBUG(3, ("No machine account credentials specified\n")); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } else { + ret = cli_credentials_get_server_gss_creds(machine_account, + gensec_security->event_ctx, + gensec_security->lp_ctx, &gcc); + if (ret) { + DEBUG(1, ("Aquiring acceptor credentials failed: %s\n", + error_message(ret))); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + } + + gensec_gssapi_state->server_cred = gcc; + return NT_STATUS_OK; + +} + +static NTSTATUS gensec_gssapi_sasl_server_start(struct gensec_security *gensec_security) +{ + NTSTATUS nt_status; + struct gensec_gssapi_state *gensec_gssapi_state; + nt_status = gensec_gssapi_server_start(gensec_security); + + if (NT_STATUS_IS_OK(nt_status)) { + gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + gensec_gssapi_state->sasl = true; + } + return nt_status; +} + +static NTSTATUS gensec_gssapi_client_start(struct gensec_security *gensec_security) +{ + struct gensec_gssapi_state *gensec_gssapi_state; + struct cli_credentials *creds = gensec_get_credentials(gensec_security); + krb5_error_code ret; + NTSTATUS nt_status; + gss_buffer_desc name_token; + gss_OID name_type; + OM_uint32 maj_stat, min_stat; + const char *hostname = gensec_get_target_hostname(gensec_security); + const char *principal; + struct gssapi_creds_container *gcc; + + if (!hostname) { + DEBUG(1, ("Could not determine hostname for target computer, cannot use kerberos\n")); + return NT_STATUS_INVALID_PARAMETER; + } + if (is_ipaddress(hostname)) { + DEBUG(2, ("Cannot do GSSAPI to an IP address\n")); + return NT_STATUS_INVALID_PARAMETER; + } + if (strcmp(hostname, "localhost") == 0) { + DEBUG(2, ("GSSAPI to 'localhost' does not make sense\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + nt_status = gensec_gssapi_start(gensec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + + gensec_gssapi_state->gss_oid = gss_mech_krb5; + + principal = gensec_get_target_principal(gensec_security); + if (principal && lp_client_use_spnego_principal(gensec_security->lp_ctx)) { + name_type = GSS_C_NULL_OID; + } else { + principal = talloc_asprintf(gensec_gssapi_state, "%s@%s", + gensec_get_target_service(gensec_security), + hostname); + + name_type = GSS_C_NT_HOSTBASED_SERVICE; + } + name_token.value = discard_const_p(uint8_t, principal); + name_token.length = strlen(principal); + + + maj_stat = gss_import_name (&min_stat, + &name_token, + name_type, + &gensec_gssapi_state->server_name); + if (maj_stat) { + DEBUG(2, ("GSS Import name of %s failed: %s\n", + (char *)name_token.value, + gssapi_error_string(gensec_gssapi_state, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_INVALID_PARAMETER; + } + + ret = cli_credentials_get_client_gss_creds(creds, + gensec_security->event_ctx, + gensec_security->lp_ctx, &gcc); + switch (ret) { + case 0: + break; + case KRB5KDC_ERR_PREAUTH_FAILED: + return NT_STATUS_LOGON_FAILURE; + case KRB5_KDC_UNREACH: + DEBUG(3, ("Cannot reach a KDC we require to contact %s\n", principal)); + return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */ + default: + DEBUG(1, ("Aquiring initiator credentials failed\n")); + return NT_STATUS_UNSUCCESSFUL; + } + + gensec_gssapi_state->client_cred = gcc; + if (!talloc_reference(gensec_gssapi_state, gcc)) { + return NT_STATUS_NO_MEMORY; + } + + return NT_STATUS_OK; +} + +static NTSTATUS gensec_gssapi_sasl_client_start(struct gensec_security *gensec_security) +{ + NTSTATUS nt_status; + struct gensec_gssapi_state *gensec_gssapi_state; + nt_status = gensec_gssapi_client_start(gensec_security); + + if (NT_STATUS_IS_OK(nt_status)) { + gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + gensec_gssapi_state->sasl = true; + } + return nt_status; +} + + +/** + * Check if the packet is one for this mechansim + * + * @param gensec_security GENSEC state + * @param in The request, as a DATA_BLOB + * @return Error, INVALID_PARAMETER if it's not a packet for us + * or NT_STATUS_OK if the packet is ok. + */ + +static NTSTATUS gensec_gssapi_magic(struct gensec_security *gensec_security, + const DATA_BLOB *in) +{ + if (gensec_gssapi_check_oid(in, GENSEC_OID_KERBEROS5)) { + return NT_STATUS_OK; + } else { + return NT_STATUS_INVALID_PARAMETER; + } +} + + +/** + * Next state function for the GSSAPI GENSEC mechanism + * + * @param gensec_gssapi_state GSSAPI State + * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on + * @param in The request, as a DATA_BLOB + * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx + * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, + * or NT_STATUS_OK if the user is authenticated. + */ + +static NTSTATUS gensec_gssapi_update(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE; + OM_uint32 maj_stat, min_stat; + OM_uint32 min_stat2; + gss_buffer_desc input_token, output_token; + gss_OID gss_oid_p = NULL; + input_token.length = in.length; + input_token.value = in.data; + + switch (gensec_gssapi_state->sasl_state) { + case STAGE_GSS_NEG: + { + switch (gensec_security->gensec_role) { + case GENSEC_CLIENT: + { + maj_stat = gss_init_sec_context(&min_stat, + gensec_gssapi_state->client_cred->creds, + &gensec_gssapi_state->gssapi_context, + gensec_gssapi_state->server_name, + gensec_gssapi_state->gss_oid, + gensec_gssapi_state->want_flags, + 0, + gensec_gssapi_state->input_chan_bindings, + &input_token, + &gss_oid_p, + &output_token, + &gensec_gssapi_state->got_flags, /* ret flags */ + NULL); + if (gss_oid_p) { + gensec_gssapi_state->gss_oid = gss_oid_p; + } + break; + } + case GENSEC_SERVER: + { + maj_stat = gss_accept_sec_context(&min_stat, + &gensec_gssapi_state->gssapi_context, + gensec_gssapi_state->server_cred->creds, + &input_token, + gensec_gssapi_state->input_chan_bindings, + &gensec_gssapi_state->client_name, + &gss_oid_p, + &output_token, + &gensec_gssapi_state->got_flags, + NULL, + &gensec_gssapi_state->delegated_cred_handle); + if (gss_oid_p) { + gensec_gssapi_state->gss_oid = gss_oid_p; + } + break; + } + default: + return NT_STATUS_INVALID_PARAMETER; + + } + + gensec_gssapi_state->gss_exchange_count++; + + if (maj_stat == GSS_S_COMPLETE) { + *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length); + gss_release_buffer(&min_stat2, &output_token); + + if (gensec_gssapi_state->got_flags & GSS_C_DELEG_FLAG) { + DEBUG(5, ("gensec_gssapi: credentials were delegated\n")); + } else { + DEBUG(5, ("gensec_gssapi: NO credentials were delegated\n")); + } + + /* We may have been invoked as SASL, so there + * is more work to do */ + if (gensec_gssapi_state->sasl) { + /* Due to a very subtle interaction + * with SASL and the LDAP libs, we + * must ensure the data pointer is + * != NULL, but the length is 0. + * + * This ensures we send a 'zero + * length' (rather than NULL) response + */ + + if (!out->data) { + out->data = (uint8_t *)talloc_strdup(out_mem_ctx, "\0"); + } + + gensec_gssapi_state->sasl_state = STAGE_SASL_SSF_NEG; + return NT_STATUS_MORE_PROCESSING_REQUIRED; + } else { + gensec_gssapi_state->sasl_state = STAGE_DONE; + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + DEBUG(5, ("GSSAPI Connection will be cryptographicly sealed\n")); + } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + DEBUG(5, ("GSSAPI Connection will be cryptographicly signed\n")); + } else { + DEBUG(5, ("GSSAPI Connection will have no cryptographic protection\n")); + } + + return NT_STATUS_OK; + } + } else if (maj_stat == GSS_S_CONTINUE_NEEDED) { + *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length); + gss_release_buffer(&min_stat2, &output_token); + + return NT_STATUS_MORE_PROCESSING_REQUIRED; + } else if (gss_oid_equal(gensec_gssapi_state->gss_oid, gss_mech_krb5)) { + switch (min_stat) { + case KRB5_KDC_UNREACH: + DEBUG(3, ("Cannot reach a KDC we require: %s\n", + gssapi_error_string(gensec_gssapi_state, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */ + case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN: + DEBUG(3, ("Server is not registered with our KDC: %s\n", + gssapi_error_string(gensec_gssapi_state, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */ + case KRB5KRB_AP_ERR_MSG_TYPE: + /* garbage input, possibly from the auto-mech detection */ + return NT_STATUS_INVALID_PARAMETER; + default: + DEBUG(1, ("GSS Update(krb5)(%d) Update failed: %s\n", + gensec_gssapi_state->gss_exchange_count, + gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return nt_status; + } + } else { + DEBUG(1, ("GSS Update(%d) failed: %s\n", + gensec_gssapi_state->gss_exchange_count, + gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return nt_status; + } + break; + } + + /* These last two stages are only done if we were invoked as SASL */ + case STAGE_SASL_SSF_NEG: + { + switch (gensec_security->gensec_role) { + case GENSEC_CLIENT: + { + uint8_t maxlength_proposed[4]; + uint8_t maxlength_accepted[4]; + uint8_t security_supported; + int conf_state; + gss_qop_t qop_state; + input_token.length = in.length; + input_token.value = in.data; + + /* As a client, we have just send a + * zero-length blob to the server (after the + * normal GSSAPI exchange), and it has replied + * with it's SASL negotiation */ + + maj_stat = gss_unwrap(&min_stat, + gensec_gssapi_state->gssapi_context, + &input_token, + &output_token, + &conf_state, + &qop_state); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("gensec_gssapi_update: GSS UnWrap of SASL protection negotiation failed: %s\n", + gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + if (output_token.length < 4) { + return NT_STATUS_INVALID_PARAMETER; + } + + memcpy(maxlength_proposed, output_token.value, 4); + gss_release_buffer(&min_stat, &output_token); + + /* first byte is the proposed security */ + security_supported = maxlength_proposed[0]; + maxlength_proposed[0] = '\0'; + + /* Rest is the proposed max wrap length */ + gensec_gssapi_state->max_wrap_buf_size = MIN(RIVAL(maxlength_proposed, 0), + gensec_gssapi_state->max_wrap_buf_size); + gensec_gssapi_state->sasl_protection = 0; + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + if (security_supported & NEG_SEAL) { + gensec_gssapi_state->sasl_protection |= NEG_SEAL; + } + } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + if (security_supported & NEG_SIGN) { + gensec_gssapi_state->sasl_protection |= NEG_SIGN; + } + } else if (security_supported & NEG_NONE) { + gensec_gssapi_state->sasl_protection |= NEG_NONE; + } else { + DEBUG(1, ("Remote server does not support unprotected connections")); + return NT_STATUS_ACCESS_DENIED; + } + + /* Send back the negotiated max length */ + + RSIVAL(maxlength_accepted, 0, gensec_gssapi_state->max_wrap_buf_size); + + maxlength_accepted[0] = gensec_gssapi_state->sasl_protection; + + input_token.value = maxlength_accepted; + input_token.length = sizeof(maxlength_accepted); + + maj_stat = gss_wrap(&min_stat, + gensec_gssapi_state->gssapi_context, + false, + GSS_C_QOP_DEFAULT, + &input_token, + &conf_state, + &output_token); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("GSS Update(SSF_NEG): GSS Wrap failed: %s\n", + gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length); + gss_release_buffer(&min_stat, &output_token); + + /* quirk: This changes the value that gensec_have_feature returns, to be that after SASL negotiation */ + gensec_gssapi_state->sasl_state = STAGE_DONE; + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + DEBUG(3, ("SASL/GSSAPI Connection to server will be cryptographicly sealed\n")); + } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + DEBUG(3, ("SASL/GSSAPI Connection to server will be cryptographicly signed\n")); + } else { + DEBUG(3, ("SASL/GSSAPI Connection to server will have no cryptographicly protection\n")); + } + + return NT_STATUS_OK; + } + case GENSEC_SERVER: + { + uint8_t maxlength_proposed[4]; + uint8_t security_supported = 0x0; + int conf_state; + + /* As a server, we have just been sent a zero-length blob (note this, but it isn't fatal) */ + if (in.length != 0) { + DEBUG(1, ("SASL/GSSAPI: client sent non-zero length starting SASL negotiation!\n")); + } + + /* Give the client some idea what we will support */ + + RSIVAL(maxlength_proposed, 0, gensec_gssapi_state->max_wrap_buf_size); + /* first byte is the proposed security */ + maxlength_proposed[0] = '\0'; + + gensec_gssapi_state->sasl_protection = 0; + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + security_supported |= NEG_SEAL; + } + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + security_supported |= NEG_SIGN; + } + if (security_supported == 0) { + /* If we don't support anything, this must be 0 */ + RSIVAL(maxlength_proposed, 0, 0x0); + } + + /* TODO: We may not wish to support this */ + security_supported |= NEG_NONE; + maxlength_proposed[0] = security_supported; + + input_token.value = maxlength_proposed; + input_token.length = sizeof(maxlength_proposed); + + maj_stat = gss_wrap(&min_stat, + gensec_gssapi_state->gssapi_context, + false, + GSS_C_QOP_DEFAULT, + &input_token, + &conf_state, + &output_token); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("GSS Update(SSF_NEG): GSS Wrap failed: %s\n", + gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length); + gss_release_buffer(&min_stat, &output_token); + + gensec_gssapi_state->sasl_state = STAGE_SASL_SSF_ACCEPT; + return NT_STATUS_MORE_PROCESSING_REQUIRED; + } + default: + return NT_STATUS_INVALID_PARAMETER; + + } + } + /* This is s server-only stage */ + case STAGE_SASL_SSF_ACCEPT: + { + uint8_t maxlength_accepted[4]; + uint8_t security_accepted; + int conf_state; + gss_qop_t qop_state; + input_token.length = in.length; + input_token.value = in.data; + + maj_stat = gss_unwrap(&min_stat, + gensec_gssapi_state->gssapi_context, + &input_token, + &output_token, + &conf_state, + &qop_state); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("gensec_gssapi_update: GSS UnWrap of SASL protection negotiation failed: %s\n", + gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + if (output_token.length < 4) { + return NT_STATUS_INVALID_PARAMETER; + } + + memcpy(maxlength_accepted, output_token.value, 4); + gss_release_buffer(&min_stat, &output_token); + + /* first byte is the proposed security */ + security_accepted = maxlength_accepted[0]; + maxlength_accepted[0] = '\0'; + + /* Rest is the proposed max wrap length */ + gensec_gssapi_state->max_wrap_buf_size = MIN(RIVAL(maxlength_accepted, 0), + gensec_gssapi_state->max_wrap_buf_size); + + gensec_gssapi_state->sasl_protection = 0; + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + if (security_accepted & NEG_SEAL) { + gensec_gssapi_state->sasl_protection |= NEG_SEAL; + } + } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + if (security_accepted & NEG_SIGN) { + gensec_gssapi_state->sasl_protection |= NEG_SIGN; + } + } else if (security_accepted & NEG_NONE) { + gensec_gssapi_state->sasl_protection |= NEG_NONE; + } else { + DEBUG(1, ("Remote client does not support unprotected connections, but we failed to negotiate anything better")); + return NT_STATUS_ACCESS_DENIED; + } + + /* quirk: This changes the value that gensec_have_feature returns, to be that after SASL negotiation */ + gensec_gssapi_state->sasl_state = STAGE_DONE; + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + DEBUG(5, ("SASL/GSSAPI Connection from client will be cryptographicly sealed\n")); + } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + DEBUG(5, ("SASL/GSSAPI Connection from client will be cryptographicly signed\n")); + } else { + DEBUG(5, ("SASL/GSSAPI Connection from client will have no cryptographic protection\n")); + } + + *out = data_blob(NULL, 0); + return NT_STATUS_OK; + } + default: + return NT_STATUS_INVALID_PARAMETER; + } +} + +static NTSTATUS gensec_gssapi_wrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + gss_buffer_desc input_token, output_token; + int conf_state; + input_token.length = in->length; + input_token.value = in->data; + + maj_stat = gss_wrap(&min_stat, + gensec_gssapi_state->gssapi_context, + gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL), + GSS_C_QOP_DEFAULT, + &input_token, + &conf_state, + &output_token); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("gensec_gssapi_wrap: GSS Wrap failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + *out = data_blob_talloc(mem_ctx, output_token.value, output_token.length); + gss_release_buffer(&min_stat, &output_token); + + if (gensec_gssapi_state->sasl) { + size_t max_wrapped_size = gensec_gssapi_max_wrapped_size(gensec_security); + if (max_wrapped_size < out->length) { + DEBUG(1, ("gensec_gssapi_wrap: when wrapped, INPUT data (%u) is grew to be larger than SASL negotiated maximum output size (%u > %u)\n", + (unsigned)in->length, + (unsigned)out->length, + (unsigned int)max_wrapped_size)); + return NT_STATUS_INVALID_PARAMETER; + } + } + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL) + && !conf_state) { + return NT_STATUS_ACCESS_DENIED; + } + return NT_STATUS_OK; +} + +static NTSTATUS gensec_gssapi_unwrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + gss_buffer_desc input_token, output_token; + int conf_state; + gss_qop_t qop_state; + input_token.length = in->length; + input_token.value = in->data; + + if (gensec_gssapi_state->sasl) { + size_t max_wrapped_size = gensec_gssapi_max_wrapped_size(gensec_security); + if (max_wrapped_size < in->length) { + DEBUG(1, ("gensec_gssapi_unwrap: WRAPPED data is larger than SASL negotiated maximum size\n")); + return NT_STATUS_INVALID_PARAMETER; + } + } + + maj_stat = gss_unwrap(&min_stat, + gensec_gssapi_state->gssapi_context, + &input_token, + &output_token, + &conf_state, + &qop_state); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("gensec_gssapi_unwrap: GSS UnWrap failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + *out = data_blob_talloc(mem_ctx, output_token.value, output_token.length); + gss_release_buffer(&min_stat, &output_token); + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL) + && !conf_state) { + return NT_STATUS_ACCESS_DENIED; + } + return NT_STATUS_OK; +} + +/* Find out the maximum input size negotiated on this connection */ + +static size_t gensec_gssapi_max_input_size(struct gensec_security *gensec_security) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + OM_uint32 max_input_size; + + maj_stat = gss_wrap_size_limit(&min_stat, + gensec_gssapi_state->gssapi_context, + gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL), + GSS_C_QOP_DEFAULT, + gensec_gssapi_state->max_wrap_buf_size, + &max_input_size); + if (GSS_ERROR(maj_stat)) { + TALLOC_CTX *mem_ctx = talloc_new(NULL); + DEBUG(1, ("gensec_gssapi_max_input_size: determinaing signature size with gss_wrap_size_limit failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + talloc_free(mem_ctx); + return 0; + } + + return max_input_size; +} + +/* Find out the maximum output size negotiated on this connection */ +static size_t gensec_gssapi_max_wrapped_size(struct gensec_security *gensec_security) +{ + struct gensec_gssapi_state *gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);; + return gensec_gssapi_state->max_wrap_buf_size; +} + +static NTSTATUS gensec_gssapi_seal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + gss_buffer_desc input_token, output_token; + int conf_state; + ssize_t sig_length; + + input_token.length = length; + input_token.value = data; + + maj_stat = gss_wrap(&min_stat, + gensec_gssapi_state->gssapi_context, + gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL), + GSS_C_QOP_DEFAULT, + &input_token, + &conf_state, + &output_token); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("gensec_gssapi_seal_packet: GSS Wrap failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + if (output_token.length < input_token.length) { + DEBUG(1, ("gensec_gssapi_seal_packet: GSS Wrap length [%ld] *less* than caller length [%ld]\n", + (long)output_token.length, (long)length)); + return NT_STATUS_INTERNAL_ERROR; + } + sig_length = output_token.length - input_token.length; + + memcpy(data, ((uint8_t *)output_token.value) + sig_length, length); + *sig = data_blob_talloc(mem_ctx, (uint8_t *)output_token.value, sig_length); + + dump_data_pw("gensec_gssapi_seal_packet: sig\n", sig->data, sig->length); + dump_data_pw("gensec_gssapi_seal_packet: clear\n", data, length); + dump_data_pw("gensec_gssapi_seal_packet: sealed\n", ((uint8_t *)output_token.value) + sig_length, output_token.length - sig_length); + + gss_release_buffer(&min_stat, &output_token); + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL) + && !conf_state) { + return NT_STATUS_ACCESS_DENIED; + } + return NT_STATUS_OK; +} + +static NTSTATUS gensec_gssapi_unseal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + gss_buffer_desc input_token, output_token; + int conf_state; + gss_qop_t qop_state; + DATA_BLOB in; + + dump_data_pw("gensec_gssapi_unseal_packet: sig\n", sig->data, sig->length); + + in = data_blob_talloc(mem_ctx, NULL, sig->length + length); + + memcpy(in.data, sig->data, sig->length); + memcpy(in.data + sig->length, data, length); + + input_token.length = in.length; + input_token.value = in.data; + + maj_stat = gss_unwrap(&min_stat, + gensec_gssapi_state->gssapi_context, + &input_token, + &output_token, + &conf_state, + &qop_state); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("gensec_gssapi_unseal_packet: GSS UnWrap failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + if (output_token.length != length) { + return NT_STATUS_INTERNAL_ERROR; + } + + memcpy(data, output_token.value, length); + + gss_release_buffer(&min_stat, &output_token); + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL) + && !conf_state) { + return NT_STATUS_ACCESS_DENIED; + } + return NT_STATUS_OK; +} + +static NTSTATUS gensec_gssapi_sign_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + gss_buffer_desc input_token, output_token; + + if (gensec_security->want_features & GENSEC_FEATURE_SIGN_PKT_HEADER) { + input_token.length = pdu_length; + input_token.value = discard_const_p(uint8_t *, whole_pdu); + } else { + input_token.length = length; + input_token.value = discard_const_p(uint8_t *, data); + } + + maj_stat = gss_get_mic(&min_stat, + gensec_gssapi_state->gssapi_context, + GSS_C_QOP_DEFAULT, + &input_token, + &output_token); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("GSS GetMic failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + *sig = data_blob_talloc(mem_ctx, (uint8_t *)output_token.value, output_token.length); + + dump_data_pw("gensec_gssapi_seal_packet: sig\n", sig->data, sig->length); + + gss_release_buffer(&min_stat, &output_token); + + return NT_STATUS_OK; +} + +static NTSTATUS gensec_gssapi_check_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + gss_buffer_desc input_token; + gss_buffer_desc input_message; + gss_qop_t qop_state; + + dump_data_pw("gensec_gssapi_seal_packet: sig\n", sig->data, sig->length); + + if (gensec_security->want_features & GENSEC_FEATURE_SIGN_PKT_HEADER) { + input_message.length = pdu_length; + input_message.value = discard_const(whole_pdu); + } else { + input_message.length = length; + input_message.value = discard_const(data); + } + + input_token.length = sig->length; + input_token.value = sig->data; + + maj_stat = gss_verify_mic(&min_stat, + gensec_gssapi_state->gssapi_context, + &input_message, + &input_token, + &qop_state); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("GSS VerifyMic failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + + return NT_STATUS_OK; +} + +/* Try to figure out what features we actually got on the connection */ +static bool gensec_gssapi_have_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + if (feature & GENSEC_FEATURE_SIGN) { + /* If we are going GSSAPI SASL, then we honour the second negotiation */ + if (gensec_gssapi_state->sasl + && gensec_gssapi_state->sasl_state == STAGE_DONE) { + return ((gensec_gssapi_state->sasl_protection & NEG_SIGN) + && (gensec_gssapi_state->got_flags & GSS_C_INTEG_FLAG)); + } + return gensec_gssapi_state->got_flags & GSS_C_INTEG_FLAG; + } + if (feature & GENSEC_FEATURE_SEAL) { + /* If we are going GSSAPI SASL, then we honour the second negotiation */ + if (gensec_gssapi_state->sasl + && gensec_gssapi_state->sasl_state == STAGE_DONE) { + return ((gensec_gssapi_state->sasl_protection & NEG_SEAL) + && (gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG)); + } + return gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG; + } + if (feature & GENSEC_FEATURE_SESSION_KEY) { + /* Only for GSSAPI/Krb5 */ + if (gss_oid_equal(gensec_gssapi_state->gss_oid, gss_mech_krb5)) { + return true; + } + } + if (feature & GENSEC_FEATURE_DCE_STYLE) { + return gensec_gssapi_state->got_flags & GSS_C_DCE_STYLE; + } + if (feature & GENSEC_FEATURE_NEW_SPNEGO) { + NTSTATUS status; + + if (!(gensec_gssapi_state->got_flags & GSS_C_INTEG_FLAG)) { + return false; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec_gssapi", "force_new_spnego", false)) { + return true; + } + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec_gssapi", "disable_new_spnego", false)) { + return false; + } + + status = gensec_gssapi_init_lucid(gensec_gssapi_state); + if (!NT_STATUS_IS_OK(status)) { + return false; + } + + if (gensec_gssapi_state->lucid->protocol == 1) { + return true; + } + + return false; + } + /* We can always do async (rather than strict request/reply) packets. */ + if (feature & GENSEC_FEATURE_ASYNC_REPLIES) { + return true; + } + return false; +} + +/* + * Extract the 'sesssion key' needed by SMB signing and ncacn_np + * (for encrypting some passwords). + * + * This breaks all the abstractions, but what do you expect... + */ +static NTSTATUS gensec_gssapi_session_key(struct gensec_security *gensec_security, + DATA_BLOB *session_key) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + OM_uint32 maj_stat, min_stat; + krb5_keyblock *subkey; + + if (gensec_gssapi_state->session_key.data) { + *session_key = gensec_gssapi_state->session_key; + return NT_STATUS_OK; + } + + maj_stat = gsskrb5_get_subkey(&min_stat, + gensec_gssapi_state->gssapi_context, + &subkey); + if (maj_stat != 0) { + DEBUG(1, ("NO session key for this mech\n")); + return NT_STATUS_NO_USER_SESSION_KEY; + } + + DEBUG(10, ("Got KRB5 session key of length %d%s\n", + (int)KRB5_KEY_LENGTH(subkey), + (gensec_gssapi_state->sasl_state == STAGE_DONE)?" (done)":"")); + *session_key = data_blob_talloc(gensec_gssapi_state, + KRB5_KEY_DATA(subkey), KRB5_KEY_LENGTH(subkey)); + krb5_free_keyblock(gensec_gssapi_state->smb_krb5_context->krb5_context, subkey); + if (gensec_gssapi_state->sasl_state == STAGE_DONE) { + /* only cache in the done stage */ + gensec_gssapi_state->session_key = *session_key; + } + dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length); + + return NT_STATUS_OK; +} + +/* Get some basic (and authorization) information about the user on + * this session. This uses either the PAC (if present) or a local + * database lookup */ +static NTSTATUS gensec_gssapi_session_info(struct gensec_security *gensec_security, + struct auth_session_info **_session_info) +{ + NTSTATUS nt_status; + TALLOC_CTX *mem_ctx; + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + struct auth_serversupplied_info *server_info = NULL; + struct auth_session_info *session_info = NULL; + OM_uint32 maj_stat, min_stat; + gss_buffer_desc pac; + DATA_BLOB pac_blob; + + if ((gensec_gssapi_state->gss_oid->length != gss_mech_krb5->length) + || (memcmp(gensec_gssapi_state->gss_oid->elements, gss_mech_krb5->elements, + gensec_gssapi_state->gss_oid->length) != 0)) { + DEBUG(1, ("NO session info available for this mech\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + mem_ctx = talloc_named(gensec_gssapi_state, 0, "gensec_gssapi_session_info context"); + NT_STATUS_HAVE_NO_MEMORY(mem_ctx); + + maj_stat = gsskrb5_extract_authz_data_from_sec_context(&min_stat, + gensec_gssapi_state->gssapi_context, + KRB5_AUTHDATA_WIN2K_PAC, + &pac); + + + if (maj_stat == 0) { + pac_blob = data_blob_talloc(mem_ctx, pac.value, pac.length); + gss_release_buffer(&min_stat, &pac); + + } else { + pac_blob = data_blob(NULL, 0); + } + + /* IF we have the PAC - otherwise we need to get this + * data from elsewere - local ldb, or (TODO) lookup of some + * kind... + */ + if (pac_blob.length) { + nt_status = kerberos_pac_blob_to_server_info(mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + pac_blob, + gensec_gssapi_state->smb_krb5_context->krb5_context, + &server_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + } else { + gss_buffer_desc name_token; + char *principal_string; + + maj_stat = gss_display_name (&min_stat, + gensec_gssapi_state->client_name, + &name_token, + NULL); + if (GSS_ERROR(maj_stat)) { + DEBUG(1, ("GSS display_name failed: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + talloc_free(mem_ctx); + return NT_STATUS_FOOBAR; + } + + principal_string = talloc_strndup(mem_ctx, + (const char *)name_token.value, + name_token.length); + + gss_release_buffer(&min_stat, &name_token); + + if (!principal_string) { + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + if (!lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec", "require_pac", false)) { + DEBUG(1, ("Unable to find PAC, resorting to local user lookup: %s\n", + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + nt_status = sam_get_server_info_principal(mem_ctx, gensec_security->event_ctx, + gensec_security->lp_ctx, principal_string, + &server_info); + + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + } else { + DEBUG(1, ("Unable to find PAC in ticket from %s, failing to allow access: %s\n", + principal_string, + gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid))); + return NT_STATUS_ACCESS_DENIED; + } + } + + /* references the server_info into the session_info */ + nt_status = auth_generate_session_info(mem_ctx, gensec_security->event_ctx, + gensec_security->lp_ctx, server_info, &session_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + nt_status = gensec_gssapi_session_key(gensec_security, &session_info->session_key); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + if (!(gensec_gssapi_state->got_flags & GSS_C_DELEG_FLAG)) { + DEBUG(10, ("gensec_gssapi: NO delegated credentials supplied by client\n")); + } else { + krb5_error_code ret; + DEBUG(10, ("gensec_gssapi: delegated credentials supplied by client\n")); + session_info->credentials = cli_credentials_init(session_info); + if (!session_info->credentials) { + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + cli_credentials_set_conf(session_info->credentials, gensec_security->lp_ctx); + /* Just so we don't segfault trying to get at a username */ + cli_credentials_set_anonymous(session_info->credentials); + + ret = cli_credentials_set_client_gss_creds(session_info->credentials, + gensec_security->event_ctx, + gensec_security->lp_ctx, + gensec_gssapi_state->delegated_cred_handle, + CRED_SPECIFIED); + if (ret) { + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + /* This credential handle isn't useful for password authentication, so ensure nobody tries to do that */ + cli_credentials_set_kerberos_state(session_info->credentials, CRED_MUST_USE_KERBEROS); + + /* It has been taken from this place... */ + gensec_gssapi_state->delegated_cred_handle = GSS_C_NO_CREDENTIAL; + } + talloc_steal(gensec_gssapi_state, session_info); + talloc_free(mem_ctx); + *_session_info = session_info; + + return NT_STATUS_OK; +} + +size_t gensec_gssapi_sig_size(struct gensec_security *gensec_security, size_t data_size) +{ + struct gensec_gssapi_state *gensec_gssapi_state + = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state); + NTSTATUS status; + + if (gensec_gssapi_state->sig_size) { + return gensec_gssapi_state->sig_size; + } + + if (gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG) { + gensec_gssapi_state->sig_size = 45; + } else { + gensec_gssapi_state->sig_size = 37; + } + + status = gensec_gssapi_init_lucid(gensec_gssapi_state); + if (!NT_STATUS_IS_OK(status)) { + return gensec_gssapi_state->sig_size; + } + + if (gensec_gssapi_state->lucid->protocol == 1) { + if (gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG) { + /* + * TODO: windows uses 76 here, but we don't know + * gss_wrap works with aes keys yet + */ + gensec_gssapi_state->sig_size = 76; + } else { + gensec_gssapi_state->sig_size = 28; + } + } else if (gensec_gssapi_state->lucid->protocol == 0) { + switch (gensec_gssapi_state->lucid->rfc1964_kd.ctx_key.type) { + case KEYTYPE_DES: + case KEYTYPE_ARCFOUR: + case KEYTYPE_ARCFOUR_56: + if (gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG) { + gensec_gssapi_state->sig_size = 45; + } else { + gensec_gssapi_state->sig_size = 37; + } + break; + case KEYTYPE_DES3: + if (gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG) { + gensec_gssapi_state->sig_size = 57; + } else { + gensec_gssapi_state->sig_size = 49; + } + break; + } + } + + return gensec_gssapi_state->sig_size; +} + +static const char *gensec_gssapi_krb5_oids[] = { + GENSEC_OID_KERBEROS5_OLD, + GENSEC_OID_KERBEROS5, + NULL +}; + +static const char *gensec_gssapi_spnego_oids[] = { + GENSEC_OID_SPNEGO, + NULL +}; + +/* As a server, this could in theory accept any GSSAPI mech */ +static const struct gensec_security_ops gensec_gssapi_spnego_security_ops = { + .name = "gssapi_spnego", + .sasl_name = "GSS-SPNEGO", + .auth_type = DCERPC_AUTH_TYPE_SPNEGO, + .oid = gensec_gssapi_spnego_oids, + .client_start = gensec_gssapi_client_start, + .server_start = gensec_gssapi_server_start, + .magic = gensec_gssapi_magic, + .update = gensec_gssapi_update, + .session_key = gensec_gssapi_session_key, + .session_info = gensec_gssapi_session_info, + .sign_packet = gensec_gssapi_sign_packet, + .check_packet = gensec_gssapi_check_packet, + .seal_packet = gensec_gssapi_seal_packet, + .unseal_packet = gensec_gssapi_unseal_packet, + .wrap = gensec_gssapi_wrap, + .unwrap = gensec_gssapi_unwrap, + .have_feature = gensec_gssapi_have_feature, + .enabled = false, + .kerberos = true, + .priority = GENSEC_GSSAPI +}; + +/* As a server, this could in theory accept any GSSAPI mech */ +static const struct gensec_security_ops gensec_gssapi_krb5_security_ops = { + .name = "gssapi_krb5", + .auth_type = DCERPC_AUTH_TYPE_KRB5, + .oid = gensec_gssapi_krb5_oids, + .client_start = gensec_gssapi_client_start, + .server_start = gensec_gssapi_server_start, + .magic = gensec_gssapi_magic, + .update = gensec_gssapi_update, + .session_key = gensec_gssapi_session_key, + .session_info = gensec_gssapi_session_info, + .sig_size = gensec_gssapi_sig_size, + .sign_packet = gensec_gssapi_sign_packet, + .check_packet = gensec_gssapi_check_packet, + .seal_packet = gensec_gssapi_seal_packet, + .unseal_packet = gensec_gssapi_unseal_packet, + .wrap = gensec_gssapi_wrap, + .unwrap = gensec_gssapi_unwrap, + .have_feature = gensec_gssapi_have_feature, + .enabled = true, + .kerberos = true, + .priority = GENSEC_GSSAPI +}; + +/* As a server, this could in theory accept any GSSAPI mech */ +static const struct gensec_security_ops gensec_gssapi_sasl_krb5_security_ops = { + .name = "gssapi_krb5_sasl", + .sasl_name = "GSSAPI", + .client_start = gensec_gssapi_sasl_client_start, + .server_start = gensec_gssapi_sasl_server_start, + .update = gensec_gssapi_update, + .session_key = gensec_gssapi_session_key, + .session_info = gensec_gssapi_session_info, + .max_input_size = gensec_gssapi_max_input_size, + .max_wrapped_size = gensec_gssapi_max_wrapped_size, + .wrap = gensec_gssapi_wrap, + .unwrap = gensec_gssapi_unwrap, + .have_feature = gensec_gssapi_have_feature, + .enabled = true, + .kerberos = true, + .priority = GENSEC_GSSAPI +}; + +_PUBLIC_ NTSTATUS gensec_gssapi_init(void) +{ + NTSTATUS ret; + + ret = gensec_register(&gensec_gssapi_spnego_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_gssapi_spnego_security_ops.name)); + return ret; + } + + ret = gensec_register(&gensec_gssapi_krb5_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_gssapi_krb5_security_ops.name)); + return ret; + } + + ret = gensec_register(&gensec_gssapi_sasl_krb5_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_gssapi_sasl_krb5_security_ops.name)); + return ret; + } + + return ret; +} diff --git a/source4/auth/gensec/gensec_gssapi.h b/source4/auth/gensec/gensec_gssapi.h new file mode 100644 index 0000000000..b55b4391e0 --- /dev/null +++ b/source4/auth/gensec/gensec_gssapi.h @@ -0,0 +1,68 @@ +/* + Unix SMB/CIFS implementation. + + Kerberos backend for GENSEC + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + Copyright (C) Stefan Metzmacher <metze@samba.org> 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +/* This structure described here, so the RPC-PAC test can get at the PAC provided */ + +enum gensec_gssapi_sasl_state +{ + STAGE_GSS_NEG, + STAGE_SASL_SSF_NEG, + STAGE_SASL_SSF_ACCEPT, + STAGE_DONE +}; + +#define NEG_SEAL 0x4 +#define NEG_SIGN 0x2 +#define NEG_NONE 0x1 + +struct gensec_gssapi_state { + gss_ctx_id_t gssapi_context; + struct gss_channel_bindings_struct *input_chan_bindings; + gss_name_t server_name; + gss_name_t client_name; + OM_uint32 want_flags, got_flags; + gss_OID gss_oid; + + DATA_BLOB session_key; + DATA_BLOB pac; + + struct smb_krb5_context *smb_krb5_context; + struct gssapi_creds_container *client_cred; + struct gssapi_creds_container *server_cred; + gss_krb5_lucid_context_v1_t *lucid; + + gss_cred_id_t delegated_cred_handle; + + bool sasl; /* We have two different mechs in this file: One + * for SASL wrapped GSSAPI and another for normal + * GSSAPI */ + enum gensec_gssapi_sasl_state sasl_state; + uint8_t sasl_protection; /* What was negotiated at the SASL + * layer, independent of the GSSAPI + * layer... */ + + size_t max_wrap_buf_size; + int gss_exchange_count; + size_t sig_size; +}; + diff --git a/source4/auth/gensec/gensec_krb5.c b/source4/auth/gensec/gensec_krb5.c new file mode 100644 index 0000000000..47df2ccfcc --- /dev/null +++ b/source4/auth/gensec/gensec_krb5.c @@ -0,0 +1,809 @@ +/* + Unix SMB/CIFS implementation. + + Kerberos backend for GENSEC + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004 + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Luke Howard 2002-2003 + Copyright (C) Stefan Metzmacher 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/kerberos.h" +#include "auth/kerberos/kerberos.h" +#include "librpc/gen_ndr/krb5pac.h" +#include "auth/auth.h" +#include "lib/ldb/include/ldb.h" +#include "auth/auth_sam.h" +#include "system/network.h" +#include "lib/socket/socket.h" +#include "librpc/rpc/dcerpc.h" +#include "auth/credentials/credentials.h" +#include "auth/credentials/credentials_krb5.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" +#include "param/param.h" +#include "auth/session_proto.h" + +enum GENSEC_KRB5_STATE { + GENSEC_KRB5_SERVER_START, + GENSEC_KRB5_CLIENT_START, + GENSEC_KRB5_CLIENT_MUTUAL_AUTH, + GENSEC_KRB5_DONE +}; + +struct gensec_krb5_state { + DATA_BLOB session_key; + DATA_BLOB pac; + enum GENSEC_KRB5_STATE state_position; + struct smb_krb5_context *smb_krb5_context; + krb5_auth_context auth_context; + krb5_data enc_ticket; + krb5_keyblock *keyblock; + krb5_ticket *ticket; + bool gssapi; +}; + +static int gensec_krb5_destroy(struct gensec_krb5_state *gensec_krb5_state) +{ + if (!gensec_krb5_state->smb_krb5_context) { + /* We can't clean anything else up unless we started up this far */ + return 0; + } + if (gensec_krb5_state->enc_ticket.length) { + kerberos_free_data_contents(gensec_krb5_state->smb_krb5_context->krb5_context, + &gensec_krb5_state->enc_ticket); + } + + if (gensec_krb5_state->ticket) { + krb5_free_ticket(gensec_krb5_state->smb_krb5_context->krb5_context, + gensec_krb5_state->ticket); + } + + /* ccache freed in a child destructor */ + + krb5_free_keyblock(gensec_krb5_state->smb_krb5_context->krb5_context, + gensec_krb5_state->keyblock); + + if (gensec_krb5_state->auth_context) { + krb5_auth_con_free(gensec_krb5_state->smb_krb5_context->krb5_context, + gensec_krb5_state->auth_context); + } + + return 0; +} + +static NTSTATUS gensec_krb5_start(struct gensec_security *gensec_security) +{ + krb5_error_code ret; + struct gensec_krb5_state *gensec_krb5_state; + struct cli_credentials *creds; + const struct socket_address *my_addr, *peer_addr; + krb5_address my_krb5_addr, peer_krb5_addr; + + creds = gensec_get_credentials(gensec_security); + if (!creds) { + return NT_STATUS_INVALID_PARAMETER; + } + + gensec_krb5_state = talloc(gensec_security, struct gensec_krb5_state); + if (!gensec_krb5_state) { + return NT_STATUS_NO_MEMORY; + } + + gensec_security->private_data = gensec_krb5_state; + gensec_krb5_state->smb_krb5_context = NULL; + gensec_krb5_state->auth_context = NULL; + gensec_krb5_state->ticket = NULL; + ZERO_STRUCT(gensec_krb5_state->enc_ticket); + gensec_krb5_state->keyblock = NULL; + gensec_krb5_state->session_key = data_blob(NULL, 0); + gensec_krb5_state->pac = data_blob(NULL, 0); + gensec_krb5_state->gssapi = false; + + talloc_set_destructor(gensec_krb5_state, gensec_krb5_destroy); + + if (cli_credentials_get_krb5_context(creds, + gensec_security->event_ctx, + gensec_security->lp_ctx, &gensec_krb5_state->smb_krb5_context)) { + talloc_free(gensec_krb5_state); + return NT_STATUS_INTERNAL_ERROR; + } + + ret = krb5_auth_con_init(gensec_krb5_state->smb_krb5_context->krb5_context, &gensec_krb5_state->auth_context); + if (ret) { + DEBUG(1,("gensec_krb5_start: krb5_auth_con_init failed (%s)\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, + ret, gensec_krb5_state))); + talloc_free(gensec_krb5_state); + return NT_STATUS_INTERNAL_ERROR; + } + + ret = krb5_auth_con_setflags(gensec_krb5_state->smb_krb5_context->krb5_context, + gensec_krb5_state->auth_context, + KRB5_AUTH_CONTEXT_DO_SEQUENCE); + if (ret) { + DEBUG(1,("gensec_krb5_start: krb5_auth_con_setflags failed (%s)\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, + ret, gensec_krb5_state))); + talloc_free(gensec_krb5_state); + return NT_STATUS_INTERNAL_ERROR; + } + + my_addr = gensec_get_my_addr(gensec_security); + if (my_addr && my_addr->sockaddr) { + ret = krb5_sockaddr2address(gensec_krb5_state->smb_krb5_context->krb5_context, + my_addr->sockaddr, &my_krb5_addr); + if (ret) { + DEBUG(1,("gensec_krb5_start: krb5_sockaddr2address (local) failed (%s)\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, + ret, gensec_krb5_state))); + talloc_free(gensec_krb5_state); + return NT_STATUS_INTERNAL_ERROR; + } + } + + peer_addr = gensec_get_peer_addr(gensec_security); + if (peer_addr && peer_addr->sockaddr) { + ret = krb5_sockaddr2address(gensec_krb5_state->smb_krb5_context->krb5_context, + peer_addr->sockaddr, &peer_krb5_addr); + if (ret) { + DEBUG(1,("gensec_krb5_start: krb5_sockaddr2address (local) failed (%s)\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, + ret, gensec_krb5_state))); + talloc_free(gensec_krb5_state); + return NT_STATUS_INTERNAL_ERROR; + } + } + + ret = krb5_auth_con_setaddrs(gensec_krb5_state->smb_krb5_context->krb5_context, + gensec_krb5_state->auth_context, + my_addr ? &my_krb5_addr : NULL, + peer_addr ? &peer_krb5_addr : NULL); + if (ret) { + DEBUG(1,("gensec_krb5_start: krb5_auth_con_setaddrs failed (%s)\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, + ret, gensec_krb5_state))); + talloc_free(gensec_krb5_state); + return NT_STATUS_INTERNAL_ERROR; + } + + return NT_STATUS_OK; +} + +static NTSTATUS gensec_krb5_server_start(struct gensec_security *gensec_security) +{ + NTSTATUS nt_status; + struct gensec_krb5_state *gensec_krb5_state; + + nt_status = gensec_krb5_start(gensec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + gensec_krb5_state->state_position = GENSEC_KRB5_SERVER_START; + + return NT_STATUS_OK; +} + +static NTSTATUS gensec_fake_gssapi_krb5_server_start(struct gensec_security *gensec_security) +{ + NTSTATUS nt_status = gensec_krb5_server_start(gensec_security); + + if (NT_STATUS_IS_OK(nt_status)) { + struct gensec_krb5_state *gensec_krb5_state; + gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + gensec_krb5_state->gssapi = true; + } + return nt_status; +} + +static NTSTATUS gensec_krb5_client_start(struct gensec_security *gensec_security) +{ + struct gensec_krb5_state *gensec_krb5_state; + krb5_error_code ret; + NTSTATUS nt_status; + struct ccache_container *ccache_container; + const char *hostname; + krb5_flags ap_req_options = AP_OPTS_USE_SUBKEY | AP_OPTS_MUTUAL_REQUIRED; + + const char *principal; + krb5_data in_data; + + hostname = gensec_get_target_hostname(gensec_security); + if (!hostname) { + DEBUG(1, ("Could not determine hostname for target computer, cannot use kerberos\n")); + return NT_STATUS_INVALID_PARAMETER; + } + if (is_ipaddress(hostname)) { + DEBUG(2, ("Cannot do krb5 to an IP address")); + return NT_STATUS_INVALID_PARAMETER; + } + if (strcmp(hostname, "localhost") == 0) { + DEBUG(2, ("krb5 to 'localhost' does not make sense")); + return NT_STATUS_INVALID_PARAMETER; + } + + nt_status = gensec_krb5_start(gensec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + gensec_krb5_state->state_position = GENSEC_KRB5_CLIENT_START; + + principal = gensec_get_target_principal(gensec_security); + + ret = cli_credentials_get_ccache(gensec_get_credentials(gensec_security), + gensec_security->event_ctx, + gensec_security->lp_ctx, &ccache_container); + switch (ret) { + case 0: + break; + case KRB5KDC_ERR_PREAUTH_FAILED: + return NT_STATUS_LOGON_FAILURE; + case KRB5_KDC_UNREACH: + DEBUG(3, ("Cannot reach a KDC we require to contact %s\n", principal)); + return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */ + default: + DEBUG(1, ("gensec_krb5_start: Aquiring initiator credentials failed: %s\n", error_message(ret))); + return NT_STATUS_UNSUCCESSFUL; + } + in_data.length = 0; + + if (principal && lp_client_use_spnego_principal(gensec_security->lp_ctx)) { + krb5_principal target_principal; + ret = krb5_parse_name(gensec_krb5_state->smb_krb5_context->krb5_context, principal, + &target_principal); + if (ret == 0) { + ret = krb5_mk_req_exact(gensec_krb5_state->smb_krb5_context->krb5_context, + &gensec_krb5_state->auth_context, + ap_req_options, + target_principal, + &in_data, ccache_container->ccache, + &gensec_krb5_state->enc_ticket); + krb5_free_principal(gensec_krb5_state->smb_krb5_context->krb5_context, + target_principal); + } + } else { + ret = krb5_mk_req(gensec_krb5_state->smb_krb5_context->krb5_context, + &gensec_krb5_state->auth_context, + ap_req_options, + gensec_get_target_service(gensec_security), + hostname, + &in_data, ccache_container->ccache, + &gensec_krb5_state->enc_ticket); + } + switch (ret) { + case 0: + return NT_STATUS_OK; + case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN: + DEBUG(3, ("Server [%s] is not registered with our KDC: %s\n", + hostname, smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state))); + return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */ + case KRB5_KDC_UNREACH: + DEBUG(3, ("Cannot reach a KDC we require to contact host [%s]: %s\n", + hostname, smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state))); + return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */ + case KRB5KDC_ERR_PREAUTH_FAILED: + case KRB5KRB_AP_ERR_TKT_EXPIRED: + case KRB5_CC_END: + /* Too much clock skew - we will need to kinit to re-skew the clock */ + case KRB5KRB_AP_ERR_SKEW: + case KRB5_KDCREP_SKEW: + { + DEBUG(3, ("kerberos (mk_req) failed: %s\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state))); + /*fall through*/ + } + + /* just don't print a message for these really ordinary messages */ + case KRB5_FCC_NOFILE: + case KRB5_CC_NOTFOUND: + case ENOENT: + + return NT_STATUS_UNSUCCESSFUL; + break; + + default: + DEBUG(0, ("kerberos: %s\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state))); + return NT_STATUS_UNSUCCESSFUL; + } +} + +static NTSTATUS gensec_fake_gssapi_krb5_client_start(struct gensec_security *gensec_security) +{ + NTSTATUS nt_status = gensec_krb5_client_start(gensec_security); + + if (NT_STATUS_IS_OK(nt_status)) { + struct gensec_krb5_state *gensec_krb5_state; + gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + gensec_krb5_state->gssapi = true; + } + return nt_status; +} + +/** + * Check if the packet is one for this mechansim + * + * @param gensec_security GENSEC state + * @param in The request, as a DATA_BLOB + * @return Error, INVALID_PARAMETER if it's not a packet for us + * or NT_STATUS_OK if the packet is ok. + */ + +static NTSTATUS gensec_fake_gssapi_krb5_magic(struct gensec_security *gensec_security, + const DATA_BLOB *in) +{ + if (gensec_gssapi_check_oid(in, GENSEC_OID_KERBEROS5)) { + return NT_STATUS_OK; + } else { + return NT_STATUS_INVALID_PARAMETER; + } +} + + +/** + * Next state function for the Krb5 GENSEC mechanism + * + * @param gensec_krb5_state KRB5 State + * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on + * @param in The request, as a DATA_BLOB + * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx + * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, + * or NT_STATUS_OK if the user is authenticated. + */ + +static NTSTATUS gensec_krb5_update(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + krb5_error_code ret = 0; + NTSTATUS nt_status; + + switch (gensec_krb5_state->state_position) { + case GENSEC_KRB5_CLIENT_START: + { + DATA_BLOB unwrapped_out; + + if (gensec_krb5_state->gssapi) { + unwrapped_out = data_blob_talloc(out_mem_ctx, gensec_krb5_state->enc_ticket.data, gensec_krb5_state->enc_ticket.length); + + /* wrap that up in a nice GSS-API wrapping */ + *out = gensec_gssapi_gen_krb5_wrap(out_mem_ctx, &unwrapped_out, TOK_ID_KRB_AP_REQ); + } else { + *out = data_blob_talloc(out_mem_ctx, gensec_krb5_state->enc_ticket.data, gensec_krb5_state->enc_ticket.length); + } + gensec_krb5_state->state_position = GENSEC_KRB5_CLIENT_MUTUAL_AUTH; + nt_status = NT_STATUS_MORE_PROCESSING_REQUIRED; + return nt_status; + } + + case GENSEC_KRB5_CLIENT_MUTUAL_AUTH: + { + DATA_BLOB unwrapped_in; + krb5_data inbuf; + krb5_ap_rep_enc_part *repl = NULL; + uint8_t tok_id[2]; + + if (gensec_krb5_state->gssapi) { + if (!gensec_gssapi_parse_krb5_wrap(out_mem_ctx, &in, &unwrapped_in, tok_id)) { + DEBUG(1,("gensec_gssapi_parse_krb5_wrap(mutual authentication) failed to parse\n")); + dump_data_pw("Mutual authentication message:\n", in.data, in.length); + return NT_STATUS_INVALID_PARAMETER; + } + } else { + unwrapped_in = in; + } + /* TODO: check the tok_id */ + + inbuf.data = unwrapped_in.data; + inbuf.length = unwrapped_in.length; + ret = krb5_rd_rep(gensec_krb5_state->smb_krb5_context->krb5_context, + gensec_krb5_state->auth_context, + &inbuf, &repl); + if (ret) { + DEBUG(1,("krb5_rd_rep (mutual authentication) failed (%s)\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, out_mem_ctx))); + dump_data_pw("Mutual authentication message:\n", (uint8_t *)inbuf.data, inbuf.length); + nt_status = NT_STATUS_ACCESS_DENIED; + } else { + *out = data_blob(NULL, 0); + nt_status = NT_STATUS_OK; + gensec_krb5_state->state_position = GENSEC_KRB5_DONE; + } + if (repl) { + krb5_free_ap_rep_enc_part(gensec_krb5_state->smb_krb5_context->krb5_context, repl); + } + return nt_status; + } + + case GENSEC_KRB5_SERVER_START: + { + DATA_BLOB unwrapped_in; + DATA_BLOB unwrapped_out = data_blob(NULL, 0); + krb5_data inbuf, outbuf; + uint8_t tok_id[2]; + struct keytab_container *keytab; + krb5_principal server_in_keytab; + + if (!in.data) { + return NT_STATUS_INVALID_PARAMETER; + } + + /* Grab the keytab, however generated */ + ret = cli_credentials_get_keytab(gensec_get_credentials(gensec_security), + gensec_security->event_ctx, + gensec_security->lp_ctx, &keytab); + if (ret) { + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + + /* This ensures we lookup the correct entry in that keytab */ + ret = principal_from_credentials(out_mem_ctx, gensec_get_credentials(gensec_security), + gensec_krb5_state->smb_krb5_context, + &server_in_keytab); + + if (ret) { + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + + /* Parse the GSSAPI wrapping, if it's there... (win2k3 allows it to be omited) */ + if (gensec_krb5_state->gssapi + && gensec_gssapi_parse_krb5_wrap(out_mem_ctx, &in, &unwrapped_in, tok_id)) { + inbuf.data = unwrapped_in.data; + inbuf.length = unwrapped_in.length; + } else { + inbuf.data = in.data; + inbuf.length = in.length; + } + + ret = smb_rd_req_return_stuff(gensec_krb5_state->smb_krb5_context->krb5_context, + &gensec_krb5_state->auth_context, + &inbuf, keytab->keytab, server_in_keytab, + &outbuf, + &gensec_krb5_state->ticket, + &gensec_krb5_state->keyblock); + + if (ret) { + return NT_STATUS_LOGON_FAILURE; + } + unwrapped_out.data = (uint8_t *)outbuf.data; + unwrapped_out.length = outbuf.length; + gensec_krb5_state->state_position = GENSEC_KRB5_DONE; + /* wrap that up in a nice GSS-API wrapping */ + if (gensec_krb5_state->gssapi) { + *out = gensec_gssapi_gen_krb5_wrap(out_mem_ctx, &unwrapped_out, TOK_ID_KRB_AP_REP); + } else { + *out = data_blob_talloc(out_mem_ctx, outbuf.data, outbuf.length); + } + krb5_data_free(&outbuf); + return NT_STATUS_OK; + } + + case GENSEC_KRB5_DONE: + default: + /* Asking too many times... */ + return NT_STATUS_INVALID_PARAMETER; + } +} + +static NTSTATUS gensec_krb5_session_key(struct gensec_security *gensec_security, + DATA_BLOB *session_key) +{ + struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context; + krb5_auth_context auth_context = gensec_krb5_state->auth_context; + krb5_keyblock *skey; + krb5_error_code err = -1; + + if (gensec_krb5_state->session_key.data) { + *session_key = gensec_krb5_state->session_key; + return NT_STATUS_OK; + } + + switch (gensec_security->gensec_role) { + case GENSEC_CLIENT: + err = krb5_auth_con_getlocalsubkey(context, auth_context, &skey); + break; + case GENSEC_SERVER: + err = krb5_auth_con_getremotesubkey(context, auth_context, &skey); + break; + } + if (err == 0 && skey != NULL) { + DEBUG(10, ("Got KRB5 session key of length %d\n", + (int)KRB5_KEY_LENGTH(skey))); + gensec_krb5_state->session_key = data_blob_talloc(gensec_krb5_state, + KRB5_KEY_DATA(skey), KRB5_KEY_LENGTH(skey)); + *session_key = gensec_krb5_state->session_key; + dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length); + + krb5_free_keyblock(context, skey); + return NT_STATUS_OK; + } else { + DEBUG(10, ("KRB5 error getting session key %d\n", err)); + return NT_STATUS_NO_USER_SESSION_KEY; + } +} + +static NTSTATUS gensec_krb5_session_info(struct gensec_security *gensec_security, + struct auth_session_info **_session_info) +{ + NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL; + struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context; + struct auth_serversupplied_info *server_info = NULL; + struct auth_session_info *session_info = NULL; + struct PAC_LOGON_INFO *logon_info; + + krb5_principal client_principal; + char *principal_string; + + DATA_BLOB pac; + krb5_data pac_data; + + krb5_error_code ret; + + TALLOC_CTX *mem_ctx = talloc_new(gensec_security); + if (!mem_ctx) { + return NT_STATUS_NO_MEMORY; + } + + ret = krb5_ticket_get_client(context, gensec_krb5_state->ticket, &client_principal); + if (ret) { + DEBUG(5, ("krb5_ticket_get_client failed to get cleint principal: %s\n", + smb_get_krb5_error_message(context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + ret = krb5_unparse_name(gensec_krb5_state->smb_krb5_context->krb5_context, + client_principal, &principal_string); + if (ret) { + DEBUG(1, ("Unable to parse client principal: %s\n", + smb_get_krb5_error_message(context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + ret = krb5_ticket_get_authorization_data_type(context, gensec_krb5_state->ticket, + KRB5_AUTHDATA_WIN2K_PAC, + &pac_data); + + if (ret && lp_parm_bool(gensec_security->lp_ctx, NULL, "gensec", "require_pac", false)) { + DEBUG(1, ("Unable to find PAC in ticket from %s, failing to allow access: %s \n", + principal_string, + smb_get_krb5_error_message(context, + ret, mem_ctx))); + krb5_free_principal(context, client_principal); + free(principal_string); + return NT_STATUS_ACCESS_DENIED; + } else if (ret) { + /* NO pac */ + DEBUG(5, ("krb5_ticket_get_authorization_data_type failed to find PAC: %s\n", + smb_get_krb5_error_message(context, + ret, mem_ctx))); + nt_status = sam_get_server_info_principal(mem_ctx, gensec_security->event_ctx, gensec_security->lp_ctx, principal_string, + &server_info); + krb5_free_principal(context, client_principal); + free(principal_string); + + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + } else { + /* Found pac */ + union netr_Validation validation; + free(principal_string); + + pac = data_blob_talloc(mem_ctx, pac_data.data, pac_data.length); + if (!pac.data) { + krb5_free_principal(context, client_principal); + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + /* decode and verify the pac */ + nt_status = kerberos_pac_logon_info(gensec_krb5_state, + lp_iconv_convenience(gensec_security->lp_ctx), + &logon_info, pac, + gensec_krb5_state->smb_krb5_context->krb5_context, + NULL, gensec_krb5_state->keyblock, + client_principal, + gensec_krb5_state->ticket->ticket.authtime, NULL); + krb5_free_principal(context, client_principal); + + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + validation.sam3 = &logon_info->info3; + nt_status = make_server_info_netlogon_validation(mem_ctx, + NULL, + 3, &validation, + &server_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + } + + /* references the server_info into the session_info */ + nt_status = auth_generate_session_info(mem_ctx, gensec_security->event_ctx, gensec_security->lp_ctx, server_info, &session_info); + + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + nt_status = gensec_krb5_session_key(gensec_security, &session_info->session_key); + + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + *_session_info = session_info; + + talloc_steal(gensec_krb5_state, session_info); + talloc_free(mem_ctx); + return NT_STATUS_OK; +} + +static NTSTATUS gensec_krb5_wrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context; + krb5_auth_context auth_context = gensec_krb5_state->auth_context; + krb5_error_code ret; + krb5_data input, output; + input.length = in->length; + input.data = in->data; + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + ret = krb5_mk_priv(context, auth_context, &input, &output, NULL); + if (ret) { + DEBUG(1, ("krb5_mk_priv failed: %s\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, + ret, mem_ctx))); + return NT_STATUS_ACCESS_DENIED; + } + *out = data_blob_talloc(mem_ctx, output.data, output.length); + + krb5_data_free(&output); + } else { + return NT_STATUS_ACCESS_DENIED; + } + return NT_STATUS_OK; +} + +static NTSTATUS gensec_krb5_unwrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context; + krb5_auth_context auth_context = gensec_krb5_state->auth_context; + krb5_error_code ret; + krb5_data input, output; + krb5_replay_data replay; + input.length = in->length; + input.data = in->data; + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + ret = krb5_rd_priv(context, auth_context, &input, &output, &replay); + if (ret) { + DEBUG(1, ("krb5_rd_priv failed: %s\n", + smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, + ret, mem_ctx))); + return NT_STATUS_ACCESS_DENIED; + } + *out = data_blob_talloc(mem_ctx, output.data, output.length); + + krb5_data_free(&output); + } else { + return NT_STATUS_ACCESS_DENIED; + } + return NT_STATUS_OK; +} + +static bool gensec_krb5_have_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data; + if (feature & GENSEC_FEATURE_SESSION_KEY) { + return true; + } + if (!gensec_krb5_state->gssapi && + (feature & GENSEC_FEATURE_SEAL)) { + return true; + } + + return false; +} + +static const char *gensec_krb5_oids[] = { + GENSEC_OID_KERBEROS5, + GENSEC_OID_KERBEROS5_OLD, + NULL +}; + +static const struct gensec_security_ops gensec_fake_gssapi_krb5_security_ops = { + .name = "fake_gssapi_krb5", + .auth_type = DCERPC_AUTH_TYPE_KRB5, + .oid = gensec_krb5_oids, + .client_start = gensec_fake_gssapi_krb5_client_start, + .server_start = gensec_fake_gssapi_krb5_server_start, + .update = gensec_krb5_update, + .magic = gensec_fake_gssapi_krb5_magic, + .session_key = gensec_krb5_session_key, + .session_info = gensec_krb5_session_info, + .have_feature = gensec_krb5_have_feature, + .enabled = false, + .kerberos = true, + .priority = GENSEC_KRB5 +}; + +static const struct gensec_security_ops gensec_krb5_security_ops = { + .name = "krb5", + .client_start = gensec_krb5_client_start, + .server_start = gensec_krb5_server_start, + .update = gensec_krb5_update, + .session_key = gensec_krb5_session_key, + .session_info = gensec_krb5_session_info, + .have_feature = gensec_krb5_have_feature, + .wrap = gensec_krb5_wrap, + .unwrap = gensec_krb5_unwrap, + .enabled = true, + .kerberos = true, + .priority = GENSEC_KRB5 +}; + +_PUBLIC_ NTSTATUS gensec_krb5_init(void) +{ + NTSTATUS ret; + + auth_init(); + + ret = gensec_register(&gensec_krb5_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_krb5_security_ops.name)); + return ret; + } + + ret = gensec_register(&gensec_fake_gssapi_krb5_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_krb5_security_ops.name)); + return ret; + } + + return ret; +} diff --git a/source4/auth/gensec/schannel.c b/source4/auth/gensec/schannel.c new file mode 100644 index 0000000000..f21202b86f --- /dev/null +++ b/source4/auth/gensec/schannel.c @@ -0,0 +1,291 @@ +/* + Unix SMB/CIFS implementation. + + dcerpc schannel operations + + Copyright (C) Andrew Tridgell 2004 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "librpc/gen_ndr/ndr_schannel.h" +#include "auth/auth.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" +#include "auth/gensec/schannel.h" +#include "auth/gensec/schannel_state.h" +#include "auth/gensec/schannel_proto.h" +#include "librpc/rpc/dcerpc.h" +#include "param/param.h" +#include "auth/session_proto.h" + +static size_t schannel_sig_size(struct gensec_security *gensec_security, size_t data_size) +{ + return 32; +} + +static NTSTATUS schannel_session_key(struct gensec_security *gensec_security, + DATA_BLOB *session_key) +{ + return NT_STATUS_NOT_IMPLEMENTED; +} + +static NTSTATUS schannel_update(struct gensec_security *gensec_security, TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct schannel_state *state = (struct schannel_state *)gensec_security->private_data; + NTSTATUS status; + enum ndr_err_code ndr_err; + struct schannel_bind bind_schannel; + struct schannel_bind_ack bind_schannel_ack; + struct creds_CredentialState *creds; + + const char *workstation; + const char *domain; + *out = data_blob(NULL, 0); + + switch (gensec_security->gensec_role) { + case GENSEC_CLIENT: + if (state->state != SCHANNEL_STATE_START) { + /* we could parse the bind ack, but we don't know what it is yet */ + return NT_STATUS_OK; + } + + state->creds = talloc_reference(state, cli_credentials_get_netlogon_creds(gensec_security->credentials)); + + bind_schannel.unknown1 = 0; +#if 0 + /* to support this we'd need to have access to the full domain name */ + bind_schannel.bind_type = 23; + bind_schannel.u.info23.domain = cli_credentials_get_domain(gensec_security->credentials); + bind_schannel.u.info23.workstation = cli_credentials_get_workstation(gensec_security->credentials); + bind_schannel.u.info23.dnsdomain = cli_credentials_get_realm(gensec_security->credentials); + /* w2k3 refuses us if we use the full DNS workstation? + why? perhaps because we don't fill in the dNSHostName + attribute in the machine account? */ + bind_schannel.u.info23.dnsworkstation = cli_credentials_get_workstation(gensec_security->credentials); +#else + bind_schannel.bind_type = 3; + bind_schannel.u.info3.domain = cli_credentials_get_domain(gensec_security->credentials); + bind_schannel.u.info3.workstation = cli_credentials_get_workstation(gensec_security->credentials); +#endif + + ndr_err = ndr_push_struct_blob(out, out_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), &bind_schannel, + (ndr_push_flags_fn_t)ndr_push_schannel_bind); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(3, ("Could not create schannel bind: %s\n", + nt_errstr(status))); + return status; + } + + state->state = SCHANNEL_STATE_UPDATE_1; + + return NT_STATUS_MORE_PROCESSING_REQUIRED; + case GENSEC_SERVER: + + if (state->state != SCHANNEL_STATE_START) { + /* no third leg on this protocol */ + return NT_STATUS_INVALID_PARAMETER; + } + + /* parse the schannel startup blob */ + ndr_err = ndr_pull_struct_blob(&in, out_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + &bind_schannel, + (ndr_pull_flags_fn_t)ndr_pull_schannel_bind); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(3, ("Could not parse incoming schannel bind: %s\n", + nt_errstr(status))); + return status; + } + + if (bind_schannel.bind_type == 23) { + workstation = bind_schannel.u.info23.workstation; + domain = bind_schannel.u.info23.domain; + } else { + workstation = bind_schannel.u.info3.workstation; + domain = bind_schannel.u.info3.domain; + } + + /* pull the session key for this client */ + status = schannel_fetch_session_key(out_mem_ctx, gensec_security->event_ctx, + gensec_security->lp_ctx, workstation, + domain, &creds); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(3, ("Could not find session key for attempted schannel connection from %s: %s\n", + workstation, nt_errstr(status))); + if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_HANDLE)) { + return NT_STATUS_LOGON_FAILURE; + } + return status; + } + + state->creds = talloc_reference(state, creds); + + bind_schannel_ack.unknown1 = 1; + bind_schannel_ack.unknown2 = 0; + bind_schannel_ack.unknown3 = 0x6c0000; + + ndr_err = ndr_push_struct_blob(out, out_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), &bind_schannel_ack, + (ndr_push_flags_fn_t)ndr_push_schannel_bind_ack); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(3, ("Could not return schannel bind ack for client %s: %s\n", + workstation, nt_errstr(status))); + return status; + } + + state->state = SCHANNEL_STATE_UPDATE_1; + + return NT_STATUS_OK; + } + return NT_STATUS_INVALID_PARAMETER; +} + +/** + * Return the struct creds_CredentialState. + * + * Make sure not to call this unless gensec is using schannel... + */ + +/* TODO: make this non-public */ +_PUBLIC_ NTSTATUS dcerpc_schannel_creds(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + struct creds_CredentialState **creds) +{ + struct schannel_state *state = talloc_get_type(gensec_security->private_data, struct schannel_state); + + *creds = talloc_reference(mem_ctx, state->creds); + if (!*creds) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + + +/** + * Returns anonymous credentials for schannel, matching Win2k3. + * + */ + +static NTSTATUS schannel_session_info(struct gensec_security *gensec_security, + struct auth_session_info **_session_info) +{ + struct schannel_state *state = talloc_get_type(gensec_security->private_data, struct schannel_state); + return auth_anonymous_session_info(state, gensec_security->event_ctx, gensec_security->lp_ctx, _session_info); +} + +static NTSTATUS schannel_start(struct gensec_security *gensec_security) +{ + struct schannel_state *state; + + state = talloc(gensec_security, struct schannel_state); + if (!state) { + return NT_STATUS_NO_MEMORY; + } + + state->state = SCHANNEL_STATE_START; + state->seq_num = 0; + gensec_security->private_data = state; + + return NT_STATUS_OK; +} + +static NTSTATUS schannel_server_start(struct gensec_security *gensec_security) +{ + NTSTATUS status; + struct schannel_state *state; + + status = schannel_start(gensec_security); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + + state = (struct schannel_state *)gensec_security->private_data; + state->initiator = false; + + return NT_STATUS_OK; +} + +static NTSTATUS schannel_client_start(struct gensec_security *gensec_security) +{ + NTSTATUS status; + struct schannel_state *state; + + status = schannel_start(gensec_security); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + + state = (struct schannel_state *)gensec_security->private_data; + state->initiator = true; + + return NT_STATUS_OK; +} + + +static bool schannel_have_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + if (feature & (GENSEC_FEATURE_SIGN | + GENSEC_FEATURE_SEAL)) { + return true; + } + if (feature & GENSEC_FEATURE_DCE_STYLE) { + return true; + } + if (feature & GENSEC_FEATURE_ASYNC_REPLIES) { + return true; + } + return false; +} + + +static const struct gensec_security_ops gensec_schannel_security_ops = { + .name = "schannel", + .auth_type = DCERPC_AUTH_TYPE_SCHANNEL, + .client_start = schannel_client_start, + .server_start = schannel_server_start, + .update = schannel_update, + .seal_packet = schannel_seal_packet, + .sign_packet = schannel_sign_packet, + .check_packet = schannel_check_packet, + .unseal_packet = schannel_unseal_packet, + .session_key = schannel_session_key, + .session_info = schannel_session_info, + .sig_size = schannel_sig_size, + .have_feature = schannel_have_feature, + .enabled = true, + .priority = GENSEC_SCHANNEL +}; + +_PUBLIC_ NTSTATUS gensec_schannel_init(void) +{ + NTSTATUS ret; + ret = gensec_register(&gensec_schannel_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_schannel_security_ops.name)); + return ret; + } + + return ret; +} diff --git a/source4/auth/gensec/schannel.h b/source4/auth/gensec/schannel.h new file mode 100644 index 0000000000..2ddea29006 --- /dev/null +++ b/source4/auth/gensec/schannel.h @@ -0,0 +1,36 @@ +/* + Unix SMB/CIFS implementation. + + dcerpc schannel operations + + Copyright (C) Andrew Tridgell 2004 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "libcli/auth/credentials.h" + +enum schannel_position { + SCHANNEL_STATE_START = 0, + SCHANNEL_STATE_UPDATE_1 +}; + +struct schannel_state { + enum schannel_position state; + uint32_t seq_num; + bool initiator; + struct creds_CredentialState *creds; +}; + diff --git a/source4/auth/gensec/schannel_sign.c b/source4/auth/gensec/schannel_sign.c new file mode 100644 index 0000000000..1e57beba08 --- /dev/null +++ b/source4/auth/gensec/schannel_sign.c @@ -0,0 +1,285 @@ +/* + Unix SMB/CIFS implementation. + + schannel library code + + Copyright (C) Andrew Tridgell 2004 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/crypto/crypto.h" +#include "auth/auth.h" +#include "auth/gensec/schannel.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/schannel_proto.h" + +#define NETSEC_SIGN_SIGNATURE { 0x77, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00 } +#define NETSEC_SEAL_SIGNATURE { 0x77, 0x00, 0x7a, 0x00, 0xff, 0xff, 0x00, 0x00 } + +/******************************************************************* + Encode or Decode the sequence number (which is symmetric) + ********************************************************************/ +static void netsec_deal_with_seq_num(struct schannel_state *state, + const uint8_t packet_digest[8], + uint8_t seq_num[8]) +{ + static const uint8_t zeros[4]; + uint8_t sequence_key[16]; + uint8_t digest1[16]; + + hmac_md5(state->creds->session_key, zeros, sizeof(zeros), digest1); + hmac_md5(digest1, packet_digest, 8, sequence_key); + arcfour_crypt(seq_num, sequence_key, 8); + + state->seq_num++; +} + + +/******************************************************************* + Calculate the key with which to encode the data payload + ********************************************************************/ +static void netsec_get_sealing_key(const uint8_t session_key[16], + const uint8_t seq_num[8], + uint8_t sealing_key[16]) +{ + static const uint8_t zeros[4]; + uint8_t digest2[16]; + uint8_t sess_kf0[16]; + int i; + + for (i = 0; i < 16; i++) { + sess_kf0[i] = session_key[i] ^ 0xf0; + } + + hmac_md5(sess_kf0, zeros, 4, digest2); + hmac_md5(digest2, seq_num, 8, sealing_key); +} + + +/******************************************************************* + Create a digest over the entire packet (including the data), and + MD5 it with the session key. + ********************************************************************/ +static void schannel_digest(const uint8_t sess_key[16], + const uint8_t netsec_sig[8], + const uint8_t *confounder, + const uint8_t *data, size_t data_len, + uint8_t digest_final[16]) +{ + uint8_t packet_digest[16]; + static const uint8_t zeros[4]; + struct MD5Context ctx; + + MD5Init(&ctx); + MD5Update(&ctx, zeros, 4); + MD5Update(&ctx, netsec_sig, 8); + if (confounder) { + MD5Update(&ctx, confounder, 8); + } + MD5Update(&ctx, data, data_len); + MD5Final(packet_digest, &ctx); + + hmac_md5(sess_key, packet_digest, sizeof(packet_digest), digest_final); +} + + +/* + unseal a packet +*/ +NTSTATUS schannel_unseal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct schannel_state *state = talloc_get_type(gensec_security->private_data, struct schannel_state); + + uint8_t digest_final[16]; + uint8_t confounder[8]; + uint8_t seq_num[8]; + uint8_t sealing_key[16]; + static const uint8_t netsec_sig[8] = NETSEC_SEAL_SIGNATURE; + + if (sig->length != 32) { + return NT_STATUS_ACCESS_DENIED; + } + + memcpy(confounder, sig->data+24, 8); + + RSIVAL(seq_num, 0, state->seq_num); + SIVAL(seq_num, 4, state->initiator?0:0x80); + + netsec_get_sealing_key(state->creds->session_key, seq_num, sealing_key); + arcfour_crypt(confounder, sealing_key, 8); + arcfour_crypt(data, sealing_key, length); + + schannel_digest(state->creds->session_key, + netsec_sig, confounder, + data, length, digest_final); + + if (memcmp(digest_final, sig->data+16, 8) != 0) { + dump_data_pw("calc digest:", digest_final, 8); + dump_data_pw("wire digest:", sig->data+16, 8); + return NT_STATUS_ACCESS_DENIED; + } + + netsec_deal_with_seq_num(state, digest_final, seq_num); + + if (memcmp(seq_num, sig->data+8, 8) != 0) { + dump_data_pw("calc seq num:", seq_num, 8); + dump_data_pw("wire seq num:", sig->data+8, 8); + return NT_STATUS_ACCESS_DENIED; + } + + return NT_STATUS_OK; +} + +/* + check the signature on a packet +*/ +NTSTATUS schannel_check_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct schannel_state *state = talloc_get_type(gensec_security->private_data, struct schannel_state); + + uint8_t digest_final[16]; + uint8_t seq_num[8]; + static const uint8_t netsec_sig[8] = NETSEC_SIGN_SIGNATURE; + + /* w2k sends just 24 bytes and skip the confounder */ + if (sig->length != 32 && sig->length != 24) { + return NT_STATUS_ACCESS_DENIED; + } + + RSIVAL(seq_num, 0, state->seq_num); + SIVAL(seq_num, 4, state->initiator?0:0x80); + + dump_data_pw("seq_num:\n", seq_num, 8); + dump_data_pw("sess_key:\n", state->creds->session_key, 16); + + schannel_digest(state->creds->session_key, + netsec_sig, NULL, + data, length, digest_final); + + netsec_deal_with_seq_num(state, digest_final, seq_num); + + if (memcmp(seq_num, sig->data+8, 8) != 0) { + dump_data_pw("calc seq num:", seq_num, 8); + dump_data_pw("wire seq num:", sig->data+8, 8); + return NT_STATUS_ACCESS_DENIED; + } + + if (memcmp(digest_final, sig->data+16, 8) != 0) { + dump_data_pw("calc digest:", digest_final, 8); + dump_data_pw("wire digest:", sig->data+16, 8); + return NT_STATUS_ACCESS_DENIED; + } + + return NT_STATUS_OK; +} + + +/* + seal a packet +*/ +NTSTATUS schannel_seal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct schannel_state *state = talloc_get_type(gensec_security->private_data, struct schannel_state); + + uint8_t digest_final[16]; + uint8_t confounder[8]; + uint8_t seq_num[8]; + uint8_t sealing_key[16]; + static const uint8_t netsec_sig[8] = NETSEC_SEAL_SIGNATURE; + + generate_random_buffer(confounder, 8); + + RSIVAL(seq_num, 0, state->seq_num); + SIVAL(seq_num, 4, state->initiator?0x80:0); + + schannel_digest(state->creds->session_key, + netsec_sig, confounder, + data, length, digest_final); + + netsec_get_sealing_key(state->creds->session_key, seq_num, sealing_key); + arcfour_crypt(confounder, sealing_key, 8); + arcfour_crypt(data, sealing_key, length); + + netsec_deal_with_seq_num(state, digest_final, seq_num); + + (*sig) = data_blob_talloc(mem_ctx, NULL, 32); + + memcpy(sig->data, netsec_sig, 8); + memcpy(sig->data+8, seq_num, 8); + memcpy(sig->data+16, digest_final, 8); + memcpy(sig->data+24, confounder, 8); + + dump_data_pw("signature:", sig->data+ 0, 8); + dump_data_pw("seq_num :", sig->data+ 8, 8); + dump_data_pw("digest :", sig->data+16, 8); + dump_data_pw("confound :", sig->data+24, 8); + + return NT_STATUS_OK; +} + + +/* + sign a packet +*/ +NTSTATUS schannel_sign_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct schannel_state *state = talloc_get_type(gensec_security->private_data, struct schannel_state); + + uint8_t digest_final[16]; + uint8_t seq_num[8]; + static const uint8_t netsec_sig[8] = NETSEC_SIGN_SIGNATURE; + + RSIVAL(seq_num, 0, state->seq_num); + SIVAL(seq_num, 4, state->initiator?0x80:0); + + schannel_digest(state->creds->session_key, + netsec_sig, NULL, + data, length, digest_final); + + netsec_deal_with_seq_num(state, digest_final, seq_num); + + (*sig) = data_blob_talloc(mem_ctx, NULL, 32); + + memcpy(sig->data, netsec_sig, 8); + memcpy(sig->data+8, seq_num, 8); + memcpy(sig->data+16, digest_final, 8); + memset(sig->data+24, 0, 8); + + dump_data_pw("signature:", sig->data+ 0, 8); + dump_data_pw("seq_num :", sig->data+ 8, 8); + dump_data_pw("digest :", sig->data+16, 8); + dump_data_pw("confound :", sig->data+24, 8); + + return NT_STATUS_OK; +} diff --git a/source4/auth/gensec/schannel_state.c b/source4/auth/gensec/schannel_state.c new file mode 100644 index 0000000000..f0710c5581 --- /dev/null +++ b/source4/auth/gensec/schannel_state.c @@ -0,0 +1,293 @@ +/* + Unix SMB/CIFS implementation. + + module to store/fetch session keys for the schannel server + + Copyright (C) Andrew Tridgell 2004 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/events/events.h" +#include "lib/ldb/include/ldb.h" +#include "lib/ldb/include/ldb_errors.h" +#include "dsdb/samdb/samdb.h" +#include "ldb_wrap.h" +#include "util/util_ldb.h" +#include "libcli/auth/libcli_auth.h" +#include "auth/auth.h" +#include "param/param.h" + +/** + connect to the schannel ldb +*/ +struct ldb_context *schannel_db_connect(TALLOC_CTX *mem_ctx, struct event_context *ev_ctx, + struct loadparm_context *lp_ctx) +{ + char *path; + struct ldb_context *ldb; + bool existed; + const char *init_ldif = + "dn: @ATTRIBUTES\n" \ + "computerName: CASE_INSENSITIVE\n" \ + "flatname: CASE_INSENSITIVE\n"; + + path = smbd_tmp_path(mem_ctx, lp_ctx, "schannel.ldb"); + if (!path) { + return NULL; + } + + existed = file_exist(path); + + ldb = ldb_wrap_connect(mem_ctx, ev_ctx, lp_ctx, path, + system_session(mem_ctx, lp_ctx), + NULL, LDB_FLG_NOSYNC, NULL); + talloc_free(path); + if (!ldb) { + return NULL; + } + + if (!existed) { + gendb_add_ldif(ldb, init_ldif); + } + + return ldb; +} + +/* + remember an established session key for a netr server authentication + use a simple ldb structure +*/ +NTSTATUS schannel_store_session_key_ldb(TALLOC_CTX *mem_ctx, + struct ldb_context *ldb, + struct creds_CredentialState *creds) +{ + struct ldb_message *msg; + struct ldb_val val, seed, client_state, server_state; + char *f; + char *sct; + int ret; + + f = talloc_asprintf(mem_ctx, "%u", (unsigned int)creds->negotiate_flags); + + if (f == NULL) { + return NT_STATUS_NO_MEMORY; + } + + sct = talloc_asprintf(mem_ctx, "%u", (unsigned int)creds->secure_channel_type); + + if (sct == NULL) { + return NT_STATUS_NO_MEMORY; + } + + msg = ldb_msg_new(ldb); + if (msg == NULL) { + return NT_STATUS_NO_MEMORY; + } + + msg->dn = ldb_dn_new_fmt(msg, ldb, "computerName=%s", creds->computer_name); + if ( ! msg->dn) { + return NT_STATUS_NO_MEMORY; + } + + val.data = creds->session_key; + val.length = sizeof(creds->session_key); + + seed.data = creds->seed.data; + seed.length = sizeof(creds->seed.data); + + client_state.data = creds->client.data; + client_state.length = sizeof(creds->client.data); + server_state.data = creds->server.data; + server_state.length = sizeof(creds->server.data); + + ldb_msg_add_string(msg, "objectClass", "schannelState"); + ldb_msg_add_value(msg, "sessionKey", &val, NULL); + ldb_msg_add_value(msg, "seed", &seed, NULL); + ldb_msg_add_value(msg, "clientState", &client_state, NULL); + ldb_msg_add_value(msg, "serverState", &server_state, NULL); + ldb_msg_add_string(msg, "negotiateFlags", f); + ldb_msg_add_string(msg, "secureChannelType", sct); + ldb_msg_add_string(msg, "accountName", creds->account_name); + ldb_msg_add_string(msg, "computerName", creds->computer_name); + ldb_msg_add_string(msg, "flatname", creds->domain); + samdb_msg_add_dom_sid(ldb, mem_ctx, msg, "objectSid", creds->sid); + + ldb_delete(ldb, msg->dn); + + ret = ldb_add(ldb, msg); + + if (ret != 0) { + DEBUG(0,("Unable to add %s to session key db - %s\n", + ldb_dn_get_linearized(msg->dn), ldb_errstring(ldb))); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + return NT_STATUS_OK; +} + +NTSTATUS schannel_store_session_key(TALLOC_CTX *mem_ctx, + struct event_context *ev_ctx, + struct loadparm_context *lp_ctx, + struct creds_CredentialState *creds) +{ + struct ldb_context *ldb; + NTSTATUS nt_status; + int ret; + + ldb = schannel_db_connect(mem_ctx, ev_ctx, lp_ctx); + if (!ldb) { + return NT_STATUS_ACCESS_DENIED; + } + + ret = ldb_transaction_start(ldb); + if (ret != 0) { + talloc_free(ldb); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + nt_status = schannel_store_session_key_ldb(mem_ctx, ldb, creds); + + if (NT_STATUS_IS_OK(nt_status)) { + ret = ldb_transaction_commit(ldb); + } else { + ret = ldb_transaction_cancel(ldb); + } + + if (ret != 0) { + DEBUG(0,("Unable to commit adding credentials for %s to schannel key db - %s\n", + creds->computer_name, ldb_errstring(ldb))); + talloc_free(ldb); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + talloc_free(ldb); + return nt_status; +} + +/* + read back a credentials back for a computer +*/ +NTSTATUS schannel_fetch_session_key_ldb(TALLOC_CTX *mem_ctx, + struct ldb_context *ldb, + const char *computer_name, + const char *domain, + struct creds_CredentialState **creds) +{ + struct ldb_result *res; + int ret; + const struct ldb_val *val; + + *creds = talloc_zero(mem_ctx, struct creds_CredentialState); + if (!*creds) { + return NT_STATUS_NO_MEMORY; + } + + ret = ldb_search_exp_fmt(ldb, mem_ctx, &res, + NULL, LDB_SCOPE_SUBTREE, NULL, + "(&(computerName=%s)(flatname=%s))", computer_name, domain); + if (ret != LDB_SUCCESS) { + DEBUG(3,("schannel: Failed to find a record for client %s: %s\n", computer_name, ldb_errstring(ldb))); + return NT_STATUS_INVALID_HANDLE; + } + if (res->count != 1) { + DEBUG(3,("schannel: Failed to find a record for client: %s (found %d records)\n", computer_name, res->count)); + talloc_free(res); + return NT_STATUS_INVALID_HANDLE; + } + + val = ldb_msg_find_ldb_val(res->msgs[0], "sessionKey"); + if (val == NULL || val->length != 16) { + DEBUG(1,("schannel: record in schannel DB must contain a sessionKey of length 16, when searching for client: %s\n", computer_name)); + talloc_free(res); + return NT_STATUS_INTERNAL_ERROR; + } + + memcpy((*creds)->session_key, val->data, 16); + + val = ldb_msg_find_ldb_val(res->msgs[0], "seed"); + if (val == NULL || val->length != 8) { + DEBUG(1,("schannel: record in schannel DB must contain a vaid seed of length 8, when searching for client: %s\n", computer_name)); + talloc_free(res); + return NT_STATUS_INTERNAL_ERROR; + } + + memcpy((*creds)->seed.data, val->data, 8); + + val = ldb_msg_find_ldb_val(res->msgs[0], "clientState"); + if (val == NULL || val->length != 8) { + DEBUG(1,("schannel: record in schannel DB must contain a vaid clientState of length 8, when searching for client: %s\n", computer_name)); + talloc_free(res); + return NT_STATUS_INTERNAL_ERROR; + } + memcpy((*creds)->client.data, val->data, 8); + + val = ldb_msg_find_ldb_val(res->msgs[0], "serverState"); + if (val == NULL || val->length != 8) { + DEBUG(1,("schannel: record in schannel DB must contain a vaid serverState of length 8, when searching for client: %s\n", computer_name)); + talloc_free(res); + return NT_STATUS_INTERNAL_ERROR; + } + memcpy((*creds)->server.data, val->data, 8); + + (*creds)->negotiate_flags = ldb_msg_find_attr_as_int(res->msgs[0], "negotiateFlags", 0); + + (*creds)->secure_channel_type = ldb_msg_find_attr_as_int(res->msgs[0], "secureChannelType", 0); + + (*creds)->account_name = talloc_strdup(*creds, ldb_msg_find_attr_as_string(res->msgs[0], "accountName", NULL)); + if ((*creds)->account_name == NULL) { + talloc_free(res); + return NT_STATUS_NO_MEMORY; + } + + (*creds)->computer_name = talloc_strdup(*creds, ldb_msg_find_attr_as_string(res->msgs[0], "computerName", NULL)); + if ((*creds)->computer_name == NULL) { + talloc_free(res); + return NT_STATUS_NO_MEMORY; + } + + (*creds)->domain = talloc_strdup(*creds, ldb_msg_find_attr_as_string(res->msgs[0], "flatname", NULL)); + if ((*creds)->domain == NULL) { + talloc_free(res); + return NT_STATUS_NO_MEMORY; + } + + (*creds)->sid = samdb_result_dom_sid(*creds, res->msgs[0], "objectSid"); + + talloc_free(res); + return NT_STATUS_OK; +} + +NTSTATUS schannel_fetch_session_key(TALLOC_CTX *mem_ctx, + struct event_context *ev_ctx, + struct loadparm_context *lp_ctx, + const char *computer_name, + const char *domain, + struct creds_CredentialState **creds) +{ + NTSTATUS nt_status; + struct ldb_context *ldb; + + ldb = schannel_db_connect(mem_ctx, ev_ctx, lp_ctx); + if (!ldb) { + return NT_STATUS_ACCESS_DENIED; + } + + nt_status = schannel_fetch_session_key_ldb(mem_ctx, ldb, + computer_name, domain, + creds); + talloc_free(ldb); + return nt_status; +} diff --git a/source4/auth/gensec/socket.c b/source4/auth/gensec/socket.c new file mode 100644 index 0000000000..27449bf610 --- /dev/null +++ b/source4/auth/gensec/socket.c @@ -0,0 +1,533 @@ +/* + Unix SMB/CIFS implementation. + + GENSEC socket interface + + Copyright (C) Andrew Bartlett 2006 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/events/events.h" +#include "lib/socket/socket.h" +#include "lib/stream/packet.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" + +static const struct socket_ops gensec_socket_ops; + +struct gensec_socket { + struct gensec_security *gensec_security; + struct socket_context *socket; + struct event_context *ev; + struct packet_context *packet; + DATA_BLOB read_buffer; /* SASL packets are turned into liniarlised data here, for reading */ + size_t orig_send_len; + bool eof; + NTSTATUS error; + bool interrupted; + void (*recv_handler)(void *, uint16_t); + void *recv_private; + int in_extra_read; + bool wrap; /* Should we be wrapping on this socket at all? */ +}; + +static NTSTATUS gensec_socket_init_fn(struct socket_context *sock) +{ + switch (sock->type) { + case SOCKET_TYPE_STREAM: + break; + default: + return NT_STATUS_INVALID_PARAMETER; + } + + sock->backend_name = "gensec"; + + return NT_STATUS_OK; +} + +/* These functions are for use here only (public because SPNEGO must + * use them for recursion) */ +_PUBLIC_ NTSTATUS gensec_wrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed) +{ + if (!gensec_security->ops->wrap_packets) { + NTSTATUS nt_status; + size_t max_input_size; + DATA_BLOB unwrapped, wrapped; + max_input_size = gensec_max_input_size(gensec_security); + unwrapped = data_blob_const(in->data, MIN(max_input_size, (size_t)in->length)); + + nt_status = gensec_wrap(gensec_security, + mem_ctx, + &unwrapped, &wrapped); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + *out = data_blob_talloc(mem_ctx, NULL, 4); + if (!out->data) { + return NT_STATUS_NO_MEMORY; + } + RSIVAL(out->data, 0, wrapped.length); + + if (!data_blob_append(mem_ctx, out, wrapped.data, wrapped.length)) { + return NT_STATUS_NO_MEMORY; + } + *len_processed = unwrapped.length; + return NT_STATUS_OK; + } + return gensec_security->ops->wrap_packets(gensec_security, mem_ctx, in, out, + len_processed); +} + +/* These functions are for use here only (public because SPNEGO must + * use them for recursion) */ +NTSTATUS gensec_unwrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed) +{ + if (!gensec_security->ops->unwrap_packets) { + DATA_BLOB wrapped; + NTSTATUS nt_status; + size_t packet_size; + if (in->length < 4) { + /* Missing the header we already had! */ + DEBUG(0, ("Asked to unwrap packet of bogus length! How did we get the short packet?!\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + packet_size = RIVAL(in->data, 0); + + wrapped = data_blob_const(in->data + 4, packet_size); + + if (wrapped.length > (in->length - 4)) { + DEBUG(0, ("Asked to unwrap packed of bogus length %d > %d! How did we get this?!\n", + (int)wrapped.length, (int)(in->length - 4))); + return NT_STATUS_INTERNAL_ERROR; + } + + nt_status = gensec_unwrap(gensec_security, + mem_ctx, + &wrapped, out); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + *len_processed = packet_size + 4; + return nt_status; + } + return gensec_security->ops->unwrap_packets(gensec_security, mem_ctx, in, out, + len_processed); +} + +/* These functions are for use here only (public because SPNEGO must + * use them for recursion) */ +NTSTATUS gensec_packet_full_request(struct gensec_security *gensec_security, + DATA_BLOB blob, size_t *size) +{ + if (gensec_security->ops->packet_full_request) { + return gensec_security->ops->packet_full_request(gensec_security, + blob, size); + } + if (gensec_security->ops->unwrap_packets) { + if (blob.length) { + *size = blob.length; + return NT_STATUS_OK; + } + return STATUS_MORE_ENTRIES; + } + return packet_full_request_u32(NULL, blob, size); +} + +static NTSTATUS gensec_socket_full_request(void *private, DATA_BLOB blob, size_t *size) +{ + struct gensec_socket *gensec_socket = talloc_get_type(private, struct gensec_socket); + struct gensec_security *gensec_security = gensec_socket->gensec_security; + return gensec_packet_full_request(gensec_security, blob, size); +} + +/* Try to figure out how much data is waiting to be read */ +static NTSTATUS gensec_socket_pending(struct socket_context *sock, size_t *npending) +{ + struct gensec_socket *gensec_socket = talloc_get_type(sock->private_data, struct gensec_socket); + if (!gensec_socket->wrap) { + return socket_pending(gensec_socket->socket, npending); + } + + if (gensec_socket->read_buffer.length > 0) { + *npending = gensec_socket->read_buffer.length; + return NT_STATUS_OK; + } + + /* This is a lie. We hope the decrypted data will always be + * less than this value, so the application just gets a short + * read. Without reading and decrypting it, we can't tell. + * If the SASL mech does compression, then we just need to + * manually trigger read events */ + return socket_pending(gensec_socket->socket, npending); +} + +/* Note if an error occours, so we can return it up the stack */ +static void gensec_socket_error_handler(void *private, NTSTATUS status) +{ + struct gensec_socket *gensec_socket = talloc_get_type(private, struct gensec_socket); + if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) { + gensec_socket->eof = true; + } else { + gensec_socket->error = status; + } +} + +static void gensec_socket_trigger_read(struct event_context *ev, + struct timed_event *te, + struct timeval t, void *private) +{ + struct gensec_socket *gensec_socket = talloc_get_type(private, struct gensec_socket); + + gensec_socket->in_extra_read++; + gensec_socket->recv_handler(gensec_socket->recv_private, EVENT_FD_READ); + gensec_socket->in_extra_read--; + + /* It may well be that, having run the recv handler, we still + * have even more data waiting for us! + */ + if (gensec_socket->read_buffer.length && gensec_socket->recv_handler) { + /* Schedule this funcion to run again */ + event_add_timed(gensec_socket->ev, gensec_socket, timeval_zero(), + gensec_socket_trigger_read, gensec_socket); + } +} + +/* These two routines could be changed to use a circular buffer of + * some kind, or linked lists, or ... */ +static NTSTATUS gensec_socket_recv(struct socket_context *sock, void *buf, + size_t wantlen, size_t *nread) +{ + struct gensec_socket *gensec_socket = talloc_get_type(sock->private_data, struct gensec_socket); + + if (!gensec_socket->wrap) { + return socket_recv(gensec_socket->socket, buf, wantlen, nread); + } + + gensec_socket->error = NT_STATUS_OK; + + if (gensec_socket->read_buffer.length == 0) { + /* Process any data on the socket, into the read buffer. At + * this point, the socket is not available for read any + * longer */ + packet_recv(gensec_socket->packet); + + if (gensec_socket->eof) { + *nread = 0; + return NT_STATUS_OK; + } + + if (!NT_STATUS_IS_OK(gensec_socket->error)) { + return gensec_socket->error; + } + + if (gensec_socket->read_buffer.length == 0) { + /* Clearly we don't have the entire SASL packet yet, + * so it has not been written into the buffer */ + *nread = 0; + return STATUS_MORE_ENTRIES; + } + } + + + *nread = MIN(wantlen, gensec_socket->read_buffer.length); + memcpy(buf, gensec_socket->read_buffer.data, *nread); + + if (gensec_socket->read_buffer.length > *nread) { + memmove(gensec_socket->read_buffer.data, + gensec_socket->read_buffer.data + *nread, + gensec_socket->read_buffer.length - *nread); + } + + gensec_socket->read_buffer.length -= *nread; + gensec_socket->read_buffer.data = talloc_realloc(gensec_socket, + gensec_socket->read_buffer.data, + uint8_t, + gensec_socket->read_buffer.length); + + if (gensec_socket->read_buffer.length && + gensec_socket->in_extra_read == 0 && + gensec_socket->recv_handler) { + /* Manually call a read event, to get this moving + * again (as the socket should be dry, so the normal + * event handler won't trigger) */ + event_add_timed(gensec_socket->ev, gensec_socket, timeval_zero(), + gensec_socket_trigger_read, gensec_socket); + } + + return NT_STATUS_OK; +} + +/* Completed SASL packet callback. When we have a 'whole' SASL + * packet, decrypt it, and add it to the read buffer + * + * This function (and anything under it) MUST NOT call the event system + */ +static NTSTATUS gensec_socket_unwrap(void *private, DATA_BLOB blob) +{ + struct gensec_socket *gensec_socket = talloc_get_type(private, struct gensec_socket); + DATA_BLOB unwrapped; + NTSTATUS nt_status; + TALLOC_CTX *mem_ctx; + size_t packet_size; + + mem_ctx = talloc_new(gensec_socket); + if (!mem_ctx) { + return NT_STATUS_NO_MEMORY; + } + nt_status = gensec_unwrap_packets(gensec_socket->gensec_security, + mem_ctx, + &blob, &unwrapped, + &packet_size); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + if (packet_size != blob.length) { + DEBUG(0, ("gensec_socket_unwrap: Did not consume entire packet!\n")); + talloc_free(mem_ctx); + return NT_STATUS_INTERNAL_ERROR; + } + + /* We could change this into a linked list, and have + * gensec_socket_recv() and gensec_socket_pending() walk the + * linked list */ + + if (!data_blob_append(gensec_socket, &gensec_socket->read_buffer, + unwrapped.data, unwrapped.length)) { + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + talloc_free(mem_ctx); + return NT_STATUS_OK; +} + +/* when the data is sent, we know we have not been interrupted */ +static void send_callback(void *private) +{ + struct gensec_socket *gensec_socket = talloc_get_type(private, struct gensec_socket); + gensec_socket->interrupted = false; +} + +/* + send data, but only as much as we allow in one packet. + + If this returns STATUS_MORE_ENTRIES, the caller must retry with + exactly the same data, or a NULL blob. +*/ +static NTSTATUS gensec_socket_send(struct socket_context *sock, + const DATA_BLOB *blob, size_t *sendlen) +{ + NTSTATUS nt_status; + struct gensec_socket *gensec_socket = talloc_get_type(sock->private_data, struct gensec_socket); + DATA_BLOB wrapped; + TALLOC_CTX *mem_ctx; + + if (!gensec_socket->wrap) { + return socket_send(gensec_socket->socket, blob, sendlen); + } + + *sendlen = 0; + + /* We have have been interupted, so the caller should be + * giving us the same data again. */ + if (gensec_socket->interrupted) { + packet_queue_run(gensec_socket->packet); + + if (!NT_STATUS_IS_OK(gensec_socket->error)) { + return gensec_socket->error; + } else if (gensec_socket->interrupted) { + return STATUS_MORE_ENTRIES; + } else { + *sendlen = gensec_socket->orig_send_len; + gensec_socket->orig_send_len = 0; + return NT_STATUS_OK; + } + } + + mem_ctx = talloc_new(gensec_socket); + if (!mem_ctx) { + return NT_STATUS_NO_MEMORY; + } + + nt_status = gensec_wrap_packets(gensec_socket->gensec_security, + mem_ctx, + blob, &wrapped, + &gensec_socket->orig_send_len); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + gensec_socket->interrupted = true; + gensec_socket->error = NT_STATUS_OK; + + nt_status = packet_send_callback(gensec_socket->packet, + wrapped, + send_callback, gensec_socket); + + talloc_free(mem_ctx); + + packet_queue_run(gensec_socket->packet); + + if (!NT_STATUS_IS_OK(gensec_socket->error)) { + return gensec_socket->error; + } else if (gensec_socket->interrupted) { + return STATUS_MORE_ENTRIES; + } else { + *sendlen = gensec_socket->orig_send_len; + gensec_socket->orig_send_len = 0; + return NT_STATUS_OK; + } +} + +/* Turn a normal socket into a potentially GENSEC wrapped socket */ + +NTSTATUS gensec_socket_init(struct gensec_security *gensec_security, + struct socket_context *current_socket, + struct event_context *ev, + void (*recv_handler)(void *, uint16_t), + void *recv_private, + struct socket_context **new_socket) +{ + struct gensec_socket *gensec_socket; + struct socket_context *new_sock; + NTSTATUS nt_status; + + nt_status = socket_create_with_ops(current_socket, &gensec_socket_ops, &new_sock, + SOCKET_TYPE_STREAM, current_socket->flags | SOCKET_FLAG_ENCRYPT); + if (!NT_STATUS_IS_OK(nt_status)) { + *new_socket = NULL; + return nt_status; + } + + new_sock->state = current_socket->state; + + gensec_socket = talloc(new_sock, struct gensec_socket); + if (gensec_socket == NULL) { + *new_socket = NULL; + return NT_STATUS_NO_MEMORY; + } + + new_sock->private_data = gensec_socket; + gensec_socket->socket = current_socket; + + if (talloc_reference(gensec_socket, current_socket) == NULL) { + *new_socket = NULL; + return NT_STATUS_NO_MEMORY; + } + + /* Nothing to do here, if we are not actually wrapping on this socket */ + if (!gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL) && + !gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + + gensec_socket->wrap = false; + *new_socket = new_sock; + return NT_STATUS_OK; + } + + gensec_socket->gensec_security = gensec_security; + + gensec_socket->wrap = true; + gensec_socket->eof = false; + gensec_socket->error = NT_STATUS_OK; + gensec_socket->interrupted = false; + gensec_socket->in_extra_read = 0; + + gensec_socket->read_buffer = data_blob(NULL, 0); + + gensec_socket->recv_handler = recv_handler; + gensec_socket->recv_private = recv_private; + gensec_socket->ev = ev; + + gensec_socket->packet = packet_init(gensec_socket); + if (gensec_socket->packet == NULL) { + *new_socket = NULL; + return NT_STATUS_NO_MEMORY; + } + + packet_set_private(gensec_socket->packet, gensec_socket); + packet_set_socket(gensec_socket->packet, gensec_socket->socket); + packet_set_callback(gensec_socket->packet, gensec_socket_unwrap); + packet_set_full_request(gensec_socket->packet, gensec_socket_full_request); + packet_set_error_handler(gensec_socket->packet, gensec_socket_error_handler); + packet_set_serialise(gensec_socket->packet); + + /* TODO: full-request that knows about maximum packet size */ + + *new_socket = new_sock; + return NT_STATUS_OK; +} + + +static NTSTATUS gensec_socket_set_option(struct socket_context *sock, const char *option, const char *val) +{ + set_socket_options(socket_get_fd(sock), option); + return NT_STATUS_OK; +} + +static char *gensec_socket_get_peer_name(struct socket_context *sock, TALLOC_CTX *mem_ctx) +{ + struct gensec_socket *gensec = talloc_get_type(sock->private_data, struct gensec_socket); + return socket_get_peer_name(gensec->socket, mem_ctx); +} + +static struct socket_address *gensec_socket_get_peer_addr(struct socket_context *sock, TALLOC_CTX *mem_ctx) +{ + struct gensec_socket *gensec = talloc_get_type(sock->private_data, struct gensec_socket); + return socket_get_peer_addr(gensec->socket, mem_ctx); +} + +static struct socket_address *gensec_socket_get_my_addr(struct socket_context *sock, TALLOC_CTX *mem_ctx) +{ + struct gensec_socket *gensec = talloc_get_type(sock->private_data, struct gensec_socket); + return socket_get_my_addr(gensec->socket, mem_ctx); +} + +static int gensec_socket_get_fd(struct socket_context *sock) +{ + struct gensec_socket *gensec = talloc_get_type(sock->private_data, struct gensec_socket); + return socket_get_fd(gensec->socket); +} + +static const struct socket_ops gensec_socket_ops = { + .name = "gensec", + .fn_init = gensec_socket_init_fn, + .fn_recv = gensec_socket_recv, + .fn_send = gensec_socket_send, + .fn_pending = gensec_socket_pending, + + .fn_set_option = gensec_socket_set_option, + + .fn_get_peer_name = gensec_socket_get_peer_name, + .fn_get_peer_addr = gensec_socket_get_peer_addr, + .fn_get_my_addr = gensec_socket_get_my_addr, + .fn_get_fd = gensec_socket_get_fd +}; + diff --git a/source4/auth/gensec/spnego.c b/source4/auth/gensec/spnego.c new file mode 100644 index 0000000000..1855e0583d --- /dev/null +++ b/source4/auth/gensec/spnego.c @@ -0,0 +1,1152 @@ +/* + Unix SMB/CIFS implementation. + + RFC2478 Compliant SPNEGO implementation + + Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + Copyright (C) Stefan Metzmacher <metze@samba.org> 2004-2008 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/gensec/spnego.h" +#include "librpc/gen_ndr/ndr_dcerpc.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" + +enum spnego_state_position { + SPNEGO_SERVER_START, + SPNEGO_CLIENT_START, + SPNEGO_SERVER_TARG, + SPNEGO_CLIENT_TARG, + SPNEGO_FALLBACK, + SPNEGO_DONE +}; + +struct spnego_state { + enum spnego_message_type expected_packet; + enum spnego_state_position state_position; + struct gensec_security *sub_sec_security; + bool no_response_expected; + + const char *neg_oid; + + DATA_BLOB mech_types; +}; + + +static NTSTATUS gensec_spnego_client_start(struct gensec_security *gensec_security) +{ + struct spnego_state *spnego_state; + + spnego_state = talloc(gensec_security, struct spnego_state); + if (!spnego_state) { + return NT_STATUS_NO_MEMORY; + } + + spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT; + spnego_state->state_position = SPNEGO_CLIENT_START; + spnego_state->sub_sec_security = NULL; + spnego_state->no_response_expected = false; + spnego_state->mech_types = data_blob(NULL, 0); + + gensec_security->private_data = spnego_state; + return NT_STATUS_OK; +} + +static NTSTATUS gensec_spnego_server_start(struct gensec_security *gensec_security) +{ + struct spnego_state *spnego_state; + + spnego_state = talloc(gensec_security, struct spnego_state); + if (!spnego_state) { + return NT_STATUS_NO_MEMORY; + } + + spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT; + spnego_state->state_position = SPNEGO_SERVER_START; + spnego_state->sub_sec_security = NULL; + spnego_state->no_response_expected = false; + spnego_state->mech_types = data_blob(NULL, 0); + + gensec_security->private_data = spnego_state; + return NT_STATUS_OK; +} + +/* + wrappers for the spnego_*() functions +*/ +static NTSTATUS gensec_spnego_unseal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_unseal_packet(spnego_state->sub_sec_security, + mem_ctx, + data, length, + whole_pdu, pdu_length, + sig); +} + +static NTSTATUS gensec_spnego_check_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_check_packet(spnego_state->sub_sec_security, + mem_ctx, + data, length, + whole_pdu, pdu_length, + sig); +} + +static NTSTATUS gensec_spnego_seal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_seal_packet(spnego_state->sub_sec_security, + mem_ctx, + data, length, + whole_pdu, pdu_length, + sig); +} + +static NTSTATUS gensec_spnego_sign_packet(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_sign_packet(spnego_state->sub_sec_security, + mem_ctx, + data, length, + whole_pdu, pdu_length, + sig); +} + +static NTSTATUS gensec_spnego_wrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + DEBUG(1, ("gensec_spnego_wrap: wrong state for wrap\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_wrap(spnego_state->sub_sec_security, + mem_ctx, in, out); +} + +static NTSTATUS gensec_spnego_unwrap(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + DEBUG(1, ("gensec_spnego_unwrap: wrong state for unwrap\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_unwrap(spnego_state->sub_sec_security, + mem_ctx, in, out); +} + +static NTSTATUS gensec_spnego_wrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + DEBUG(1, ("gensec_spnego_wrap: wrong state for wrap\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_wrap_packets(spnego_state->sub_sec_security, + mem_ctx, in, out, + len_processed); +} + +static NTSTATUS gensec_spnego_packet_full_request(struct gensec_security *gensec_security, + DATA_BLOB blob, size_t *size) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + DEBUG(1, ("gensec_spnego_unwrap: wrong state for unwrap\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_packet_full_request(spnego_state->sub_sec_security, + blob, size); +} + +static NTSTATUS gensec_spnego_unwrap_packets(struct gensec_security *gensec_security, + TALLOC_CTX *mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out, + size_t *len_processed) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + DEBUG(1, ("gensec_spnego_unwrap: wrong state for unwrap\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_unwrap_packets(spnego_state->sub_sec_security, + mem_ctx, in, out, + len_processed); +} + +static size_t gensec_spnego_sig_size(struct gensec_security *gensec_security, size_t data_size) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + return 0; + } + + return gensec_sig_size(spnego_state->sub_sec_security, data_size); +} + +static size_t gensec_spnego_max_input_size(struct gensec_security *gensec_security) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + return 0; + } + + return gensec_max_input_size(spnego_state->sub_sec_security); +} + +static size_t gensec_spnego_max_wrapped_size(struct gensec_security *gensec_security) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + + if (spnego_state->state_position != SPNEGO_DONE + && spnego_state->state_position != SPNEGO_FALLBACK) { + return 0; + } + + return gensec_max_wrapped_size(spnego_state->sub_sec_security); +} + +static NTSTATUS gensec_spnego_session_key(struct gensec_security *gensec_security, + DATA_BLOB *session_key) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + if (!spnego_state->sub_sec_security) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_session_key(spnego_state->sub_sec_security, + session_key); +} + +static NTSTATUS gensec_spnego_session_info(struct gensec_security *gensec_security, + struct auth_session_info **session_info) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + if (!spnego_state->sub_sec_security) { + return NT_STATUS_INVALID_PARAMETER; + } + + return gensec_session_info(spnego_state->sub_sec_security, + session_info); +} + +/** Fallback to another GENSEC mechanism, based on magic strings + * + * This is the 'fallback' case, where we don't get SPNEGO, and have to + * try all the other options (and hope they all have a magic string + * they check) +*/ + +static NTSTATUS gensec_spnego_server_try_fallback(struct gensec_security *gensec_security, + struct spnego_state *spnego_state, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + int i,j; + struct gensec_security_ops **all_ops + = gensec_security_mechs(gensec_security, out_mem_ctx); + for (i=0; all_ops[i]; i++) { + bool is_spnego; + NTSTATUS nt_status; + if (!all_ops[i]->oid) { + continue; + } + + is_spnego = false; + for (j=0; all_ops[i]->oid[j]; j++) { + if (strcasecmp(GENSEC_OID_SPNEGO,all_ops[i]->oid[j]) == 0) { + is_spnego = true; + } + } + if (is_spnego) { + continue; + } + + if (!all_ops[i]->magic) { + continue; + } + + nt_status = all_ops[i]->magic(gensec_security, &in); + if (!NT_STATUS_IS_OK(nt_status)) { + continue; + } + + spnego_state->state_position = SPNEGO_FALLBACK; + + nt_status = gensec_subcontext_start(spnego_state, + gensec_security, + &spnego_state->sub_sec_security); + + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + /* select the sub context */ + nt_status = gensec_start_mech_by_ops(spnego_state->sub_sec_security, + all_ops[i]); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + nt_status = gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, in, out); + return nt_status; + } + DEBUG(1, ("Failed to parse SPNEGO request\n")); + return NT_STATUS_INVALID_PARAMETER; + +} + +/* + Parse the netTokenInit, either from the client, to the server, or + from the server to the client. +*/ + +static NTSTATUS gensec_spnego_parse_negTokenInit(struct gensec_security *gensec_security, + struct spnego_state *spnego_state, + TALLOC_CTX *out_mem_ctx, + const char **mechType, + const DATA_BLOB unwrapped_in, DATA_BLOB *unwrapped_out) +{ + int i; + NTSTATUS nt_status = NT_STATUS_INVALID_PARAMETER; + DATA_BLOB null_data_blob = data_blob(NULL,0); + bool ok; + + const struct gensec_security_ops_wrapper *all_sec + = gensec_security_by_oid_list(gensec_security, + out_mem_ctx, + mechType, + GENSEC_OID_SPNEGO); + + ok = spnego_write_mech_types(spnego_state, + mechType, + &spnego_state->mech_types); + if (!ok) { + DEBUG(1, ("SPNEGO: Failed to write mechTypes\n")); + return NT_STATUS_NO_MEMORY; + } + + if (spnego_state->state_position == SPNEGO_SERVER_START) { + for (i=0; all_sec && all_sec[i].op; i++) { + /* optomisitic token */ + if (strcmp(all_sec[i].oid, mechType[0]) == 0) { + nt_status = gensec_subcontext_start(spnego_state, + gensec_security, + &spnego_state->sub_sec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + /* select the sub context */ + nt_status = gensec_start_mech_by_ops(spnego_state->sub_sec_security, + all_sec[i].op); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + break; + } + + nt_status = gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, + unwrapped_in, + unwrapped_out); + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_INVALID_PARAMETER) || + NT_STATUS_EQUAL(nt_status, NT_STATUS_CANT_ACCESS_DOMAIN_INFO)) { + /* Pretend we never started it (lets the first run find some incompatible demand) */ + + DEBUG(1, ("SPNEGO(%s) NEG_TOKEN_INIT failed to parse contents: %s\n", + spnego_state->sub_sec_security->ops->name, nt_errstr(nt_status))); + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + break; + } + + spnego_state->neg_oid = all_sec[i].oid; + break; + } + } + } + + /* Having tried any optomisitc token from the client (if we + * were the server), if we didn't get anywhere, walk our list + * in our preference order */ + + if (!spnego_state->sub_sec_security) { + for (i=0; all_sec && all_sec[i].op; i++) { + nt_status = gensec_subcontext_start(spnego_state, + gensec_security, + &spnego_state->sub_sec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + /* select the sub context */ + nt_status = gensec_start_mech_by_ops(spnego_state->sub_sec_security, + all_sec[i].op); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + continue; + } + + spnego_state->neg_oid = all_sec[i].oid; + + /* only get the helping start blob for the first OID */ + nt_status = gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, + null_data_blob, + unwrapped_out); + + /* it is likely that a NULL input token will + * not be liked by most server mechs, but if + * we are in the client, we want the first + * update packet to be able to abort the use + * of this mech */ + if (spnego_state->state_position != SPNEGO_SERVER_START) { + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_INVALID_PARAMETER) || + NT_STATUS_EQUAL(nt_status, NT_STATUS_CANT_ACCESS_DOMAIN_INFO)) { + /* Pretend we never started it (lets the first run find some incompatible demand) */ + + DEBUG(1, ("SPNEGO(%s) NEG_TOKEN_INIT failed to parse: %s\n", + spnego_state->sub_sec_security->ops->name, nt_errstr(nt_status))); + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + continue; + } + } + + break; + } + } + + if (spnego_state->sub_sec_security) { + /* it is likely that a NULL input token will + * not be liked by most server mechs, but this + * does the right thing in the CIFS client. + * just push us along the merry-go-round + * again, and hope for better luck next + * time */ + + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_INVALID_PARAMETER)) { + *unwrapped_out = data_blob(NULL, 0); + nt_status = NT_STATUS_MORE_PROCESSING_REQUIRED; + } + + if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_INVALID_PARAMETER) + && !NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED) + && !NT_STATUS_IS_OK(nt_status)) { + DEBUG(1, ("SPNEGO(%s) NEG_TOKEN_INIT failed: %s\n", + spnego_state->sub_sec_security->ops->name, nt_errstr(nt_status))); + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + + /* We started the mech correctly, and the + * input from the other side was valid. + * Return the error (say bad password, invalid + * ticket) */ + return nt_status; + } + + + return nt_status; /* OK, INVALID_PARAMETER ore MORE PROCESSING */ + } + + DEBUG(1, ("SPNEGO: Could not find a suitable mechtype in NEG_TOKEN_INIT\n")); + /* we could re-negotiate here, but it would only work + * if the client or server lied about what it could + * support the first time. Lets keep this code to + * reality */ + + return nt_status; +} + +/** create a negTokenInit + * + * This is the same packet, no matter if the client or server sends it first, but it is always the first packet +*/ +static NTSTATUS gensec_spnego_create_negTokenInit(struct gensec_security *gensec_security, + struct spnego_state *spnego_state, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + int i; + NTSTATUS nt_status = NT_STATUS_INVALID_PARAMETER; + DATA_BLOB null_data_blob = data_blob(NULL,0); + const char **mechTypes = NULL; + DATA_BLOB unwrapped_out = data_blob(NULL, 0); + const struct gensec_security_ops_wrapper *all_sec; + const char *principal = NULL; + + mechTypes = gensec_security_oids(gensec_security, + out_mem_ctx, GENSEC_OID_SPNEGO); + + all_sec = gensec_security_by_oid_list(gensec_security, + out_mem_ctx, + mechTypes, + GENSEC_OID_SPNEGO); + for (i=0; all_sec && all_sec[i].op; i++) { + struct spnego_data spnego_out; + const char **send_mech_types; + bool ok; + + nt_status = gensec_subcontext_start(spnego_state, + gensec_security, + &spnego_state->sub_sec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + /* select the sub context */ + nt_status = gensec_start_mech_by_ops(spnego_state->sub_sec_security, + all_sec[i].op); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + continue; + } + + /* In the client, try and produce the first (optimistic) packet */ + if (spnego_state->state_position == SPNEGO_CLIENT_START) { + nt_status = gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, + null_data_blob, + &unwrapped_out); + + if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED) + && !NT_STATUS_IS_OK(nt_status)) { + DEBUG(1, ("SPNEGO(%s) creating NEG_TOKEN_INIT failed: %s\n", + spnego_state->sub_sec_security->ops->name, nt_errstr(nt_status))); + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + /* Pretend we never started it (lets the first run find some incompatible demand) */ + + continue; + } + } + + spnego_out.type = SPNEGO_NEG_TOKEN_INIT; + + send_mech_types = gensec_security_oids_from_ops_wrapped(out_mem_ctx, + &all_sec[i]); + + ok = spnego_write_mech_types(spnego_state, + send_mech_types, + &spnego_state->mech_types); + if (!ok) { + DEBUG(1, ("SPNEGO: Failed to write mechTypes\n")); + return NT_STATUS_NO_MEMORY; + } + + /* List the remaining mechs as options */ + spnego_out.negTokenInit.mechTypes = send_mech_types; + spnego_out.negTokenInit.reqFlags = 0; + + if (spnego_state->state_position == SPNEGO_SERVER_START) { + /* server credentials */ + struct cli_credentials *creds = gensec_get_credentials(gensec_security); + if (creds) { + principal = cli_credentials_get_principal(creds, out_mem_ctx); + } + } + if (principal) { + spnego_out.negTokenInit.mechListMIC + = data_blob_string_const(principal); + } else { + spnego_out.negTokenInit.mechListMIC = null_data_blob; + } + + spnego_out.negTokenInit.mechToken = unwrapped_out; + + if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) { + DEBUG(1, ("Failed to write NEG_TOKEN_INIT\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + /* set next state */ + spnego_state->neg_oid = all_sec[i].oid; + + if (NT_STATUS_IS_OK(nt_status)) { + spnego_state->no_response_expected = true; + } + + return NT_STATUS_MORE_PROCESSING_REQUIRED; + } + talloc_free(spnego_state->sub_sec_security); + spnego_state->sub_sec_security = NULL; + + DEBUG(1, ("Failed to setup SPNEGO negTokenInit request: %s\n", nt_errstr(nt_status))); + return NT_STATUS_INVALID_PARAMETER; +} + + +/** create a server negTokenTarg + * + * This is the case, where the client is the first one who sends data +*/ + +static NTSTATUS gensec_spnego_server_negTokenTarg(struct gensec_security *gensec_security, + struct spnego_state *spnego_state, + TALLOC_CTX *out_mem_ctx, + NTSTATUS nt_status, + const DATA_BLOB unwrapped_out, + DATA_BLOB mech_list_mic, + DATA_BLOB *out) +{ + struct spnego_data spnego_out; + DATA_BLOB null_data_blob = data_blob(NULL, 0); + + /* compose reply */ + spnego_out.type = SPNEGO_NEG_TOKEN_TARG; + spnego_out.negTokenTarg.responseToken = unwrapped_out; + spnego_out.negTokenTarg.mechListMIC = null_data_blob; + spnego_out.negTokenTarg.supportedMech = NULL; + + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { + spnego_out.negTokenTarg.supportedMech = spnego_state->neg_oid; + spnego_out.negTokenTarg.negResult = SPNEGO_ACCEPT_INCOMPLETE; + spnego_state->state_position = SPNEGO_SERVER_TARG; + } else if (NT_STATUS_IS_OK(nt_status)) { + if (unwrapped_out.data) { + spnego_out.negTokenTarg.supportedMech = spnego_state->neg_oid; + } + spnego_out.negTokenTarg.negResult = SPNEGO_ACCEPT_COMPLETED; + spnego_out.negTokenTarg.mechListMIC = mech_list_mic; + spnego_state->state_position = SPNEGO_DONE; + } else { + spnego_out.negTokenTarg.negResult = SPNEGO_REJECT; + DEBUG(2, ("SPNEGO login failed: %s\n", nt_errstr(nt_status))); + spnego_state->state_position = SPNEGO_DONE; + } + + if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) { + DEBUG(1, ("Failed to write SPNEGO reply to NEG_TOKEN_TARG\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG; + + return nt_status; +} + + +static NTSTATUS gensec_spnego_update(struct gensec_security *gensec_security, TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + DATA_BLOB null_data_blob = data_blob(NULL, 0); + DATA_BLOB mech_list_mic = data_blob(NULL, 0); + DATA_BLOB unwrapped_out = data_blob(NULL, 0); + struct spnego_data spnego_out; + struct spnego_data spnego; + + ssize_t len; + + *out = data_blob(NULL, 0); + + if (!out_mem_ctx) { + out_mem_ctx = spnego_state; + } + + /* and switch into the state machine */ + + switch (spnego_state->state_position) { + case SPNEGO_FALLBACK: + return gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, in, out); + case SPNEGO_SERVER_START: + { + NTSTATUS nt_status; + if (in.length) { + + len = spnego_read_data(gensec_security, in, &spnego); + if (len == -1) { + return gensec_spnego_server_try_fallback(gensec_security, spnego_state, + out_mem_ctx, in, out); + } + /* client sent NegTargetInit, we send NegTokenTarg */ + + /* OK, so it's real SPNEGO, check the packet's the one we expect */ + if (spnego.type != spnego_state->expected_packet) { + DEBUG(1, ("Invalid SPNEGO request: %d, expected %d\n", spnego.type, + spnego_state->expected_packet)); + dump_data(1, in.data, in.length); + spnego_free_data(&spnego); + return NT_STATUS_INVALID_PARAMETER; + } + + nt_status = gensec_spnego_parse_negTokenInit(gensec_security, + spnego_state, + out_mem_ctx, + spnego.negTokenInit.mechTypes, + spnego.negTokenInit.mechToken, + &unwrapped_out); + + nt_status = gensec_spnego_server_negTokenTarg(gensec_security, + spnego_state, + out_mem_ctx, + nt_status, + unwrapped_out, + null_data_blob, + out); + + spnego_free_data(&spnego); + + return nt_status; + } else { + nt_status = gensec_spnego_create_negTokenInit(gensec_security, spnego_state, + out_mem_ctx, in, out); + spnego_state->state_position = SPNEGO_SERVER_START; + spnego_state->expected_packet = SPNEGO_NEG_TOKEN_INIT; + return nt_status; + } + } + + case SPNEGO_CLIENT_START: + { + /* The server offers a list of mechanisms */ + + const char *my_mechs[] = {NULL, NULL}; + NTSTATUS nt_status = NT_STATUS_INVALID_PARAMETER; + + if (!in.length) { + /* client to produce negTokenInit */ + nt_status = gensec_spnego_create_negTokenInit(gensec_security, spnego_state, + out_mem_ctx, in, out); + spnego_state->state_position = SPNEGO_CLIENT_TARG; + spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG; + return nt_status; + } + + len = spnego_read_data(gensec_security, in, &spnego); + + if (len == -1) { + DEBUG(1, ("Invalid SPNEGO request:\n")); + dump_data(1, in.data, in.length); + return NT_STATUS_INVALID_PARAMETER; + } + + /* OK, so it's real SPNEGO, check the packet's the one we expect */ + if (spnego.type != spnego_state->expected_packet) { + DEBUG(1, ("Invalid SPNEGO request: %d, expected %d\n", spnego.type, + spnego_state->expected_packet)); + dump_data(1, in.data, in.length); + spnego_free_data(&spnego); + return NT_STATUS_INVALID_PARAMETER; + } + + if (spnego.negTokenInit.targetPrincipal) { + DEBUG(5, ("Server claims it's principal name is %s\n", spnego.negTokenInit.targetPrincipal)); + gensec_set_target_principal(gensec_security, spnego.negTokenInit.targetPrincipal); + } + + nt_status = gensec_spnego_parse_negTokenInit(gensec_security, + spnego_state, + out_mem_ctx, + spnego.negTokenInit.mechTypes, + spnego.negTokenInit.mechToken, + &unwrapped_out); + + if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED) && !NT_STATUS_IS_OK(nt_status)) { + spnego_free_data(&spnego); + return nt_status; + } + + my_mechs[0] = spnego_state->neg_oid; + /* compose reply */ + spnego_out.type = SPNEGO_NEG_TOKEN_INIT; + spnego_out.negTokenInit.mechTypes = my_mechs; + spnego_out.negTokenInit.reqFlags = 0; + spnego_out.negTokenInit.mechListMIC = null_data_blob; + spnego_out.negTokenInit.mechToken = unwrapped_out; + + if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) { + DEBUG(1, ("Failed to write SPNEGO reply to NEG_TOKEN_INIT\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + /* set next state */ + spnego_state->expected_packet = SPNEGO_NEG_TOKEN_TARG; + spnego_state->state_position = SPNEGO_CLIENT_TARG; + + if (NT_STATUS_IS_OK(nt_status)) { + spnego_state->no_response_expected = true; + } + + spnego_free_data(&spnego); + return NT_STATUS_MORE_PROCESSING_REQUIRED; + } + case SPNEGO_SERVER_TARG: + { + NTSTATUS nt_status; + bool new_spnego = false; + + if (!in.length) { + return NT_STATUS_INVALID_PARAMETER; + } + + len = spnego_read_data(gensec_security, in, &spnego); + + if (len == -1) { + DEBUG(1, ("Invalid SPNEGO request:\n")); + dump_data(1, in.data, in.length); + return NT_STATUS_INVALID_PARAMETER; + } + + /* OK, so it's real SPNEGO, check the packet's the one we expect */ + if (spnego.type != spnego_state->expected_packet) { + DEBUG(1, ("Invalid SPNEGO request: %d, expected %d\n", spnego.type, + spnego_state->expected_packet)); + dump_data(1, in.data, in.length); + spnego_free_data(&spnego); + return NT_STATUS_INVALID_PARAMETER; + } + + if (!spnego_state->sub_sec_security) { + DEBUG(1, ("SPNEGO: Did not setup a mech in NEG_TOKEN_INIT\n")); + spnego_free_data(&spnego); + return NT_STATUS_INVALID_PARAMETER; + } + + nt_status = gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, + spnego.negTokenTarg.responseToken, + &unwrapped_out); + if (NT_STATUS_IS_OK(nt_status) && spnego.negTokenTarg.mechListMIC.length > 0) { + new_spnego = true; + nt_status = gensec_check_packet(spnego_state->sub_sec_security, + out_mem_ctx, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + &spnego.negTokenTarg.mechListMIC); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(2,("GENSEC SPNEGO: failed to verify mechListMIC: %s\n", + nt_errstr(nt_status))); + } + } + if (NT_STATUS_IS_OK(nt_status) && new_spnego) { + nt_status = gensec_sign_packet(spnego_state->sub_sec_security, + out_mem_ctx, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + &mech_list_mic); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(2,("GENSEC SPNEGO: failed to sign mechListMIC: %s\n", + nt_errstr(nt_status))); + } + } + + nt_status = gensec_spnego_server_negTokenTarg(gensec_security, + spnego_state, + out_mem_ctx, + nt_status, + unwrapped_out, + mech_list_mic, + out); + + spnego_free_data(&spnego); + + return nt_status; + } + case SPNEGO_CLIENT_TARG: + { + NTSTATUS nt_status; + if (!in.length) { + return NT_STATUS_INVALID_PARAMETER; + } + + len = spnego_read_data(gensec_security, in, &spnego); + + if (len == -1) { + DEBUG(1, ("Invalid SPNEGO request:\n")); + dump_data(1, in.data, in.length); + return NT_STATUS_INVALID_PARAMETER; + } + + /* OK, so it's real SPNEGO, check the packet's the one we expect */ + if (spnego.type != spnego_state->expected_packet) { + DEBUG(1, ("Invalid SPNEGO request: %d, expected %d\n", spnego.type, + spnego_state->expected_packet)); + dump_data(1, in.data, in.length); + spnego_free_data(&spnego); + return NT_STATUS_INVALID_PARAMETER; + } + + if (spnego.negTokenTarg.negResult == SPNEGO_REJECT) { + spnego_free_data(&spnego); + return NT_STATUS_ACCESS_DENIED; + } + + /* Server didn't like our choice of mech, and chose something else */ + if ((spnego.negTokenTarg.negResult == SPNEGO_ACCEPT_INCOMPLETE) && + spnego.negTokenTarg.supportedMech && + strcmp(spnego.negTokenTarg.supportedMech, spnego_state->neg_oid) != 0) { + DEBUG(3,("GENSEC SPNEGO: client preferred mech (%s) not accepted, server wants: %s\n", + gensec_get_name_by_oid(spnego.negTokenTarg.supportedMech), + gensec_get_name_by_oid(spnego_state->neg_oid))); + + talloc_free(spnego_state->sub_sec_security); + nt_status = gensec_subcontext_start(spnego_state, + gensec_security, + &spnego_state->sub_sec_security); + if (!NT_STATUS_IS_OK(nt_status)) { + spnego_free_data(&spnego); + return nt_status; + } + /* select the sub context */ + nt_status = gensec_start_mech_by_oid(spnego_state->sub_sec_security, + spnego.negTokenTarg.supportedMech); + if (!NT_STATUS_IS_OK(nt_status)) { + spnego_free_data(&spnego); + return nt_status; + } + + nt_status = gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, + spnego.negTokenTarg.responseToken, + &unwrapped_out); + spnego_state->neg_oid = talloc_strdup(spnego_state, spnego.negTokenTarg.supportedMech); + } else if (spnego_state->no_response_expected) { + if (spnego.negTokenTarg.negResult != SPNEGO_ACCEPT_COMPLETED) { + DEBUG(3,("GENSEC SPNEGO: client GENSEC accepted, but server rejected (bad password?)\n")); + nt_status = NT_STATUS_INVALID_PARAMETER; + } else if (spnego.negTokenTarg.responseToken.length) { + DEBUG(2,("GENSEC SPNEGO: client GENSEC accepted, but server continued negotiation!\n")); + nt_status = NT_STATUS_INVALID_PARAMETER; + } else { + nt_status = NT_STATUS_OK; + } + if (NT_STATUS_IS_OK(nt_status) && spnego.negTokenTarg.mechListMIC.length > 0) { + nt_status = gensec_check_packet(spnego_state->sub_sec_security, + out_mem_ctx, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + &spnego.negTokenTarg.mechListMIC); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(2,("GENSEC SPNEGO: failed to verify mechListMIC: %s\n", + nt_errstr(nt_status))); + } + } + } else { + bool new_spnego = false; + + nt_status = gensec_update(spnego_state->sub_sec_security, + out_mem_ctx, + spnego.negTokenTarg.responseToken, + &unwrapped_out); + + if (NT_STATUS_IS_OK(nt_status)) { + new_spnego = gensec_have_feature(spnego_state->sub_sec_security, + GENSEC_FEATURE_NEW_SPNEGO); + } + if (NT_STATUS_IS_OK(nt_status) && new_spnego) { + nt_status = gensec_sign_packet(spnego_state->sub_sec_security, + out_mem_ctx, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + spnego_state->mech_types.data, + spnego_state->mech_types.length, + &mech_list_mic); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(2,("GENSEC SPNEGO: failed to sign mechListMIC: %s\n", + nt_errstr(nt_status))); + } + } + if (NT_STATUS_IS_OK(nt_status)) { + spnego_state->no_response_expected = true; + } + } + + spnego_free_data(&spnego); + + if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED) + && !NT_STATUS_IS_OK(nt_status)) { + DEBUG(1, ("SPNEGO(%s) login failed: %s\n", + spnego_state->sub_sec_security->ops->name, + nt_errstr(nt_status))); + return nt_status; + } + + if (unwrapped_out.length) { + /* compose reply */ + spnego_out.type = SPNEGO_NEG_TOKEN_TARG; + spnego_out.negTokenTarg.negResult = SPNEGO_NONE_RESULT; + spnego_out.negTokenTarg.supportedMech = NULL; + spnego_out.negTokenTarg.responseToken = unwrapped_out; + spnego_out.negTokenTarg.mechListMIC = mech_list_mic; + + if (spnego_write_data(out_mem_ctx, out, &spnego_out) == -1) { + DEBUG(1, ("Failed to write SPNEGO reply to NEG_TOKEN_TARG\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + spnego_state->state_position = SPNEGO_CLIENT_TARG; + nt_status = NT_STATUS_MORE_PROCESSING_REQUIRED; + } else { + + /* all done - server has accepted, and we agree */ + *out = null_data_blob; + + if (spnego.negTokenTarg.negResult != SPNEGO_ACCEPT_COMPLETED) { + /* unless of course it did not accept */ + DEBUG(1,("gensec_update ok but not accepted\n")); + nt_status = NT_STATUS_INVALID_PARAMETER; + } + + spnego_state->state_position = SPNEGO_DONE; + } + + return nt_status; + } + case SPNEGO_DONE: + /* We should not be called after we are 'done' */ + return NT_STATUS_INVALID_PARAMETER; + } + return NT_STATUS_INVALID_PARAMETER; +} + +static bool gensec_spnego_have_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + struct spnego_state *spnego_state = (struct spnego_state *)gensec_security->private_data; + if (!spnego_state->sub_sec_security) { + return false; + } + + return gensec_have_feature(spnego_state->sub_sec_security, + feature); +} + +static const char *gensec_spnego_oids[] = { + GENSEC_OID_SPNEGO, + NULL +}; + +static const struct gensec_security_ops gensec_spnego_security_ops = { + .name = "spnego", + .sasl_name = "GSS-SPNEGO", + .auth_type = DCERPC_AUTH_TYPE_SPNEGO, + .oid = gensec_spnego_oids, + .client_start = gensec_spnego_client_start, + .server_start = gensec_spnego_server_start, + .update = gensec_spnego_update, + .seal_packet = gensec_spnego_seal_packet, + .sign_packet = gensec_spnego_sign_packet, + .sig_size = gensec_spnego_sig_size, + .max_wrapped_size = gensec_spnego_max_wrapped_size, + .max_input_size = gensec_spnego_max_input_size, + .check_packet = gensec_spnego_check_packet, + .unseal_packet = gensec_spnego_unseal_packet, + .packet_full_request = gensec_spnego_packet_full_request, + .wrap = gensec_spnego_wrap, + .unwrap = gensec_spnego_unwrap, + .wrap_packets = gensec_spnego_wrap_packets, + .unwrap_packets = gensec_spnego_unwrap_packets, + .session_key = gensec_spnego_session_key, + .session_info = gensec_spnego_session_info, + .have_feature = gensec_spnego_have_feature, + .enabled = true, + .priority = GENSEC_SPNEGO +}; + +_PUBLIC_ NTSTATUS gensec_spnego_init(void) +{ + NTSTATUS ret; + ret = gensec_register(&gensec_spnego_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_spnego_security_ops.name)); + return ret; + } + + return ret; +} diff --git a/source4/auth/gensec/spnego.h b/source4/auth/gensec/spnego.h new file mode 100644 index 0000000000..24e80ecb0b --- /dev/null +++ b/source4/auth/gensec/spnego.h @@ -0,0 +1,65 @@ +/* + Unix SMB/CIFS implementation. + + RFC2478 Compliant SPNEGO implementation + + Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#define SPNEGO_DELEG_FLAG 0x01 +#define SPNEGO_MUTUAL_FLAG 0x02 +#define SPNEGO_REPLAY_FLAG 0x04 +#define SPNEGO_SEQUENCE_FLAG 0x08 +#define SPNEGO_ANON_FLAG 0x10 +#define SPNEGO_CONF_FLAG 0x20 +#define SPNEGO_INTEG_FLAG 0x40 +#define SPNEGO_REQ_FLAG 0x80 + +enum spnego_negResult { + SPNEGO_ACCEPT_COMPLETED = 0, + SPNEGO_ACCEPT_INCOMPLETE = 1, + SPNEGO_REJECT = 2, + SPNEGO_NONE_RESULT = 3 +}; + +struct spnego_negTokenInit { + const char **mechTypes; + int reqFlags; + DATA_BLOB mechToken; + DATA_BLOB mechListMIC; + char *targetPrincipal; +}; + +struct spnego_negTokenTarg { + uint8_t negResult; + const char *supportedMech; + DATA_BLOB responseToken; + DATA_BLOB mechListMIC; +}; + +struct spnego_data { + int type; + struct spnego_negTokenInit negTokenInit; + struct spnego_negTokenTarg negTokenTarg; +}; + +enum spnego_message_type { + SPNEGO_NEG_TOKEN_INIT = 0, + SPNEGO_NEG_TOKEN_TARG = 1, +}; + +#include "auth/gensec/spnego_proto.h" diff --git a/source4/auth/gensec/spnego_parse.c b/source4/auth/gensec/spnego_parse.c new file mode 100644 index 0000000000..5ea8cf7100 --- /dev/null +++ b/source4/auth/gensec/spnego_parse.c @@ -0,0 +1,408 @@ +/* + Unix SMB/CIFS implementation. + + RFC2478 Compliant SPNEGO implementation + + Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/gensec/spnego.h" +#include "auth/gensec/gensec.h" +#include "lib/util/asn1.h" + +static bool read_negTokenInit(struct asn1_data *asn1, TALLOC_CTX *mem_ctx, + struct spnego_negTokenInit *token) +{ + ZERO_STRUCTP(token); + + asn1_start_tag(asn1, ASN1_CONTEXT(0)); + asn1_start_tag(asn1, ASN1_SEQUENCE(0)); + + while (!asn1->has_error && 0 < asn1_tag_remaining(asn1)) { + int i; + uint8_t context; + if (!asn1_peek_uint8(asn1, &context)) { + asn1->has_error = true; + break; + } + + switch (context) { + /* Read mechTypes */ + case ASN1_CONTEXT(0): + asn1_start_tag(asn1, ASN1_CONTEXT(0)); + asn1_start_tag(asn1, ASN1_SEQUENCE(0)); + + token->mechTypes = talloc(NULL, const char *); + for (i = 0; !asn1->has_error && + 0 < asn1_tag_remaining(asn1); i++) { + token->mechTypes = talloc_realloc(NULL, + token->mechTypes, + const char *, i+2); + asn1_read_OID(asn1, token->mechTypes, token->mechTypes + i); + } + token->mechTypes[i] = NULL; + + asn1_end_tag(asn1); + asn1_end_tag(asn1); + break; + /* Read reqFlags */ + case ASN1_CONTEXT(1): + asn1_start_tag(asn1, ASN1_CONTEXT(1)); + asn1_read_Integer(asn1, &token->reqFlags); + token->reqFlags |= SPNEGO_REQ_FLAG; + asn1_end_tag(asn1); + break; + /* Read mechToken */ + case ASN1_CONTEXT(2): + asn1_start_tag(asn1, ASN1_CONTEXT(2)); + asn1_read_OctetString(asn1, mem_ctx, &token->mechToken); + asn1_end_tag(asn1); + break; + /* Read mecListMIC */ + case ASN1_CONTEXT(3): + { + uint8_t type_peek; + asn1_start_tag(asn1, ASN1_CONTEXT(3)); + if (!asn1_peek_uint8(asn1, &type_peek)) { + asn1->has_error = true; + break; + } + if (type_peek == ASN1_OCTET_STRING) { + asn1_read_OctetString(asn1, mem_ctx, + &token->mechListMIC); + } else { + /* RFC 2478 says we have an Octet String here, + but W2k sends something different... */ + char *mechListMIC; + asn1_push_tag(asn1, ASN1_SEQUENCE(0)); + asn1_push_tag(asn1, ASN1_CONTEXT(0)); + asn1_read_GeneralString(asn1, mem_ctx, &mechListMIC); + asn1_pop_tag(asn1); + asn1_pop_tag(asn1); + + token->targetPrincipal = mechListMIC; + } + asn1_end_tag(asn1); + break; + } + default: + asn1->has_error = true; + break; + } + } + + asn1_end_tag(asn1); + asn1_end_tag(asn1); + + return !asn1->has_error; +} + +static bool write_negTokenInit(struct asn1_data *asn1, struct spnego_negTokenInit *token) +{ + asn1_push_tag(asn1, ASN1_CONTEXT(0)); + asn1_push_tag(asn1, ASN1_SEQUENCE(0)); + + /* Write mechTypes */ + if (token->mechTypes && *token->mechTypes) { + int i; + + asn1_push_tag(asn1, ASN1_CONTEXT(0)); + asn1_push_tag(asn1, ASN1_SEQUENCE(0)); + for (i = 0; token->mechTypes[i]; i++) { + asn1_write_OID(asn1, token->mechTypes[i]); + } + asn1_pop_tag(asn1); + asn1_pop_tag(asn1); + } + + /* write reqFlags */ + if (token->reqFlags & SPNEGO_REQ_FLAG) { + int flags = token->reqFlags & ~SPNEGO_REQ_FLAG; + + asn1_push_tag(asn1, ASN1_CONTEXT(1)); + asn1_write_Integer(asn1, flags); + asn1_pop_tag(asn1); + } + + /* write mechToken */ + if (token->mechToken.data) { + asn1_push_tag(asn1, ASN1_CONTEXT(2)); + asn1_write_OctetString(asn1, token->mechToken.data, + token->mechToken.length); + asn1_pop_tag(asn1); + } + + /* write mechListMIC */ + if (token->mechListMIC.data) { + asn1_push_tag(asn1, ASN1_CONTEXT(3)); +#if 0 + /* This is what RFC 2478 says ... */ + asn1_write_OctetString(asn1, token->mechListMIC.data, + token->mechListMIC.length); +#else + /* ... but unfortunately this is what Windows + sends/expects */ + asn1_push_tag(asn1, ASN1_SEQUENCE(0)); + asn1_push_tag(asn1, ASN1_CONTEXT(0)); + asn1_push_tag(asn1, ASN1_GENERAL_STRING); + asn1_write(asn1, token->mechListMIC.data, + token->mechListMIC.length); + asn1_pop_tag(asn1); + asn1_pop_tag(asn1); + asn1_pop_tag(asn1); +#endif + asn1_pop_tag(asn1); + } + + asn1_pop_tag(asn1); + asn1_pop_tag(asn1); + + return !asn1->has_error; +} + +static bool read_negTokenTarg(struct asn1_data *asn1, TALLOC_CTX *mem_ctx, + struct spnego_negTokenTarg *token) +{ + ZERO_STRUCTP(token); + + asn1_start_tag(asn1, ASN1_CONTEXT(1)); + asn1_start_tag(asn1, ASN1_SEQUENCE(0)); + + while (!asn1->has_error && 0 < asn1_tag_remaining(asn1)) { + uint8_t context; + if (!asn1_peek_uint8(asn1, &context)) { + asn1->has_error = true; + break; + } + + switch (context) { + case ASN1_CONTEXT(0): + asn1_start_tag(asn1, ASN1_CONTEXT(0)); + asn1_start_tag(asn1, ASN1_ENUMERATED); + asn1_read_uint8(asn1, &token->negResult); + asn1_end_tag(asn1); + asn1_end_tag(asn1); + break; + case ASN1_CONTEXT(1): + asn1_start_tag(asn1, ASN1_CONTEXT(1)); + asn1_read_OID(asn1, mem_ctx, &token->supportedMech); + asn1_end_tag(asn1); + break; + case ASN1_CONTEXT(2): + asn1_start_tag(asn1, ASN1_CONTEXT(2)); + asn1_read_OctetString(asn1, mem_ctx, &token->responseToken); + asn1_end_tag(asn1); + break; + case ASN1_CONTEXT(3): + asn1_start_tag(asn1, ASN1_CONTEXT(3)); + asn1_read_OctetString(asn1, mem_ctx, &token->mechListMIC); + asn1_end_tag(asn1); + break; + default: + asn1->has_error = true; + break; + } + } + + asn1_end_tag(asn1); + asn1_end_tag(asn1); + + return !asn1->has_error; +} + +static bool write_negTokenTarg(struct asn1_data *asn1, struct spnego_negTokenTarg *token) +{ + asn1_push_tag(asn1, ASN1_CONTEXT(1)); + asn1_push_tag(asn1, ASN1_SEQUENCE(0)); + + if (token->negResult != SPNEGO_NONE_RESULT) { + asn1_push_tag(asn1, ASN1_CONTEXT(0)); + asn1_write_enumerated(asn1, token->negResult); + asn1_pop_tag(asn1); + } + + if (token->supportedMech) { + asn1_push_tag(asn1, ASN1_CONTEXT(1)); + asn1_write_OID(asn1, token->supportedMech); + asn1_pop_tag(asn1); + } + + if (token->responseToken.data) { + asn1_push_tag(asn1, ASN1_CONTEXT(2)); + asn1_write_OctetString(asn1, token->responseToken.data, + token->responseToken.length); + asn1_pop_tag(asn1); + } + + if (token->mechListMIC.data) { + asn1_push_tag(asn1, ASN1_CONTEXT(3)); + asn1_write_OctetString(asn1, token->mechListMIC.data, + token->mechListMIC.length); + asn1_pop_tag(asn1); + } + + asn1_pop_tag(asn1); + asn1_pop_tag(asn1); + + return !asn1->has_error; +} + +ssize_t spnego_read_data(TALLOC_CTX *mem_ctx, DATA_BLOB data, struct spnego_data *token) +{ + struct asn1_data *asn1; + ssize_t ret = -1; + uint8_t context; + + ZERO_STRUCTP(token); + + if (data.length == 0) { + return ret; + } + + asn1 = asn1_init(mem_ctx); + if (asn1 == NULL) { + return -1; + } + + asn1_load(asn1, data); + + if (!asn1_peek_uint8(asn1, &context)) { + asn1->has_error = true; + } else { + switch (context) { + case ASN1_APPLICATION(0): + asn1_start_tag(asn1, ASN1_APPLICATION(0)); + asn1_check_OID(asn1, GENSEC_OID_SPNEGO); + if (read_negTokenInit(asn1, mem_ctx, &token->negTokenInit)) { + token->type = SPNEGO_NEG_TOKEN_INIT; + } + asn1_end_tag(asn1); + break; + case ASN1_CONTEXT(1): + if (read_negTokenTarg(asn1, mem_ctx, &token->negTokenTarg)) { + token->type = SPNEGO_NEG_TOKEN_TARG; + } + break; + default: + asn1->has_error = true; + break; + } + } + + if (!asn1->has_error) ret = asn1->ofs; + asn1_free(asn1); + + return ret; +} + +ssize_t spnego_write_data(TALLOC_CTX *mem_ctx, DATA_BLOB *blob, struct spnego_data *spnego) +{ + struct asn1_data *asn1 = asn1_init(mem_ctx); + ssize_t ret = -1; + + if (asn1 == NULL) { + return -1; + } + + switch (spnego->type) { + case SPNEGO_NEG_TOKEN_INIT: + asn1_push_tag(asn1, ASN1_APPLICATION(0)); + asn1_write_OID(asn1, GENSEC_OID_SPNEGO); + write_negTokenInit(asn1, &spnego->negTokenInit); + asn1_pop_tag(asn1); + break; + case SPNEGO_NEG_TOKEN_TARG: + write_negTokenTarg(asn1, &spnego->negTokenTarg); + break; + default: + asn1->has_error = true; + break; + } + + if (!asn1->has_error) { + *blob = data_blob_talloc(mem_ctx, asn1->data, asn1->length); + ret = asn1->ofs; + } + asn1_free(asn1); + + return ret; +} + +bool spnego_free_data(struct spnego_data *spnego) +{ + bool ret = true; + + if (!spnego) goto out; + + switch(spnego->type) { + case SPNEGO_NEG_TOKEN_INIT: + if (spnego->negTokenInit.mechTypes) { + talloc_free(spnego->negTokenInit.mechTypes); + } + data_blob_free(&spnego->negTokenInit.mechToken); + data_blob_free(&spnego->negTokenInit.mechListMIC); + talloc_free(spnego->negTokenInit.targetPrincipal); + break; + case SPNEGO_NEG_TOKEN_TARG: + if (spnego->negTokenTarg.supportedMech) { + talloc_free(discard_const(spnego->negTokenTarg.supportedMech)); + } + data_blob_free(&spnego->negTokenTarg.responseToken); + data_blob_free(&spnego->negTokenTarg.mechListMIC); + break; + default: + ret = false; + break; + } + ZERO_STRUCTP(spnego); +out: + return ret; +} + +bool spnego_write_mech_types(TALLOC_CTX *mem_ctx, + const char **mech_types, + DATA_BLOB *blob) +{ + struct asn1_data *asn1 = asn1_init(mem_ctx); + + /* Write mechTypes */ + if (mech_types && *mech_types) { + int i; + + asn1_push_tag(asn1, ASN1_SEQUENCE(0)); + for (i = 0; mech_types[i]; i++) { + asn1_write_OID(asn1, mech_types[i]); + } + asn1_pop_tag(asn1); + } + + if (asn1->has_error) { + asn1_free(asn1); + return false; + } + + *blob = data_blob_talloc(mem_ctx, asn1->data, asn1->length); + if (blob->length != asn1->length) { + asn1_free(asn1); + return false; + } + + asn1_free(asn1); + + return true; +} diff --git a/source4/auth/kerberos/clikrb5.c b/source4/auth/kerberos/clikrb5.c new file mode 100644 index 0000000000..cf87d13cf2 --- /dev/null +++ b/source4/auth/kerberos/clikrb5.c @@ -0,0 +1,113 @@ +/* + Unix SMB/CIFS implementation. + simple kerberos5 routines for active directory + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Luke Howard 2002-2003 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/network.h" +#include "system/kerberos.h" +#include "system/time.h" +#include "auth/kerberos/kerberos.h" + +#ifdef HAVE_KRB5 + +#if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_USE_ENCTYPE) && defined(HAVE_KRB5_STRING_TO_KEY) && defined(HAVE_KRB5_ENCRYPT_BLOCK) + int create_kerberos_key_from_string(krb5_context context, + krb5_principal host_princ, + krb5_data *password, + krb5_keyblock *key, + krb5_enctype enctype) +{ + int ret; + krb5_data salt; + krb5_encrypt_block eblock; + + ret = krb5_principal2salt(context, host_princ, &salt); + if (ret) { + DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret))); + return ret; + } + krb5_use_enctype(context, &eblock, enctype); + ret = krb5_string_to_key(context, &eblock, key, password, &salt); + SAFE_FREE(salt.data); + return ret; +} +#elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT) + int create_kerberos_key_from_string(krb5_context context, + krb5_principal host_princ, + krb5_data *password, + krb5_keyblock *key, + krb5_enctype enctype) +{ + int ret; + krb5_salt salt; + + ret = krb5_get_pw_salt(context, host_princ, &salt); + if (ret) { + DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret))); + return ret; + } + ret = krb5_string_to_key_salt(context, enctype, password->data, + salt, key); + krb5_free_salt(context, salt); + return ret; +} +#else +#error UNKNOWN_CREATE_KEY_FUNCTIONS +#endif + + void kerberos_free_data_contents(krb5_context context, krb5_data *pdata) +{ +#if defined(HAVE_KRB5_FREE_DATA_CONTENTS) + if (pdata->data) { + krb5_free_data_contents(context, pdata); + } +#else + SAFE_FREE(pdata->data); +#endif +} + + krb5_error_code smb_krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *kt_entry) +{ +#if defined(HAVE_KRB5_KT_FREE_ENTRY) + return krb5_kt_free_entry(context, kt_entry); +#elif defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS) + return krb5_free_keytab_entry_contents(context, kt_entry); +#else +#error UNKNOWN_KT_FREE_FUNCTION +#endif +} + + char *smb_get_krb5_error_message(krb5_context context, krb5_error_code code, TALLOC_CTX *mem_ctx) +{ + char *ret; + +#if defined(HAVE_KRB5_GET_ERROR_STRING) && defined(HAVE_KRB5_FREE_ERROR_STRING) + char *context_error = krb5_get_error_string(context); + if (context_error) { + ret = talloc_asprintf(mem_ctx, "%s: %s", error_message(code), context_error); + krb5_free_error_string(context, context_error); + return ret; + } +#endif + ret = talloc_strdup(mem_ctx, error_message(code)); + return ret; +} + +#endif diff --git a/source4/auth/kerberos/config.m4 b/source4/auth/kerberos/config.m4 new file mode 100644 index 0000000000..bf14ca0ee4 --- /dev/null +++ b/source4/auth/kerberos/config.m4 @@ -0,0 +1,540 @@ +# NOTE! this whole m4 file is disabled in configure.in for now + +################################################# +# KRB5 support +KRB5_CFLAGS="" +KRB5_CPPFLAGS="" +KRB5_LDFLAGS="" +KRB5_LIBS="" +with_krb5_support=auto +krb5_withval=auto +AC_MSG_CHECKING([for KRB5 support]) + +# Do no harm to the values of CFLAGS and LIBS while testing for +# Kerberos support. +AC_ARG_WITH(krb5, +[ --with-krb5=base-dir Locate Kerberos 5 support (default=auto)], + [ case "$withval" in + no) + with_krb5_support=no + AC_MSG_RESULT(no) + krb5_withval=no + ;; + yes) + with_krb5_support=yes + AC_MSG_RESULT(yes) + krb5_withval=yes + ;; + auto) + with_krb5_support=auto + AC_MSG_RESULT(auto) + krb5_withval=auto + ;; + *) + with_krb5_support=yes + AC_MSG_RESULT(yes) + krb5_withval=$withval + KRB5CONFIG="$krb5_withval/bin/krb5-config" + ;; + esac ], + AC_MSG_RESULT($with_krb5_support) +) + +if test x$with_krb5_support != x"no"; then + FOUND_KRB5=no + FOUND_KRB5_VIA_CONFIG=no + + ################################################# + # check for krb5-config from recent MIT and Heimdal kerberos 5 + AC_MSG_CHECKING(for working specified location for krb5-config) + if test x$KRB5CONFIG != "x"; then + if test -x "$KRB5CONFIG"; then + ac_save_CFLAGS=$CFLAGS + CFLAGS="";export CFLAGS + ac_save_LDFLAGS=$LDFLAGS + LDFLAGS="";export LDFLAGS + KRB5_LIBS="`$KRB5CONFIG --libs gssapi`" + KRB5_CFLAGS="`$KRB5CONFIG --cflags | sed s/@INCLUDE_des@//`" + KRB5_CPPFLAGS="`$KRB5CONFIG --cflags | sed s/@INCLUDE_des@//`" + CFLAGS=$ac_save_CFLAGS;export CFLAGS + LDFLAGS=$ac_save_LDFLAGS;export LDFLAGS + FOUND_KRB5=yes + FOUND_KRB5_VIA_CONFIG=yes + AC_MSG_RESULT(yes. Found $KRB5CONFIG) + else + AC_MSG_RESULT(no. Fallback to specified directory) + fi + else + AC_MSG_RESULT(no. Fallback to finding krb5-config in path) + ################################################# + # check for krb5-config from recent MIT and Heimdal kerberos 5 + AC_PATH_PROG(KRB5CONFIG, krb5-config) + AC_MSG_CHECKING(for working krb5-config in path) + if test -x "$KRB5CONFIG"; then + ac_save_CFLAGS=$CFLAGS + CFLAGS="";export CFLAGS + ac_save_LDFLAGS=$LDFLAGS + LDFLAGS="";export LDFLAGS + KRB5_LIBS="`$KRB5CONFIG --libs gssapi`" + KRB5_CFLAGS="`$KRB5CONFIG --cflags | sed s/@INCLUDE_des@//`" + KRB5_CPPFLAGS="`$KRB5CONFIG --cflags | sed s/@INCLUDE_des@//`" + CFLAGS=$ac_save_CFLAGS;export CFLAGS + LDFLAGS=$ac_save_LDFLAGS;export LDFLAGS + FOUND_KRB5=yes + FOUND_KRB5_VIA_CONFIG=yes + AC_MSG_RESULT(yes. Found $KRB5CONFIG) + else + AC_MSG_RESULT(no. Fallback to previous krb5 detection strategy) + fi + fi + + if test x$FOUND_KRB5 != x"yes"; then + ################################################# + # check for location of Kerberos 5 install + AC_MSG_CHECKING(for kerberos 5 install path) + case "$krb5_withval" in + no) + AC_MSG_RESULT(no krb5-path given) + ;; + yes) + AC_MSG_RESULT(/usr) + FOUND_KRB5=yes + ;; + *) + AC_MSG_RESULT($krb5_withval) + KRB5_CFLAGS="-I$krb5_withval/include" + KRB5_CPPFLAGS="-I$krb5_withval/include" + KRB5_LDFLAGS="-L$krb5_withval/lib" + FOUND_KRB5=yes + ;; + esac + fi + + if test x$FOUND_KRB5 != x"yes"; then + ################################################# + # see if this box has the SuSE location for the heimdal krb implementation + AC_MSG_CHECKING(for /usr/include/heimdal) + if test -d /usr/include/heimdal; then + if test -f /usr/lib/heimdal/lib/libkrb5.a; then + KRB5_CFLAGS="-I/usr/include/heimdal" + KRB5_CPPFLAGS="-I/usr/include/heimdal" + KRB5_LDFLAGS="-L/usr/lib/heimdal/lib" + AC_MSG_RESULT(yes) + else + KRB5_CFLAGS="-I/usr/include/heimdal" + KRB5_CPPFLAGS="-I/usr/include/heimdal" + AC_MSG_RESULT(yes) + fi + else + AC_MSG_RESULT(no) + fi + fi + + if test x$FOUND_KRB5 != x"yes"; then + ################################################# + # see if this box has the RedHat location for kerberos + AC_MSG_CHECKING(for /usr/kerberos) + if test -d /usr/kerberos -a -f /usr/kerberos/lib/libkrb5.a; then + KRB5_LDFLAGS="-L/usr/kerberos/lib" + KRB5_CFLAGS="-I/usr/kerberos/include" + KRB5_CPPFLAGS="-I/usr/kerberos/include" + AC_MSG_RESULT(yes) + else + AC_MSG_RESULT(no) + fi + fi + + ac_save_CFLAGS=$CFLAGS + ac_save_CPPFLAGS=$CPPFLAGS + ac_save_LDFLAGS=$LDFLAGS + + #MIT needs this, to let us see 'internal' parts of the headers we use + KRB5_CFLAGS="${KRB5_CFLAGS} -DKRB5_PRIVATE -DKRB5_DEPRECATED" + + #Heimdal needs this + #TODO: we need to parse KRB5_LIBS for -L path + # and set -Wl,-rpath -Wl,path + + CFLAGS="$CFLAGS $KRB5_CFLAGS" + CPPFLAGS="$CPPFLAGS $KRB5_CPPFLAGS" + LDFLAGS="$LDFLAGS $KRB5_LDFLAGS" + + KRB5_LIBS="$KRB5_LDFLAGS $KRB5_LIBS" + + # now check for krb5.h. Some systems have the libraries without the headers! + # note that this check is done here to allow for different kerberos + # include paths + AC_CHECK_HEADERS(krb5.h) + + if test x"$ac_cv_header_krb5_h" = x"no"; then + # Give a warning if KRB5 support was not explicitly requested, + # i.e with_krb5_support = auto, otherwise die with an error. + if test x"$with_krb5_support" = x"yes"; then + AC_MSG_ERROR([KRB5 cannot be supported without krb5.h]) + else + AC_MSG_WARN([KRB5 cannot be supported without krb5.h]) + fi + # Turn off AD support and restore CFLAGS and LIBS variables + with_krb5_support="no" + fi + + CFLAGS=$ac_save_CFLAGS + CPPFLAGS=$ac_save_CPPFLAGS + LDFLAGS=$ac_save_LDFLAGS +fi + +# Now we have determined whether we really want KRB5 support + +if test x"$with_krb5_support" != x"no"; then + ac_save_CFLAGS=$CFLAGS + ac_save_CPPFLAGS=$CPPFLAGS + ac_save_LDFLAGS=$LDFLAGS + ac_save_LIBS=$LIBS + + CFLAGS="$CFLAGS $KRB5_CFLAGS" + CPPFLAGS="$CPPFLAGS $KRB5_CPPFLAGS" + LDFLAGS="$LDFLAGS $KRB5_LDFLAGS" + + # now check for gssapi headers. This is also done here to allow for + # different kerberos include paths + AC_CHECK_HEADERS(gssapi.h gssapi_krb5.h gssapi/gssapi.h gssapi/gssapi_generic.h gssapi/gssapi_krb5.h com_err.h) + + + # Heimdal checks. + # But only if we didn't have a krb5-config to tell us this already + if test x"$FOUND_KRB5_VIA_CONFIG" != x"yes"; then + ################################################################## + # we might need the k5crypto and com_err libraries on some systems + AC_CHECK_LIB_EXT(com_err, KRB5_LIBS, _et_list) + AC_CHECK_LIB_EXT(k5crypto, KRB5_LIBS, krb5_encrypt_data) + + AC_CHECK_LIB_EXT(crypto, KRB5_LIBS, des_set_key) + AC_CHECK_LIB_EXT(asn1, KRB5_LIBS, copy_Authenticator) + AC_CHECK_LIB_EXT(roken, KRB5_LIBS, roken_getaddrinfo_hostspec) + fi + + # Heimdal checks. On static Heimdal gssapi must be linked before krb5. + AC_CHECK_LIB_EXT(gssapi, KRB5_LIBS, gss_display_status,[],[], + AC_DEFINE(HAVE_GSSAPI,1,[Whether GSSAPI is available])) + + ######################################################## + # now see if we can find the krb5 libs in standard paths + # or as specified above + AC_CHECK_LIB_EXT(krb5, KRB5_LIBS, krb5_mk_req_extended) + AC_CHECK_LIB_EXT(krb5, KRB5_LIBS, krb5_kt_compare) + + ######################################################## + # now see if we can find the gssapi libs in standard paths + if test x"$ac_cv_lib_ext_gssapi_gss_display_status" != x"yes"; then + AC_CHECK_LIB_EXT(gssapi_krb5, KRB5_LIBS,gss_display_status,[],[], + AC_DEFINE(HAVE_GSSAPI,1,[Whether GSSAPI is available])) + fi + + AC_CHECK_FUNC_EXT(krb5_set_real_time, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_set_default_in_tkt_etypes, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_set_default_tgs_ktypes, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_principal2salt, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_use_enctype, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_string_to_key, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_get_pw_salt, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_string_to_key_salt, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_auth_con_setkey, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_auth_con_setuseruserkey, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_locate_kdc, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_get_permitted_enctypes, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_get_default_in_tkt_etypes, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_free_ktypes, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_free_data_contents, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_principal_get_comp_string, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_free_unparsed_name, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_free_keytab_entry_contents, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_kt_free_entry, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_krbhst_get_addrinfo, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_verify_checksum, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_c_verify_checksum, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_ticket_get_authorization_data_type, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_krbhst_get_addrinfo, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_c_enctype_compare, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_enctypes_compatible_keys, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_get_error_string, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_free_error_string, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_initlog, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_addlog_func, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(krb5_set_warn_dest, $KRB5_LIBS) + + LIBS="$LIBS $KRB5_LIBS" + + AC_CACHE_CHECK([for krb5_log_facility type], + samba_cv_HAVE_KRB5_LOG_FACILITY,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_log_facility block;], + samba_cv_HAVE_KRB5_LOG_FACILITY=yes, + samba_cv_HAVE_KRB5_LOG_FACILITY=no)]) + + if test x"$samba_cv_HAVE_KRB5_LOG_FACILITY" = x"yes"; then + AC_DEFINE(HAVE_KRB5_LOG_FACILITY,1, + [Whether the type krb5_log_facility exists]) + fi + + AC_CACHE_CHECK([for krb5_encrypt_block type], + samba_cv_HAVE_KRB5_ENCRYPT_BLOCK,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_encrypt_block block;], + samba_cv_HAVE_KRB5_ENCRYPT_BLOCK=yes, + samba_cv_HAVE_KRB5_ENCRYPT_BLOCK=no)]) + + if test x"$samba_cv_HAVE_KRB5_ENCRYPT_BLOCK" = x"yes"; then + AC_DEFINE(HAVE_KRB5_ENCRYPT_BLOCK,1, + [Whether the type krb5_encrypt_block exists]) + fi + + AC_CACHE_CHECK([for addrtype in krb5_address], + samba_cv_HAVE_ADDRTYPE_IN_KRB5_ADDRESS,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_address kaddr; kaddr.addrtype = ADDRTYPE_INET;], + samba_cv_HAVE_ADDRTYPE_IN_KRB5_ADDRESS=yes, + samba_cv_HAVE_ADDRTYPE_IN_KRB5_ADDRESS=no)]) + if test x"$samba_cv_HAVE_ADDRTYPE_IN_KRB5_ADDRESS" = x"yes"; then + AC_DEFINE(HAVE_ADDRTYPE_IN_KRB5_ADDRESS,1, + [Whether the krb5_address struct has a addrtype property]) + fi + + AC_CACHE_CHECK([for addr_type in krb5_address], + samba_cv_HAVE_ADDR_TYPE_IN_KRB5_ADDRESS,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_address kaddr; kaddr.addr_type = KRB5_ADDRESS_INET;], + samba_cv_HAVE_ADDR_TYPE_IN_KRB5_ADDRESS=yes, + samba_cv_HAVE_ADDR_TYPE_IN_KRB5_ADDRESS=no)]) + if test x"$samba_cv_HAVE_ADDR_TYPE_IN_KRB5_ADDRESS" = x"yes"; then + AC_DEFINE(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS,1, + [Whether the krb5_address struct has a addr_type property]) + fi + + AC_CACHE_CHECK([for enc_part2 in krb5_ticket], + samba_cv_HAVE_KRB5_TKT_ENC_PART2,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_ticket tkt; tkt.enc_part2->authorization_data[0]->contents = NULL;], + samba_cv_HAVE_KRB5_TKT_ENC_PART2=yes, + samba_cv_HAVE_KRB5_TKT_ENC_PART2=no)]) + if test x"$samba_cv_HAVE_KRB5_TKT_ENC_PART2" = x"yes"; then + AC_DEFINE(HAVE_KRB5_TKT_ENC_PART2,1, + [Whether the krb5_ticket struct has a enc_part2 property]) + fi + + AC_CACHE_CHECK([for keyblock in krb5_creds], + samba_cv_HAVE_KRB5_KEYBLOCK_IN_CREDS,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_creds creds; krb5_keyblock kb; creds.keyblock = kb;], + samba_cv_HAVE_KRB5_KEYBLOCK_IN_CREDS=yes, + samba_cv_HAVE_KRB5_KEYBLOCK_IN_CREDS=no)]) + + if test x"$samba_cv_HAVE_KRB5_KEYBLOCK_IN_CREDS" = x"yes"; then + AC_DEFINE(HAVE_KRB5_KEYBLOCK_IN_CREDS,1, + [Whether the krb5_creds struct has a keyblock property]) + fi + + AC_CACHE_CHECK([for session in krb5_creds], + samba_cv_HAVE_KRB5_SESSION_IN_CREDS,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_creds creds; krb5_keyblock kb; creds.session = kb;], + samba_cv_HAVE_KRB5_SESSION_IN_CREDS=yes, + samba_cv_HAVE_KRB5_SESSION_IN_CREDS=no)]) + + if test x"$samba_cv_HAVE_KRB5_SESSION_IN_CREDS" = x"yes"; then + AC_DEFINE(HAVE_KRB5_SESSION_IN_CREDS,1, + [Whether the krb5_creds struct has a session property]) + fi + + AC_CACHE_CHECK([for keyvalue in krb5_keyblock], + samba_cv_HAVE_KRB5_KEYBLOCK_KEYVALUE,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_keyblock key; key.keyvalue.data = NULL;], + samba_cv_HAVE_KRB5_KEYBLOCK_KEYVALUE=yes, + samba_cv_HAVE_KRB5_KEYBLOCK_KEYVALUE=no)]) + if test x"$samba_cv_HAVE_KRB5_KEYBLOCK_KEYVALUE" = x"yes"; then + AC_DEFINE(HAVE_KRB5_KEYBLOCK_KEYVALUE,1, + [Whether the krb5_keyblock struct has a keyvalue property]) + fi + + AC_CACHE_CHECK([for ENCTYPE_ARCFOUR_HMAC_MD5], + samba_cv_HAVE_ENCTYPE_ARCFOUR_HMAC_MD5,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_enctype enctype; enctype = ENCTYPE_ARCFOUR_HMAC_MD5;], + samba_cv_HAVE_ENCTYPE_ARCFOUR_HMAC_MD5=yes, + samba_cv_HAVE_ENCTYPE_ARCFOUR_HMAC_MD5=no)]) + AC_CACHE_CHECK([for KEYTYPE_ARCFOUR_56], + samba_cv_HAVE_KEYTYPE_ARCFOUR_56,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_keytype keytype; keytype = KEYTYPE_ARCFOUR_56;], + samba_cv_HAVE_KEYTYPE_ARCFOUR_56=yes, + samba_cv_HAVE_KEYTYPE_ARCFOUR_56=no)]) + # Heimdals with KEYTYPE_ARCFOUR but not KEYTYPE_ARCFOUR_56 are broken + # w.r.t. arcfour and windows, so we must not enable it here + if test x"$samba_cv_HAVE_ENCTYPE_ARCFOUR_HMAC_MD5" = x"yes" -a\ + x"$samba_cv_HAVE_KEYTYPE_ARCFOUR_56" = x"yes"; then + AC_DEFINE(HAVE_ENCTYPE_ARCFOUR_HMAC_MD5,1, + [Whether the ENCTYPE_ARCFOUR_HMAC_MD5 key type is available]) + fi + + AC_CACHE_CHECK([for AP_OPTS_USE_SUBKEY], + samba_cv_HAVE_AP_OPTS_USE_SUBKEY,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_flags ap_options; ap_options = AP_OPTS_USE_SUBKEY;], + samba_cv_HAVE_AP_OPTS_USE_SUBKEY=yes, + samba_cv_HAVE_AP_OPTS_USE_SUBKEY=no)]) + if test x"$samba_cv_HAVE_AP_OPTS_USE_SUBKEY" = x"yes"; then + AC_DEFINE(HAVE_AP_OPTS_USE_SUBKEY,1, + [Whether the AP_OPTS_USE_SUBKEY ap option is available]) + fi + + AC_CACHE_CHECK([for KV5M_KEYTAB], + samba_cv_HAVE_KV5M_KEYTAB,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_keytab_entry entry; entry.magic = KV5M_KEYTAB;], + samba_cv_HAVE_KV5M_KEYTAB=yes, + samba_cv_HAVE_KV5M_KEYTAB=no)]) + if test x"$samba_cv_HAVE_KV5M_KEYTAB" = x"yes"; then + AC_DEFINE(HAVE_KV5M_KEYTAB,1, + [Whether the KV5M_KEYTAB option is available]) + fi + + AC_CACHE_CHECK([for the krb5_princ_component macro], + samba_cv_HAVE_KRB5_PRINC_COMPONENT,[ + AC_TRY_LINK([#include <krb5.h>], + [const krb5_data *pkdata; krb5_context context; krb5_principal principal; + pkdata = krb5_princ_component(context, principal, 0);], + samba_cv_HAVE_KRB5_PRINC_COMPONENT=yes, + samba_cv_HAVE_KRB5_PRINC_COMPONENT=no)]) + if test x"$samba_cv_HAVE_KRB5_PRINC_COMPONENT" = x"yes"; then + AC_DEFINE(HAVE_KRB5_PRINC_COMPONENT,1, + [Whether krb5_princ_component is available]) + fi + + AC_CACHE_CHECK([for key in krb5_keytab_entry], + samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEY,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_keytab_entry entry; krb5_keyblock e; entry.key = e;], + samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEY=yes, + samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEY=no)]) + if test x"$samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEY" = x"yes"; then + AC_DEFINE(HAVE_KRB5_KEYTAB_ENTRY_KEY,1, + [Whether krb5_keytab_entry has key member]) + fi + + AC_CACHE_CHECK([for keyblock in krb5_keytab_entry], + samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_keytab_entry entry; entry.keyblock.keytype = 0;], + samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK=yes, + samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK=no)]) + if test x"$samba_cv_HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK" = x"yes"; then + AC_DEFINE(HAVE_KRB5_KEYTAB_ENTRY_KEYBLOCK,1, + [Whether krb5_keytab_entry has keyblock member]) + fi + + AC_CACHE_CHECK([for WRFILE: keytab support], + samba_cv_HAVE_WRFILE_KEYTAB,[ + AC_TRY_RUN([ + #include<krb5.h> + main() + { + krb5_context context; + krb5_keytab keytab; + krb5_init_context(&context); + return krb5_kt_resolve(context, "WRFILE:api", &keytab); + }], + samba_cv_HAVE_WRFILE_KEYTAB=yes, + samba_cv_HAVE_WRFILE_KEYTAB=no)]) + if test x"$samba_cv_HAVE_WRFILE_KEYTAB" = x"yes"; then + AC_DEFINE(HAVE_WRFILE_KEYTAB,1, + [Whether the WRFILE:-keytab is supported]) + fi + + AC_CACHE_CHECK([for krb5_princ_realm returns krb5_realm or krb5_data], + samba_cv_KRB5_PRINC_REALM_RETURNS_REALM,[ + AC_TRY_COMPILE([#include <krb5.h>], + [krb5_context context;krb5_principal principal;krb5_realm realm; + realm = *krb5_princ_realm(context, principal);], + samba_cv_KRB5_PRINC_REALM_RETURNS_REALM=yes, + samba_cv_KRB5_PRINC_REALM_RETURNS_REALM=no)]) + if test x"$samba_cv_KRB5_PRINC_REALM_RETURNS_REALM" = x"yes"; then + AC_DEFINE(KRB5_PRINC_REALM_RETURNS_REALM,1, + [Whether krb5_princ_realm returns krb5_realm or krb5_data]) + fi + + # TODO: check all gssapi headers for this + AC_CACHE_CHECK([for GSS_C_DCE_STYLE in gssapi.h], + samba_cv_GSS_C_DCE_STYLE,[ + AC_TRY_COMPILE([#include <gssapi.h>], + [int flags = GSS_C_DCE_STYLE;], + samba_cv_GSS_C_DCE_STYLE=yes, + samba_cv_GSS_C_DCE_STYLE=no)]) + + AC_CHECK_FUNC_EXT(gsskrb5_get_initiator_subkey, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(gsskrb5_extract_authz_data_from_sec_context, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(gsskrb5_register_acceptor_identity, $KRB5_LIBS) + AC_CHECK_FUNC_EXT(gss_krb5_ccache_name, $KRB5_LIBS) + if test x"$ac_cv_lib_ext_krb5_krb5_mk_req_extended" = x"yes"; then + AC_DEFINE(HAVE_KRB5,1,[Whether to have KRB5 support]) + AC_MSG_CHECKING(whether KRB5 support is used) + SMB_ENABLE(KRB5,YES) + AC_MSG_RESULT(yes) + echo "KRB5_CFLAGS: ${KRB5_CFLAGS}" + echo "KRB5_CPPFLAGS: ${KRB5_CPPFLAGS}" + echo "KRB5_LDFLAGS: ${KRB5_LDFLAGS}" + echo "KRB5_LIBS: ${KRB5_LIBS}" + else + if test x"$with_krb5_support" = x"yes"; then + AC_MSG_ERROR(a working krb5 library is needed for KRB5 support) + else + AC_MSG_WARN(a working krb5 library is needed for KRB5 support) + fi + KRB5_CFLAGS="" + KRB5_CPPFLAGS="" + KRB5_LDFLAGS="" + KRB5_LIBS="" + with_krb5_support=no + fi + + # checks if we have access to a libkdc + # and can use it for our builtin kdc server_service + KDC_CFLAGS="" + KDC_CPPFLAGS="" + KDC_DLFLAGS="" + KDC_LIBS="" + AC_CHECK_HEADERS(kdc.h) + AC_CHECK_LIB_EXT(kdc, KDC_LIBS, krb5_kdc_default_config) + AC_CHECK_LIB_EXT(hdb, KDC_LIBS, hdb_generate_key_set_password) + + AC_MSG_CHECKING(whether libkdc is used) + if test x"$ac_cv_header_kdc_h" = x"yes"; then + if test x"$ac_cv_lib_ext_kdc_krb5_kdc_default_config" = x"yes"; then + if test x"$ac_cv_lib_ext_hdb_hdb_generate_key_set_password" = x"yes"; then + SMB_ENABLE(KDC,YES) + AC_MSG_RESULT(yes) + echo "KDC_LIBS: ${KDC_LIBS}" + else + AC_MSG_RESULT(no) + fi + else + AC_MSG_RESULT(no) + fi + else + AC_MSG_RESULT(no) + fi + + CFLAGS=$ac_save_CFLAGS + CPPFLAGS=$ac_save_CPPFLAGS + LDFLAGS=$ac_save_LDFLAGS + LIBS="$ac_save_LIBS" + + # as a nasty hack add the krb5 stuff to the global vars, + # at some point this should not be needed anymore when the build system + # can handle that alone + CFLAGS="$CFLAGS $KRB5_CFLAGS" + CPPFLAGS="$CPPFLAGS $KRB5_CPPFLAGS" + LDFLAGS="$LDFLAGS $KRB5_LDFLAGS" +fi + +SMB_EXT_LIB(KRB5,[${KRB5_LIBS}],[${KRB5_CFLAGS}],[${KRB5_CPPFLAGS}],[${KRB5_LDFLAGS}]) +SMB_EXT_LIB(KDC,[${KDC_LIBS}],[${KDC_CFLAGS}],[${KDC_CPPFLAGS}],[${KDC_LDFLAGS}]) diff --git a/source4/auth/kerberos/config.mk b/source4/auth/kerberos/config.mk new file mode 100644 index 0000000000..951e247258 --- /dev/null +++ b/source4/auth/kerberos/config.mk @@ -0,0 +1,18 @@ +################################# +# Start SUBSYSTEM KERBEROS +[SUBSYSTEM::KERBEROS] +PUBLIC_DEPENDENCIES = HEIMDAL_KRB5 NDR_KRB5PAC samba-socket LIBCLI_RESOLVE +PRIVATE_DEPENDENCIES = ASN1_UTIL auth_sam_reply LIBPACKET LIBNDR +# End SUBSYSTEM KERBEROS +################################# + +KERBEROS_OBJ_FILES = $(addprefix $(authsrcdir)/kerberos/, \ + kerberos.o \ + clikrb5.o \ + kerberos_heimdal.o \ + kerberos_pac.o \ + gssapi_parse.o \ + krb5_init_context.o) + +$(eval $(call proto_header_template,$(authsrcdir)/kerberos/proto.h,$(KERBEROS_OBJ_FILES:.o=.c))) + diff --git a/source4/auth/kerberos/gssapi_parse.c b/source4/auth/kerberos/gssapi_parse.c new file mode 100644 index 0000000000..77e907d3fa --- /dev/null +++ b/source4/auth/kerberos/gssapi_parse.c @@ -0,0 +1,123 @@ +/* + Unix SMB/CIFS implementation. + + simple GSSAPI wrappers + + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2002 + Copyright (C) Luke Howard 2003 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/util/asn1.h" +#include "auth/gensec/gensec.h" + +/* + generate a krb5 GSS-API wrapper packet given a ticket +*/ +DATA_BLOB gensec_gssapi_gen_krb5_wrap(TALLOC_CTX *mem_ctx, const DATA_BLOB *ticket, const uint8_t tok_id[2]) +{ + struct asn1_data *data; + DATA_BLOB ret; + + if (!data || !ticket->data) { + return data_blob(NULL,0); + } + + data = asn1_init(mem_ctx); + if (data == NULL) { + return data_blob(NULL,0); + } + + asn1_push_tag(data, ASN1_APPLICATION(0)); + asn1_write_OID(data, GENSEC_OID_KERBEROS5); + + asn1_write(data, tok_id, 2); + asn1_write(data, ticket->data, ticket->length); + asn1_pop_tag(data); + + if (data->has_error) { + DEBUG(1,("Failed to build krb5 wrapper at offset %d\n", (int)data->ofs)); + asn1_free(data); + return data_blob(NULL,0); + } + + ret = data_blob_talloc(mem_ctx, data->data, data->length); + asn1_free(data); + + return ret; +} + +/* + parse a krb5 GSS-API wrapper packet giving a ticket +*/ +bool gensec_gssapi_parse_krb5_wrap(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, DATA_BLOB *ticket, uint8_t tok_id[2]) +{ + bool ret; + struct asn1_data *data = asn1_init(mem_ctx); + int data_remaining; + + if (!data) { + return false; + } + + asn1_load(data, *blob); + asn1_start_tag(data, ASN1_APPLICATION(0)); + asn1_check_OID(data, GENSEC_OID_KERBEROS5); + + data_remaining = asn1_tag_remaining(data); + + if (data_remaining < 3) { + data->has_error = true; + } else { + asn1_read(data, tok_id, 2); + data_remaining -= 2; + *ticket = data_blob_talloc(mem_ctx, NULL, data_remaining); + asn1_read(data, ticket->data, ticket->length); + } + + asn1_end_tag(data); + + ret = !data->has_error; + + asn1_free(data); + + return ret; +} + + +/* + check a GSS-API wrapper packet givin an expected OID +*/ +bool gensec_gssapi_check_oid(const DATA_BLOB *blob, const char *oid) +{ + bool ret; + struct asn1_data *data = asn1_init(NULL); + + if (!data) return false; + + asn1_load(data, *blob); + asn1_start_tag(data, ASN1_APPLICATION(0)); + asn1_check_OID(data, oid); + + ret = !data->has_error; + + asn1_free(data); + + return ret; +} + + diff --git a/source4/auth/kerberos/kerberos-notes.txt b/source4/auth/kerberos/kerberos-notes.txt new file mode 100644 index 0000000000..43881a20d3 --- /dev/null +++ b/source4/auth/kerberos/kerberos-notes.txt @@ -0,0 +1,466 @@ +AllowedWorkstationNames and Krb5 +-------------------------------- + +Microsoft uses the clientAddresses *multiple value* field in the krb5 +protocol (particularly the AS_REQ) to communicate it's netbios name. +This is (my guess) to permit the userWorkstations field to work. + +The KDC I imagine checks the netbios address against this value, in +the same way that the Samba server does this. + +The checking of this implies a little of the next question: + +Is a DAL the layer we need? +--------------------------- + +Looking at what we need to pass around, I start to seriously wonder if +the DAL is even the right layer - we seem to want to create an account +authorization abstraction layer - is this account permitted to login to +this computer, at this time? + +This information in AD is much richer than the Heimdal HDB, and it +seems to make sense to do AD-specific access control checks in an +AD-specific layer, not in the back-end agnostic server. + +Because the DAL only reads in the principalName as the key, it has +trouble performing access control decisions on things other than the +name. + +I'll be very interested if the DAL really works for eDirectory too. +Perhaps all we need to do is add in the same kludges as we have in +Samba 3.0 for eDirectory. Hmm... + +That said, the current layer provides us with a very good start, and +any redefinition would occour from that basis. + + +GSSAPI layer requirements +------------------------- + +Welcome to the wonderful world of canonicalisation + +The MIT GSSAPI libs do not support kinit returning a different +realm to what the client asked for, even just in case differences. + +Heimdal has the same problem, and this applies to the krb5 layer, not +just gssapi. + +We need to test if the canonicalisation is controlled by the KDCOption +flags, windows always sends the Canonicalize flags + +Old Clients (samba3 and HPUX clients) uses 'selfmade' gssapi/krb5 +for using it in the CIFS session setup. Because they use krb5_mk_req() +they get a chksum field depending on the encryption type, but that's wrong +for GSSAPI (see rfc 1964 section 1.1.1). The Cheksum type 8003 +should be used in the Authenticator of the AP-REQ! That allows the channel bindings, +the GCC_C_* req_flags and optional delegation tickets to be passed from the client to the server. +Hower windows doesn't seems to care about if the checksum is of the wrong type, +for CIFS SessionSetups, it seems that the req_flags are just set to 0. +So this can't work for LDAP connections with sign or seal, or for any DCERPC +connection. + +So we need to also support old clients! + +Principal Names, long and short names +------------------------------------- + +As far as servicePrincipalNames are concerned, these are not +canonicalised, except as regards the realm in the reply. That is, the +client gets back the principal it asked for, with the realm portion +'fixed' to uppercase, long form. + +The short name of the realm seems to be accepted for at least AS_REQ +operations, but because the server performs canonicalisation, this +causes pain for current client libraries. + +The canonicalisation of names matters not only for the KDC, but also +for code that has to deal with keytabs. + +We also need to handle type 10 names (NT-ENTERPRISE), which are a full +principal name in the principal field, unrelated to the realm. + +HOST/ Aliases +------------- + +There is another post somewhere (ref lost for the moment) that details +where in active directory the list of stored aliases for HOST/ is. +This should be read, parsed and used to allow any of these requests to +use the HOST/ key. + +For example, this is how HTTP/, DNS/ and CIFS/ can use HOST/ without +any explicit entry. + + +Jean-Baptiste.Marchand@hsc.fr reminds me: + +> This is the SPNMappings attribute in Active Directory: + +> http://msdn.microsoft.com/library/en-us/adschema/adschema/a_spnmappings.asp + +We implement this in hdb-ldb. + +Implicit names for Win2000 Accounts +----------------------------------- + +Despite not having a DNS name, nor a servicePrincipalName on accounts +created by computers running win2000, it appears we are expected to +have an implicit mapping from host/computer.full.name and +host/computer to it's entry. + +Returned Salt for PreAuthentication +----------------------------------- + +When the server replies for pre-authentication, it returns the Salt, +which may be in the form of a principalName that is in no way +connected with the current names. (ie, even if the userPrincipalName +and samAccountName are renamed, the old salt is returned). + +This is probably the kerberos standard salt, kept in the 'Key'. The +standard generation rules are found in a Mail from Luke Howard dated +10 Nov 2004: + + +From: Luke Howard <lukeh@padl.com> +Message-Id: <200411100231.iAA2VLUW006101@au.padl.com> +MIME-Version: 1.0 +Content-Type: text/plain; charset=US-ASCII +Organization: PADL Software Pty Ltd +To: lukeh@padl.com +Date: Wed, 10 Nov 2004 13:31:21 +1100 +Versions: dmail (bsd44) 2.6d/makemail 2.10 +Cc: huaraz@moeller.plus.com, samba-technical@lists.samba.org +Subject: Re: Samba-3.0.7-1.3E Active Directory Issues +X-BeenThere: samba-technical@lists.samba.org +X-Mailman-Version: 2.1.4 +Precedence: list +Reply-To: lukeh@padl.com + +Did some more testing, it appears the behaviour has another +explanation. It appears that the standard Kerberos password salt +algorithm is applied in Windows 2003, just that the source principal +name is different. + +Here is what I've been able to deduce from creating a bunch of +different accounts: + +Type of account Principal for Salting +======================================================================== +Computer Account host/<SAM-Name-Without-$>.realm@REALM +User Account Without UPN <SAM-Name>@REALM +User Account With UPN <LHS-Of-UPN>@REALM + +Note that if the computer account's SAM account name does not include +the trailing '$', then the entire SAM account name is used as input to +the salting principal. Setting a UPN for a computer account has no +effect. + +It seems to me odd that the RHS of the UPN is not used in the salting +principal. For example, a user with UPN foo@mydomain.com in the realm +MYREALM.COM would have a salt of MYREALM.COMfoo. Perhaps this is to +allow a user's UPN suffix to be changed without changing the salt. And +perhaps using the UPN for salting signifies a move away SAM names and +their associated constraints. + +For more information on how UPNs relate to the Kerberos protocol, +see: + +http://www.ietf.org/proceedings/01dec/I-D/draft-ietf-krb-wg-kerberos-referrals-02.txt + +-- Luke + +-- + + + + +Heimdal oddities +---------------- + +Heimdal is built such that it should be able to serve multiple realms +at the same time. This isn't relevant for Samba's use, but it shows +up in a lot of generalisations throughout the code. + +Other odd things: + - Support for multiple passwords on a client account: we seem to + call hdb_next_enctype2key() in the pre-authentication routines to + allow multiple passwords per account in krb5. (I think this was + intened to allow multiple salts) + +State Machine safety +-------------------- + +Samba is a giant state machine, and as such have very different +requirements to those traditionally expressed for kerberos and GSSAPI +libraries. + +Samba requires all of the libraries it uses to be state machine safe in +their use of internal data. This does not mean thread safe, and an +application could be thread safe, but not state machine safe (if it +instead used thread-local variables). + +So, what does it mean for a library to be state machine safe? This is +mostly a question of context, and how the library manages whatever +internal state machines it has. If the library uses a context +variable, passed in by the caller, which contains all the information +about the current state of the library, then it is safe. An example +of this state is the sequence number and session keys for an ongoing +encrypted session). + +The other issue affecting state machines is 'blocking' (waiting for a +read on a network socket). + +Heimdal has this 'state machine safety' in parts, and we have modified +the lorikeet branch to improve this behviour, when using a new, +non-standard API. + +Heimdal uses a per-context variable for the 'krb5_auth_context', which +controls the ongoing encrypted connection, but does use global +variables for the ubiquitous krb5_context parameter. + +The modification that has added most to 'state machine safety' of +GSSAPI is the addition of the gsskrb5_acquire_creds function. This +allows the caller to specify a keytab and ccache, for use by the +GSSAPI code. Therefore there is no need to use global variables to +communicate this information. + +At a more theoritical level (simply counting static and global +variables) Heimdal is not state machine safe for the GSSAPI layer. +The Krb5 layer alone is much closer, as far as I can tell, blocking +excepted. . + +To deal with blocking, we could have a fork()ed child per context, +using the 'GSSAPI export context' function to transfer +the GSSAPI state back into the main code for the wrap()/unwrap() part +of the operation. This will still hit issues of static storage (one +gss_krb5_context per process, and multiple GSSAPI encrypted sessions +at a time) but these may not matter in practice. + +In the short-term, we deal with blocking by taking over the network +send() and recv() functions, therefore making them 'semi-async'. This +doens't apply to DNS yet. + +GSSAPI and Kerberos extensions +------------------------------ + +This is a general list of the other extensions we have made to / need from +the kerberos libraries + + - DCE_STYLE + + - gsskrb5_get_initiator_subkey() (return the exact key that Samba3 + has always asked for. gsskrb5_get_subkey() might do what we need + anyway) + + - gsskrb5_acquire_creds() (takes keytab and/or ccache as input + parameters, see keytab and state machine discussion) + + - gss_krb5_copy_service_keyblock() (get the key used to actually + encrypt the ticket to the server, because the same key is used for + the PAC validation). + - gsskrb5_extract_authtime_from_sec_context (get authtime from + kerberos ticket) + - gsskrb5_extract_authz_data_from_sec_context (get authdata from + ticket, ie the PAC. Must unwrap the data if in an AD-IFRELEVENT) + - gsskrb5_wrap_size (find out how big the wrapped packet will be, + given input length). + +Keytab requirements +------------------- + +Because windows machine account handling is very different to the +tranditional 'MIT' keytab operation. This starts when we look at the +basis of the secrets handling: + +Traditional 'MIT' behaviour is to use a keytab, continaing salted key +data, extracted from the KDC. (In this modal, there is no 'service +password', instead the keys are often simply application of random +bytes). Heimdal also implements this behaviour. + +The windows modal is very different - instead of sharing a keytab with +each member server, a password is stored for the whole machine. The +password is set with non-kerberos mechanisms (particularly SAMR, a +DCE-RPC service) and when interacting on a kerberos basis, the +password is salted by the client. (That is, no salt infromation +appears to be convayed from the KDC to the member). + +In dealing with this modal, we leverage both the traditional file +keytab and in-MEMORY keytabs. + +When dealing with a windows KDC, the behaviour regarding case +sensitivity and canonacolisation must be accomidated. This means that +an incoming request to a member server may have a wide variety of +service principal names. These include: + +machine$@REALM (samba clients) +HOST/foo.bar@realm (win2k clients) +HOST/foo@realm (win2k clients, using netbios) +cifs/foo.bar@realm (winxp clients) +cifs/foo@realm (winxp clients, using netbios) + +as well as all case variations on the above. + +Because that all got 'too hard' to put into a keytab in the +traditional way (with the client to specify the name), we either +pre-compute the keys into a traditional keytab or make an in-MEMORY +keytab at run time. In both cases we specifiy the principal name to +GSSAPI, which avoids the need to store duplicate principals. + +We use a 'private' keytab in our private dir, referenced from the +secrets.ldb by default. + +Extra Heimdal functions used +---------------------------- +(an attempt to list some of the Heimdal-specific functions I know we use) + +krb5_free_keyblock_contents() + +also a raft of prinicpal manipulation functions: + +Prncipal Manipulation +--------------------- + +Samba makes extensive use of the principal manipulation functions in +Heimdal, including the known structure behind krb_principal and +krb5_realm (a char *). + +Authz data extraction +--------------------- + +We use krb5_ticket_get_authorization_data_type(), and expect it to +return the correct authz data, even if wrapped in an AD-IFRELEVENT container. + + +KDC/hdb Extensions +-------------- + +We have modified Heimdal's 'hdb' interface to specify the 'type' of +Principal being requested. This allows us to correctly behave with +the different 'classes' of Principal name. + +We currently define 2 classes: + - client (kinit) + - server (tgt) + +I also now specify the kerberos principal as an explict parameter, not +an in/out value on the entry itself. + +Inside hdb-ldb, we add krbtgt as a special class of principal, because +of particular special-case backend requirements. + +Callbacks: + In addition, I have added a new interface hdb_fetch_ex(), which + returns a structure including callbacks, which provide the hook for + the PAC, as well as a callback into the main access control routines. + + A new callback should be added to increment the bad password counter + on failure. + + Another possability for a callback is to obtain the keys. This would + allow the plaintext password to only be hashed into the encryption + types we need. This idea from the eDirectory/MIT DAL work. + + This probably should be combined with storing the hashed passwords in + the supplementalCredentials attribute. If combined with a kvno + parameter, this could also allow changing of the krbtgt password + (valuable for security). + +libkdc +------ + +Samba4 needs to be built as a single binary (design requirement), and +this should include the KDC. Samba also (and perhaps more +importantly) needs to control the configuration environment of the +KDC. + +The interface we have defined for libkdc allow for packet injection +into the post-socket layer, with a defined krb5_context and +kdb5_kdc_configuration structure. These effectively redirect the +kerberos warnings, logging and database calls as we require. + +Using our socket lib +-------------------- + +An important detail in the use of libkdc is that we use our own socket +lib. This allows the KDC code to be as portable as the rest of samba +(this cuts both ways), but far more importantly it ensures a +consistancy in the handling of requests, binding to sockets etc. + +To handle TCP, we use of our socket layer in much the same way as +we deal with TCP for CIFS. Tridge created a generic packet handling +layer for this. + +For the client, we likewise must take over the socket functions, so +that our single thread smbd will not lock up talking to itself. (We +allow processing while waiting for packets in our socket routines). + +Kerberos logging support +------------------------ + +Samba now (optionally in the main code, required for the KDC) uses the +krb5_log_facility from Heimdal. This allows us to redirect the +warnings and status from the KDC (and client/server kerberos code) to +Samba's DEBUG() system. + +Similarly important is the Heimdal-specific krb5_get_error_string() +function, which does a lot to reduce the 'administrator pain' level, +by providing specific, english text-string error messages instead of +just error code translations. + + +Short name rules +---------------- + +Samba is highly likely to be misconfigured, in many weird and +interesting ways. As such, we have a patch for Heimdal that avoids +DNS lookups on names without a . in them. This should avoid some +delay and root server load. + +PAC Correctness +--------------- + +We now put the PAC into the TGT, not just the service ticket. + +Forwarded tickets +----------------- + +We extract forwarded tickets from the GSSAPI layer, and put +them into the credentials. We can then use them for proxy work. + + +Kerberos TODO +============= + +(Feel free to contribute to any of these tasks, or ask +abartlet@samba.org about them). + +Lockout Control +-------------- + +We need to get (either if PADL publishes their patch, or write our +own) access control hooks in the Heimdal KDC. We need to lockout +accounts, and perform other controls. + +Gssmonger +--------- + +Microsoft has released a testsuite called gssmonger, which tests +interop. We should compile it against lorikeet-heimdal, MIT and see +if we can build a 'Samba4' server for it. + +Kpasswd server +-------------- + +I have a partial kpasswd server which needs finishing, and a we need a +client testsuite written, either via the krb5 API or directly against +GENSEC and the ASN.1 routines. + +Currently it only works for Heimdal, not MIT clients. This may be due +to call ordering constraints. + + +Correct TCP support +------------------- + +Our current TCP support does not send back 'too large' error messages +if the high bit is set. This is needed for a proposed extension +mechanism, but is likewise unsupported in both current Heimdal and MIT. diff --git a/source4/auth/kerberos/kerberos.c b/source4/auth/kerberos/kerberos.c new file mode 100644 index 0000000000..2579ab20cc --- /dev/null +++ b/source4/auth/kerberos/kerberos.c @@ -0,0 +1,122 @@ +/* + Unix SMB/CIFS implementation. + kerberos utility library + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Remus Koos 2001 + Copyright (C) Nalin Dahyabhai 2004. + Copyright (C) Jeremy Allison 2004. + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/kerberos.h" + +#ifdef HAVE_KRB5 + +/* + simulate a kinit, putting the tgt in the given credentials cache. + Orignally by remus@snapserver.com + + This version is built to use a keyblock, rather than needing the + original password. +*/ + int kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc, + krb5_principal principal, krb5_keyblock *keyblock, + time_t *expire_time, time_t *kdc_time) +{ + krb5_error_code code = 0; + krb5_creds my_creds; + krb5_get_init_creds_opt options; + + krb5_get_init_creds_opt_init(&options); + + krb5_get_init_creds_opt_set_default_flags(ctx, NULL, NULL, &options); + + if ((code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal, keyblock, + 0, NULL, &options))) { + return code; + } + + if ((code = krb5_cc_initialize(ctx, cc, principal))) { + krb5_free_cred_contents(ctx, &my_creds); + return code; + } + + if ((code = krb5_cc_store_cred(ctx, cc, &my_creds))) { + krb5_free_cred_contents(ctx, &my_creds); + return code; + } + + if (expire_time) { + *expire_time = (time_t) my_creds.times.endtime; + } + + if (kdc_time) { + *kdc_time = (time_t) my_creds.times.starttime; + } + + krb5_free_cred_contents(ctx, &my_creds); + + return 0; +} + +/* + simulate a kinit, putting the tgt in the given credentials cache. + Orignally by remus@snapserver.com +*/ + int kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc, + krb5_principal principal, const char *password, + time_t *expire_time, time_t *kdc_time) +{ + krb5_error_code code = 0; + krb5_creds my_creds; + krb5_get_init_creds_opt options; + + krb5_get_init_creds_opt_init(&options); + + krb5_get_init_creds_opt_set_default_flags(ctx, NULL, NULL, &options); + + if ((code = krb5_get_init_creds_password(ctx, &my_creds, principal, password, + NULL, + NULL, 0, NULL, &options))) { + return code; + } + + if ((code = krb5_cc_initialize(ctx, cc, principal))) { + krb5_free_cred_contents(ctx, &my_creds); + return code; + } + + if ((code = krb5_cc_store_cred(ctx, cc, &my_creds))) { + krb5_free_cred_contents(ctx, &my_creds); + return code; + } + + if (expire_time) { + *expire_time = (time_t) my_creds.times.endtime; + } + + if (kdc_time) { + *kdc_time = (time_t) my_creds.times.starttime; + } + + krb5_free_cred_contents(ctx, &my_creds); + + return 0; +} + + +#endif diff --git a/source4/auth/kerberos/kerberos.h b/source4/auth/kerberos/kerberos.h new file mode 100644 index 0000000000..8585aa321b --- /dev/null +++ b/source4/auth/kerberos/kerberos.h @@ -0,0 +1,153 @@ +/* + Unix SMB/CIFS implementation. + simple kerberos5 routines for active directory + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Luke Howard 2002-2003 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#if defined(HAVE_KRB5) + +#include "auth/kerberos/krb5_init_context.h" +#include "librpc/gen_ndr/krb5pac.h" + +struct auth_serversupplied_info; +struct cli_credentials; + +struct ccache_container { + struct smb_krb5_context *smb_krb5_context; + krb5_ccache ccache; +}; + +struct keytab_container { + struct smb_krb5_context *smb_krb5_context; + krb5_keytab keytab; +}; + +/* not really ASN.1, but RFC 1964 */ +#define TOK_ID_KRB_AP_REQ ((const uint8_t *)"\x01\x00") +#define TOK_ID_KRB_AP_REP ((const uint8_t *)"\x02\x00") +#define TOK_ID_KRB_ERROR ((const uint8_t *)"\x03\x00") +#define TOK_ID_GSS_GETMIC ((const uint8_t *)"\x01\x01") +#define TOK_ID_GSS_WRAP ((const uint8_t *)"\x02\x01") + +#ifdef HAVE_KRB5_KEYBLOCK_KEYVALUE +#define KRB5_KEY_TYPE(k) ((k)->keytype) +#define KRB5_KEY_LENGTH(k) ((k)->keyvalue.length) +#define KRB5_KEY_DATA(k) ((k)->keyvalue.data) +#else +#define KRB5_KEY_TYPE(k) ((k)->enctype) +#define KRB5_KEY_LENGTH(k) ((k)->length) +#define KRB5_KEY_DATA(k) ((k)->contents) +#endif /* HAVE_KRB5_KEYBLOCK_KEYVALUE */ + +#ifndef HAVE_KRB5_SET_REAL_TIME +krb5_error_code krb5_set_real_time(krb5_context context, int32_t seconds, int32_t microseconds); +#endif + +#ifndef HAVE_KRB5_SET_DEFAULT_TGS_KTYPES +krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc); +#endif + +#if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) +krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock); +#endif + +#ifndef HAVE_KRB5_FREE_UNPARSED_NAME +void krb5_free_unparsed_name(krb5_context ctx, char *val); +#endif + +#if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT) +const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i ); +#endif + +/* Samba wrapper function for krb5 functionality. */ +void setup_kaddr( krb5_address *pkaddr, struct sockaddr *paddr); +int create_kerberos_key_from_string(krb5_context context, krb5_principal host_princ, krb5_data *password, krb5_keyblock *key, krb5_enctype enctype); +int create_kerberos_key_from_string_direct(krb5_context context, krb5_principal host_princ, krb5_data *password, krb5_keyblock *key, krb5_enctype enctype); +krb5_const_principal get_principal_from_tkt(krb5_ticket *tkt); +krb5_error_code get_kerberos_allowed_etypes(krb5_context context, krb5_enctype **enctypes); +void free_kerberos_etypes(krb5_context context, krb5_enctype *enctypes); +bool get_krb5_smb_session_key(krb5_context context, krb5_auth_context auth_context, DATA_BLOB *session_key, bool remote); +krb5_error_code ads_krb5_mk_req(krb5_context context, + krb5_auth_context *auth_context, + const krb5_flags ap_req_options, + const char *principal, + krb5_ccache ccache, + krb5_data *outbuf); +bool get_auth_data_from_tkt(TALLOC_CTX *mem_ctx, DATA_BLOB *auth_data, krb5_ticket *tkt); +int kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc, + krb5_principal principal, const char *password, + time_t *expire_time, time_t *kdc_time); +int kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc, + krb5_principal principal, krb5_keyblock *keyblock, + time_t *expire_time, time_t *kdc_time); +krb5_principal kerberos_fetch_salt_princ_for_host_princ(krb5_context context, + krb5_principal host_princ, + int enctype); +void kerberos_set_creds_enctype(krb5_creds *pcreds, int enctype); +bool kerberos_compatible_enctypes(krb5_context context, krb5_enctype enctype1, krb5_enctype enctype2); +void kerberos_free_data_contents(krb5_context context, krb5_data *pdata); +krb5_error_code smb_krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *kt_entry); +char *smb_get_krb5_error_message(krb5_context context, krb5_error_code code, TALLOC_CTX *mem_ctx); + krb5_error_code kinit_to_ccache(TALLOC_CTX *parent_ctx, + struct cli_credentials *credentials, + struct smb_krb5_context *smb_krb5_context, + krb5_ccache ccache); +krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx, + struct cli_credentials *credentials, + struct smb_krb5_context *smb_krb5_context, + krb5_principal *princ); +NTSTATUS kerberos_decode_pac(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct PAC_DATA **pac_data_out, + DATA_BLOB blob, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + krb5_const_principal client_principal, + time_t tgs_authtime, + krb5_error_code *k5ret); + NTSTATUS kerberos_pac_logon_info(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct PAC_LOGON_INFO **logon_info, + DATA_BLOB blob, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + krb5_const_principal client_principal, + time_t tgs_authtime, + krb5_error_code *k5ret); + krb5_error_code kerberos_encode_pac(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct PAC_DATA *pac_data, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + DATA_BLOB *pac); + krb5_error_code kerberos_create_pac(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct auth_serversupplied_info *server_info, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + krb5_principal client_principal, + time_t tgs_authtime, + DATA_BLOB *pac); +struct loadparm_context; + +#include "auth/kerberos/proto.h" + +#endif /* HAVE_KRB5 */ diff --git a/source4/auth/kerberos/kerberos_heimdal.c b/source4/auth/kerberos/kerberos_heimdal.c new file mode 100644 index 0000000000..f669d0f2f4 --- /dev/null +++ b/source4/auth/kerberos/kerberos_heimdal.c @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* This file for code taken from the Heimdal code, to preserve licence */ +/* Modified by Andrew Bartlett <abartlet@samba.org> */ + +#include "includes.h" +#include "system/kerberos.h" + +/* Taken from accept_sec_context.c,v 1.65 */ +krb5_error_code smb_rd_req_return_stuff(krb5_context context, + krb5_auth_context *auth_context, + const krb5_data *inbuf, + krb5_keytab keytab, + krb5_principal acceptor_principal, + krb5_data *outbuf, + krb5_ticket **ticket, + krb5_keyblock **keyblock) +{ + krb5_rd_req_in_ctx in = NULL; + krb5_rd_req_out_ctx out = NULL; + krb5_error_code kret; + + *keyblock = NULL; + *ticket = NULL; + outbuf->length = 0; + outbuf->data = NULL; + + kret = krb5_rd_req_in_ctx_alloc(context, &in); + if (kret == 0) + kret = krb5_rd_req_in_set_keytab(context, in, keytab); + if (kret) { + if (in) + krb5_rd_req_in_ctx_free(context, in); + return kret; + } + + kret = krb5_rd_req_ctx(context, + auth_context, + inbuf, + acceptor_principal, + in, &out); + krb5_rd_req_in_ctx_free(context, in); + if (kret) { + return kret; + } + + /* + * We need to remember some data on the context_handle. + */ + kret = krb5_rd_req_out_get_ticket(context, out, + ticket); + if (kret == 0) { + kret = krb5_rd_req_out_get_keyblock(context, out, + keyblock); + } + krb5_rd_req_out_ctx_free(context, out); + + if (kret == 0) { + kret = krb5_mk_rep(context, *auth_context, outbuf); + } + + if (kret) { + krb5_free_ticket(context, *ticket); + krb5_free_keyblock(context, *keyblock); + krb5_data_free(outbuf); + } + + return kret; +} + diff --git a/source4/auth/kerberos/kerberos_pac.c b/source4/auth/kerberos/kerberos_pac.c new file mode 100644 index 0000000000..2943e05b18 --- /dev/null +++ b/source4/auth/kerberos/kerberos_pac.c @@ -0,0 +1,777 @@ +/* + Unix SMB/CIFS implementation. + + Create and parse the krb5 PAC + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005,2008 + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Luke Howard 2002-2003 + Copyright (C) Stefan Metzmacher 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/kerberos.h" +#include "auth/auth.h" +#include "auth/kerberos/kerberos.h" +#include "librpc/gen_ndr/ndr_krb5pac.h" +#include "lib/ldb/include/ldb.h" +#include "auth/auth_sam_reply.h" +#include "param/param.h" + +krb5_error_code check_pac_checksum(TALLOC_CTX *mem_ctx, + DATA_BLOB pac_data, + struct PAC_SIGNATURE_DATA *sig, + krb5_context context, + const krb5_keyblock *keyblock) +{ + krb5_error_code ret; + krb5_crypto crypto; + Checksum cksum; + + cksum.cksumtype = (CKSUMTYPE)sig->type; + cksum.checksum.length = sig->signature.length; + cksum.checksum.data = sig->signature.data; + + ret = krb5_crypto_init(context, + keyblock, + 0, + &crypto); + if (ret) { + DEBUG(0,("krb5_crypto_init() failed: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + return ret; + } + ret = krb5_verify_checksum(context, + crypto, + KRB5_KU_OTHER_CKSUM, + pac_data.data, + pac_data.length, + &cksum); + krb5_crypto_destroy(context, crypto); + + return ret; +} + + NTSTATUS kerberos_decode_pac(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct PAC_DATA **pac_data_out, + DATA_BLOB blob, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + krb5_const_principal client_principal, + time_t tgs_authtime, + krb5_error_code *k5ret) +{ + krb5_error_code ret; + NTSTATUS status; + enum ndr_err_code ndr_err; + struct PAC_SIGNATURE_DATA *srv_sig_ptr = NULL; + struct PAC_SIGNATURE_DATA *kdc_sig_ptr = NULL; + struct PAC_SIGNATURE_DATA *srv_sig_wipe = NULL; + struct PAC_SIGNATURE_DATA *kdc_sig_wipe = NULL; + struct PAC_LOGON_INFO *logon_info = NULL; + struct PAC_LOGON_NAME *logon_name = NULL; + struct PAC_DATA *pac_data; + struct PAC_DATA_RAW *pac_data_raw; + + DATA_BLOB *srv_sig_blob = NULL; + DATA_BLOB *kdc_sig_blob = NULL; + + DATA_BLOB modified_pac_blob; + NTTIME tgs_authtime_nttime; + krb5_principal client_principal_pac; + int i; + + krb5_clear_error_string(context); + + if (k5ret) { + *k5ret = KRB5_PARSE_MALFORMED; + } + + pac_data = talloc(mem_ctx, struct PAC_DATA); + pac_data_raw = talloc(mem_ctx, struct PAC_DATA_RAW); + kdc_sig_wipe = talloc(mem_ctx, struct PAC_SIGNATURE_DATA); + srv_sig_wipe = talloc(mem_ctx, struct PAC_SIGNATURE_DATA); + if (!pac_data_raw || !pac_data || !kdc_sig_wipe || !srv_sig_wipe) { + if (k5ret) { + *k5ret = ENOMEM; + } + return NT_STATUS_NO_MEMORY; + } + + ndr_err = ndr_pull_struct_blob(&blob, pac_data, + iconv_convenience, pac_data, + (ndr_pull_flags_fn_t)ndr_pull_PAC_DATA); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't parse the PAC: %s\n", + nt_errstr(status))); + return status; + } + + if (pac_data->num_buffers < 4) { + /* we need logon_ingo, service_key and kdc_key */ + DEBUG(0,("less than 4 PAC buffers\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + ndr_err = ndr_pull_struct_blob(&blob, pac_data_raw, + iconv_convenience, pac_data_raw, + (ndr_pull_flags_fn_t)ndr_pull_PAC_DATA_RAW); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't parse the PAC: %s\n", + nt_errstr(status))); + return status; + } + + if (pac_data_raw->num_buffers < 4) { + /* we need logon_ingo, service_key and kdc_key */ + DEBUG(0,("less than 4 PAC buffers\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + if (pac_data->num_buffers != pac_data_raw->num_buffers) { + /* we need logon_ingo, service_key and kdc_key */ + DEBUG(0,("misparse! PAC_DATA has %d buffers while PAC_DATA_RAW has %d\n", + pac_data->num_buffers, pac_data_raw->num_buffers)); + return NT_STATUS_INVALID_PARAMETER; + } + + for (i=0; i < pac_data->num_buffers; i++) { + if (pac_data->buffers[i].type != pac_data_raw->buffers[i].type) { + DEBUG(0,("misparse! PAC_DATA buffer %d has type %d while PAC_DATA_RAW has %d\n", + i, pac_data->buffers[i].type, pac_data->buffers[i].type)); + return NT_STATUS_INVALID_PARAMETER; + } + switch (pac_data->buffers[i].type) { + case PAC_TYPE_LOGON_INFO: + if (!pac_data->buffers[i].info) { + break; + } + logon_info = pac_data->buffers[i].info->logon_info.info; + break; + case PAC_TYPE_SRV_CHECKSUM: + if (!pac_data->buffers[i].info) { + break; + } + srv_sig_ptr = &pac_data->buffers[i].info->srv_cksum; + srv_sig_blob = &pac_data_raw->buffers[i].info->remaining; + break; + case PAC_TYPE_KDC_CHECKSUM: + if (!pac_data->buffers[i].info) { + break; + } + kdc_sig_ptr = &pac_data->buffers[i].info->kdc_cksum; + kdc_sig_blob = &pac_data_raw->buffers[i].info->remaining; + break; + case PAC_TYPE_LOGON_NAME: + logon_name = &pac_data->buffers[i].info->logon_name; + break; + default: + break; + } + } + + if (!logon_info) { + DEBUG(0,("PAC no logon_info\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + if (!logon_name) { + DEBUG(0,("PAC no logon_name\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + if (!srv_sig_ptr || !srv_sig_blob) { + DEBUG(0,("PAC no srv_key\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + if (!kdc_sig_ptr || !kdc_sig_blob) { + DEBUG(0,("PAC no kdc_key\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + /* Find and zero out the signatures, as required by the signing algorithm */ + + /* We find the data blobs above, now we parse them to get at the exact portion we should zero */ + ndr_err = ndr_pull_struct_blob(kdc_sig_blob, kdc_sig_wipe, + iconv_convenience, kdc_sig_wipe, + (ndr_pull_flags_fn_t)ndr_pull_PAC_SIGNATURE_DATA); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't parse the KDC signature: %s\n", + nt_errstr(status))); + return status; + } + + ndr_err = ndr_pull_struct_blob(srv_sig_blob, srv_sig_wipe, + iconv_convenience, srv_sig_wipe, + (ndr_pull_flags_fn_t)ndr_pull_PAC_SIGNATURE_DATA); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't parse the SRV signature: %s\n", + nt_errstr(status))); + return status; + } + + /* Now zero the decoded structure */ + memset(kdc_sig_wipe->signature.data, '\0', kdc_sig_wipe->signature.length); + memset(srv_sig_wipe->signature.data, '\0', srv_sig_wipe->signature.length); + + /* and reencode, back into the same place it came from */ + ndr_err = ndr_push_struct_blob(kdc_sig_blob, pac_data_raw, + iconv_convenience, + kdc_sig_wipe, + (ndr_push_flags_fn_t)ndr_push_PAC_SIGNATURE_DATA); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't repack the KDC signature: %s\n", + nt_errstr(status))); + return status; + } + ndr_err = ndr_push_struct_blob(srv_sig_blob, pac_data_raw, + iconv_convenience, + srv_sig_wipe, + (ndr_push_flags_fn_t)ndr_push_PAC_SIGNATURE_DATA); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't repack the SRV signature: %s\n", + nt_errstr(status))); + return status; + } + + /* push out the whole structure, but now with zero'ed signatures */ + ndr_err = ndr_push_struct_blob(&modified_pac_blob, pac_data_raw, + iconv_convenience, + pac_data_raw, + (ndr_push_flags_fn_t)ndr_push_PAC_DATA_RAW); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't repack the RAW PAC: %s\n", + nt_errstr(status))); + return status; + } + + /* verify by service_key */ + ret = check_pac_checksum(mem_ctx, + modified_pac_blob, srv_sig_ptr, + context, + service_keyblock); + if (ret) { + DEBUG(1, ("PAC Decode: Failed to verify the service signature: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + if (k5ret) { + *k5ret = ret; + } + return NT_STATUS_ACCESS_DENIED; + } + + if (krbtgt_keyblock) { + ret = check_pac_checksum(mem_ctx, + srv_sig_ptr->signature, kdc_sig_ptr, + context, krbtgt_keyblock); + if (ret) { + DEBUG(1, ("PAC Decode: Failed to verify the KDC signature: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + if (k5ret) { + *k5ret = ret; + } + return NT_STATUS_ACCESS_DENIED; + } + } + + /* Convert to NT time, so as not to loose accuracy in comparison */ + unix_to_nt_time(&tgs_authtime_nttime, tgs_authtime); + + if (tgs_authtime_nttime != logon_name->logon_time) { + DEBUG(2, ("PAC Decode: Logon time mismatch between ticket and PAC!\n")); + DEBUG(2, ("PAC Decode: PAC: %s\n", nt_time_string(mem_ctx, logon_name->logon_time))); + DEBUG(2, ("PAC Decode: Ticket: %s\n", nt_time_string(mem_ctx, tgs_authtime_nttime))); + return NT_STATUS_ACCESS_DENIED; + } + + ret = krb5_parse_name_flags(context, logon_name->account_name, KRB5_PRINCIPAL_PARSE_NO_REALM, + &client_principal_pac); + if (ret) { + DEBUG(2, ("Could not parse name from incoming PAC: [%s]: %s\n", + logon_name->account_name, + smb_get_krb5_error_message(context, ret, mem_ctx))); + if (k5ret) { + *k5ret = ret; + } + return NT_STATUS_INVALID_PARAMETER; + } + + if (!krb5_principal_compare_any_realm(context, client_principal, client_principal_pac)) { + DEBUG(2, ("Name in PAC [%s] does not match principal name in ticket\n", + logon_name->account_name)); + return NT_STATUS_ACCESS_DENIED; + } + +#if 0 + if (strcasecmp(logon_info->info3.base.account_name.string, + "Administrator")== 0) { + file_save("tmp_pac_data-admin.dat",blob.data,blob.length); + } +#endif + + DEBUG(3,("Found account name from PAC: %s [%s]\n", + logon_info->info3.base.account_name.string, + logon_info->info3.base.full_name.string)); + *pac_data_out = pac_data; + + return NT_STATUS_OK; +} + +_PUBLIC_ NTSTATUS kerberos_pac_logon_info(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct PAC_LOGON_INFO **logon_info, + DATA_BLOB blob, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + krb5_const_principal client_principal, + time_t tgs_authtime, + krb5_error_code *k5ret) +{ + NTSTATUS nt_status; + struct PAC_DATA *pac_data; + int i; + nt_status = kerberos_decode_pac(mem_ctx, + iconv_convenience, + &pac_data, + blob, + context, + krbtgt_keyblock, + service_keyblock, + client_principal, + tgs_authtime, + k5ret); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + *logon_info = NULL; + for (i=0; i < pac_data->num_buffers; i++) { + if (pac_data->buffers[i].type != PAC_TYPE_LOGON_INFO) { + continue; + } + *logon_info = pac_data->buffers[i].info->logon_info.info; + } + if (!*logon_info) { + return NT_STATUS_INVALID_PARAMETER; + } + return NT_STATUS_OK; +} + +static krb5_error_code make_pac_checksum(TALLOC_CTX *mem_ctx, + DATA_BLOB *pac_data, + struct PAC_SIGNATURE_DATA *sig, + krb5_context context, + const krb5_keyblock *keyblock) +{ + krb5_error_code ret; + krb5_crypto crypto; + Checksum cksum; + + + ret = krb5_crypto_init(context, + keyblock, + 0, + &crypto); + if (ret) { + DEBUG(0,("krb5_crypto_init() failed: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + return ret; + } + ret = krb5_create_checksum(context, + crypto, + KRB5_KU_OTHER_CKSUM, + 0, + pac_data->data, + pac_data->length, + &cksum); + if (ret) { + DEBUG(2, ("PAC Verification failed: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + } + + krb5_crypto_destroy(context, crypto); + + if (ret) { + return ret; + } + + sig->type = cksum.cksumtype; + sig->signature = data_blob_talloc(mem_ctx, cksum.checksum.data, cksum.checksum.length); + free_Checksum(&cksum); + + return 0; +} + + krb5_error_code kerberos_encode_pac(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct PAC_DATA *pac_data, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + DATA_BLOB *pac) +{ + NTSTATUS nt_status; + krb5_error_code ret; + enum ndr_err_code ndr_err; + DATA_BLOB zero_blob = data_blob(NULL, 0); + DATA_BLOB tmp_blob = data_blob(NULL, 0); + struct PAC_SIGNATURE_DATA *kdc_checksum = NULL; + struct PAC_SIGNATURE_DATA *srv_checksum = NULL; + int i; + + /* First, just get the keytypes filled in (and lengths right, eventually) */ + for (i=0; i < pac_data->num_buffers; i++) { + if (pac_data->buffers[i].type != PAC_TYPE_KDC_CHECKSUM) { + continue; + } + kdc_checksum = &pac_data->buffers[i].info->kdc_cksum, + ret = make_pac_checksum(mem_ctx, &zero_blob, + kdc_checksum, + context, krbtgt_keyblock); + if (ret) { + DEBUG(2, ("making krbtgt PAC checksum failed: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + talloc_free(pac_data); + return ret; + } + } + + for (i=0; i < pac_data->num_buffers; i++) { + if (pac_data->buffers[i].type != PAC_TYPE_SRV_CHECKSUM) { + continue; + } + srv_checksum = &pac_data->buffers[i].info->srv_cksum; + ret = make_pac_checksum(mem_ctx, &zero_blob, + srv_checksum, + context, service_keyblock); + if (ret) { + DEBUG(2, ("making service PAC checksum failed: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + talloc_free(pac_data); + return ret; + } + } + + if (!kdc_checksum) { + DEBUG(2, ("Invalid PAC constructed for signing, no KDC checksum present!")); + return EINVAL; + } + if (!srv_checksum) { + DEBUG(2, ("Invalid PAC constructed for signing, no SRV checksum present!")); + return EINVAL; + } + + /* But wipe out the actual signatures */ + memset(kdc_checksum->signature.data, '\0', kdc_checksum->signature.length); + memset(srv_checksum->signature.data, '\0', srv_checksum->signature.length); + + ndr_err = ndr_push_struct_blob(&tmp_blob, mem_ctx, + iconv_convenience, + pac_data, + (ndr_push_flags_fn_t)ndr_push_PAC_DATA); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + nt_status = ndr_map_error2ntstatus(ndr_err); + DEBUG(1, ("PAC (presig) push failed: %s\n", nt_errstr(nt_status))); + talloc_free(pac_data); + return EINVAL; + } + + /* Then sign the result of the previous push, where the sig was zero'ed out */ + ret = make_pac_checksum(mem_ctx, &tmp_blob, srv_checksum, + context, service_keyblock); + + /* Then sign Server checksum */ + ret = make_pac_checksum(mem_ctx, &srv_checksum->signature, kdc_checksum, context, krbtgt_keyblock); + if (ret) { + DEBUG(2, ("making krbtgt PAC checksum failed: %s\n", + smb_get_krb5_error_message(context, ret, mem_ctx))); + talloc_free(pac_data); + return ret; + } + + /* And push it out again, this time to the world. This relies on determanistic pointer values */ + ndr_err = ndr_push_struct_blob(&tmp_blob, mem_ctx, + iconv_convenience, + pac_data, + (ndr_push_flags_fn_t)ndr_push_PAC_DATA); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + nt_status = ndr_map_error2ntstatus(ndr_err); + DEBUG(1, ("PAC (final) push failed: %s\n", nt_errstr(nt_status))); + talloc_free(pac_data); + return EINVAL; + } + + *pac = tmp_blob; + + return ret; +} + + + krb5_error_code kerberos_create_pac(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + struct auth_serversupplied_info *server_info, + krb5_context context, + const krb5_keyblock *krbtgt_keyblock, + const krb5_keyblock *service_keyblock, + krb5_principal client_principal, + time_t tgs_authtime, + DATA_BLOB *pac) +{ + NTSTATUS nt_status; + krb5_error_code ret; + struct PAC_DATA *pac_data = talloc(mem_ctx, struct PAC_DATA); + struct netr_SamInfo3 *sam3; + union PAC_INFO *u_LOGON_INFO; + struct PAC_LOGON_INFO *LOGON_INFO; + union PAC_INFO *u_LOGON_NAME; + struct PAC_LOGON_NAME *LOGON_NAME; + union PAC_INFO *u_KDC_CHECKSUM; + union PAC_INFO *u_SRV_CHECKSUM; + + char *name; + + enum { + PAC_BUF_LOGON_INFO = 0, + PAC_BUF_LOGON_NAME = 1, + PAC_BUF_SRV_CHECKSUM = 2, + PAC_BUF_KDC_CHECKSUM = 3, + PAC_BUF_NUM_BUFFERS = 4 + }; + + if (!pac_data) { + return ENOMEM; + } + + pac_data->num_buffers = PAC_BUF_NUM_BUFFERS; + pac_data->version = 0; + + pac_data->buffers = talloc_array(pac_data, + struct PAC_BUFFER, + pac_data->num_buffers); + if (!pac_data->buffers) { + talloc_free(pac_data); + return ENOMEM; + } + + /* LOGON_INFO */ + u_LOGON_INFO = talloc_zero(pac_data->buffers, union PAC_INFO); + if (!u_LOGON_INFO) { + talloc_free(pac_data); + return ENOMEM; + } + pac_data->buffers[PAC_BUF_LOGON_INFO].type = PAC_TYPE_LOGON_INFO; + pac_data->buffers[PAC_BUF_LOGON_INFO].info = u_LOGON_INFO; + + /* LOGON_NAME */ + u_LOGON_NAME = talloc_zero(pac_data->buffers, union PAC_INFO); + if (!u_LOGON_NAME) { + talloc_free(pac_data); + return ENOMEM; + } + pac_data->buffers[PAC_BUF_LOGON_NAME].type = PAC_TYPE_LOGON_NAME; + pac_data->buffers[PAC_BUF_LOGON_NAME].info = u_LOGON_NAME; + LOGON_NAME = &u_LOGON_NAME->logon_name; + + /* SRV_CHECKSUM */ + u_SRV_CHECKSUM = talloc_zero(pac_data->buffers, union PAC_INFO); + if (!u_SRV_CHECKSUM) { + talloc_free(pac_data); + return ENOMEM; + } + pac_data->buffers[PAC_BUF_SRV_CHECKSUM].type = PAC_TYPE_SRV_CHECKSUM; + pac_data->buffers[PAC_BUF_SRV_CHECKSUM].info = u_SRV_CHECKSUM; + + /* KDC_CHECKSUM */ + u_KDC_CHECKSUM = talloc_zero(pac_data->buffers, union PAC_INFO); + if (!u_KDC_CHECKSUM) { + talloc_free(pac_data); + return ENOMEM; + } + pac_data->buffers[PAC_BUF_KDC_CHECKSUM].type = PAC_TYPE_KDC_CHECKSUM; + pac_data->buffers[PAC_BUF_KDC_CHECKSUM].info = u_KDC_CHECKSUM; + + /* now the real work begins... */ + + LOGON_INFO = talloc_zero(u_LOGON_INFO, struct PAC_LOGON_INFO); + if (!LOGON_INFO) { + talloc_free(pac_data); + return ENOMEM; + } + nt_status = auth_convert_server_info_saminfo3(LOGON_INFO, server_info, &sam3); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(1, ("Getting Samba info failed: %s\n", nt_errstr(nt_status))); + talloc_free(pac_data); + return EINVAL; + } + + u_LOGON_INFO->logon_info.info = LOGON_INFO; + LOGON_INFO->info3 = *sam3; + + ret = krb5_unparse_name_flags(context, client_principal, + KRB5_PRINCIPAL_UNPARSE_NO_REALM, &name); + if (ret) { + return ret; + } + LOGON_NAME->account_name = talloc_strdup(LOGON_NAME, name); + free(name); + /* + this logon_time field is absolutely critical. This is what + caused all our PAC troubles :-) + */ + unix_to_nt_time(&LOGON_NAME->logon_time, tgs_authtime); + + ret = kerberos_encode_pac(mem_ctx, + iconv_convenience, + pac_data, + context, + krbtgt_keyblock, + service_keyblock, + pac); + talloc_free(pac_data); + return ret; +} + +krb5_error_code kerberos_pac_to_server_info(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + krb5_pac pac, + krb5_context context, + struct auth_serversupplied_info **server_info) +{ + NTSTATUS nt_status; + enum ndr_err_code ndr_err; + krb5_error_code ret; + + DATA_BLOB pac_logon_info_in, pac_srv_checksum_in, pac_kdc_checksum_in; + krb5_data k5pac_logon_info_in, k5pac_srv_checksum_in, k5pac_kdc_checksum_in; + + union PAC_INFO info; + union netr_Validation validation; + struct auth_serversupplied_info *server_info_out; + + TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); + + if (!tmp_ctx) { + return ENOMEM; + } + + ret = krb5_pac_get_buffer(context, pac, PAC_TYPE_LOGON_INFO, &k5pac_logon_info_in); + if (ret != 0) { + talloc_free(tmp_ctx); + return EINVAL; + } + + pac_logon_info_in = data_blob_const(k5pac_logon_info_in.data, k5pac_logon_info_in.length); + + ndr_err = ndr_pull_union_blob(&pac_logon_info_in, tmp_ctx, iconv_convenience, &info, + PAC_TYPE_LOGON_INFO, + (ndr_pull_flags_fn_t)ndr_pull_PAC_INFO); + krb5_data_free(&k5pac_logon_info_in); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err) || !info.logon_info.info) { + nt_status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't parse the PAC LOGON_INFO: %s\n", nt_errstr(nt_status))); + talloc_free(tmp_ctx); + return EINVAL; + } + + /* Pull this right into the normal auth sysstem structures */ + validation.sam3 = &info.logon_info.info->info3; + nt_status = make_server_info_netlogon_validation(mem_ctx, + "", + 3, &validation, + &server_info_out); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(tmp_ctx); + return EINVAL; + } + + ret = krb5_pac_get_buffer(context, pac, PAC_TYPE_SRV_CHECKSUM, &k5pac_srv_checksum_in); + if (ret != 0) { + talloc_free(tmp_ctx); + return ret; + } + + pac_srv_checksum_in = data_blob_const(k5pac_srv_checksum_in.data, k5pac_srv_checksum_in.length); + + ndr_err = ndr_pull_struct_blob(&pac_srv_checksum_in, server_info_out, + iconv_convenience, &server_info_out->pac_srv_sig, + (ndr_pull_flags_fn_t)ndr_pull_PAC_SIGNATURE_DATA); + krb5_data_free(&k5pac_srv_checksum_in); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + nt_status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't parse the KDC signature: %s\n", + nt_errstr(nt_status))); + return EINVAL; + } + + ret = krb5_pac_get_buffer(context, pac, PAC_TYPE_KDC_CHECKSUM, &k5pac_kdc_checksum_in); + if (ret != 0) { + talloc_free(tmp_ctx); + return ret; + } + + pac_kdc_checksum_in = data_blob_const(k5pac_kdc_checksum_in.data, k5pac_kdc_checksum_in.length); + + ndr_err = ndr_pull_struct_blob(&pac_kdc_checksum_in, server_info_out, + iconv_convenience, &server_info_out->pac_kdc_sig, + (ndr_pull_flags_fn_t)ndr_pull_PAC_SIGNATURE_DATA); + krb5_data_free(&k5pac_kdc_checksum_in); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + nt_status = ndr_map_error2ntstatus(ndr_err); + DEBUG(0,("can't parse the KDC signature: %s\n", + nt_errstr(nt_status))); + return EINVAL; + } + + *server_info = server_info_out; + + return 0; +} + + +NTSTATUS kerberos_pac_blob_to_server_info(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + DATA_BLOB pac_blob, + krb5_context context, + struct auth_serversupplied_info **server_info) +{ + krb5_error_code ret; + krb5_pac pac; + ret = krb5_pac_parse(context, + pac_blob.data, pac_blob.length, + &pac); + if (ret) { + return map_nt_error_from_unix(ret); + } + + + ret = kerberos_pac_to_server_info(mem_ctx, iconv_convenience, pac, context, server_info); + krb5_pac_free(context, pac); + if (ret) { + return map_nt_error_from_unix(ret); + } + return NT_STATUS_OK; +} diff --git a/source4/auth/kerberos/kerberos_util.c b/source4/auth/kerberos/kerberos_util.c new file mode 100644 index 0000000000..9002715065 --- /dev/null +++ b/source4/auth/kerberos/kerberos_util.c @@ -0,0 +1,681 @@ +/* + Unix SMB/CIFS implementation. + + Kerberos utility functions for GENSEC + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/kerberos.h" +#include "auth/kerberos/kerberos.h" +#include "auth/credentials/credentials.h" +#include "auth/credentials/credentials_proto.h" +#include "auth/credentials/credentials_krb5.h" + +struct principal_container { + struct smb_krb5_context *smb_krb5_context; + krb5_principal principal; +}; + +static int free_principal(struct principal_container *pc) +{ + /* current heimdal - 0.6.3, which we need anyway, fixes segfaults here */ + krb5_free_principal(pc->smb_krb5_context->krb5_context, pc->principal); + + return 0; +} + +static krb5_error_code salt_principal_from_credentials(TALLOC_CTX *parent_ctx, + struct cli_credentials *machine_account, + struct smb_krb5_context *smb_krb5_context, + krb5_principal *salt_princ) +{ + krb5_error_code ret; + char *machine_username; + char *salt_body; + char *lower_realm; + const char *salt_principal; + struct principal_container *mem_ctx = talloc(parent_ctx, struct principal_container); + if (!mem_ctx) { + return ENOMEM; + } + + salt_principal = cli_credentials_get_salt_principal(machine_account); + if (salt_principal) { + ret = krb5_parse_name(smb_krb5_context->krb5_context, salt_principal, salt_princ); + } else { + machine_username = talloc_strdup(mem_ctx, cli_credentials_get_username(machine_account)); + + if (!machine_username) { + talloc_free(mem_ctx); + return ENOMEM; + } + + if (machine_username[strlen(machine_username)-1] == '$') { + machine_username[strlen(machine_username)-1] = '\0'; + } + lower_realm = strlower_talloc(mem_ctx, cli_credentials_get_realm(machine_account)); + if (!lower_realm) { + talloc_free(mem_ctx); + return ENOMEM; + } + + salt_body = talloc_asprintf(mem_ctx, "%s.%s", machine_username, + lower_realm); + if (!salt_body) { + talloc_free(mem_ctx); + return ENOMEM; + } + + ret = krb5_make_principal(smb_krb5_context->krb5_context, salt_princ, + cli_credentials_get_realm(machine_account), + "host", salt_body, NULL); + } + + if (ret == 0) { + /* This song-and-dance effectivly puts the principal + * into talloc, so we can't loose it. */ + mem_ctx->smb_krb5_context = talloc_reference(mem_ctx, smb_krb5_context); + mem_ctx->principal = *salt_princ; + talloc_set_destructor(mem_ctx, free_principal); + } + return ret; +} + +/* Obtain the principal set on this context. Requires a + * smb_krb5_context because we are doing krb5 principal parsing with + * the library routines. The returned princ is placed in the talloc + * system by means of a destructor (do *not* free). */ + + krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx, + struct cli_credentials *credentials, + struct smb_krb5_context *smb_krb5_context, + krb5_principal *princ) +{ + krb5_error_code ret; + const char *princ_string; + struct principal_container *mem_ctx = talloc(parent_ctx, struct principal_container); + if (!mem_ctx) { + return ENOMEM; + } + + princ_string = cli_credentials_get_principal(credentials, mem_ctx); + + /* A NULL here has meaning, as the gssapi server case will + * then use the principal from the client */ + if (!princ_string) { + talloc_free(mem_ctx); + princ = NULL; + return 0; + } + + ret = krb5_parse_name(smb_krb5_context->krb5_context, + princ_string, princ); + + if (ret == 0) { + /* This song-and-dance effectivly puts the principal + * into talloc, so we can't loose it. */ + mem_ctx->smb_krb5_context = talloc_reference(mem_ctx, smb_krb5_context); + mem_ctx->principal = *princ; + talloc_set_destructor(mem_ctx, free_principal); + } + return ret; +} + +/** + * Return a freshly allocated ccache (destroyed by destructor on child + * of parent_ctx), for a given set of client credentials + */ + + krb5_error_code kinit_to_ccache(TALLOC_CTX *parent_ctx, + struct cli_credentials *credentials, + struct smb_krb5_context *smb_krb5_context, + krb5_ccache ccache) +{ + krb5_error_code ret; + const char *password; + time_t kdc_time = 0; + krb5_principal princ; + int tries; + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + + if (!mem_ctx) { + return ENOMEM; + } + + ret = principal_from_credentials(mem_ctx, credentials, smb_krb5_context, &princ); + if (ret) { + talloc_free(mem_ctx); + return ret; + } + + password = cli_credentials_get_password(credentials); + + tries = 2; + while (tries--) { + if (password) { + ret = kerberos_kinit_password_cc(smb_krb5_context->krb5_context, ccache, + princ, + password, NULL, &kdc_time); + } else { + /* No password available, try to use a keyblock instead */ + + krb5_keyblock keyblock; + const struct samr_Password *mach_pwd; + mach_pwd = cli_credentials_get_nt_hash(credentials, mem_ctx); + if (!mach_pwd) { + talloc_free(mem_ctx); + DEBUG(1, ("kinit_to_ccache: No password available for kinit\n")); + return EINVAL; + } + ret = krb5_keyblock_init(smb_krb5_context->krb5_context, + ETYPE_ARCFOUR_HMAC_MD5, + mach_pwd->hash, sizeof(mach_pwd->hash), + &keyblock); + + if (ret == 0) { + ret = kerberos_kinit_keyblock_cc(smb_krb5_context->krb5_context, ccache, + princ, + &keyblock, NULL, &kdc_time); + krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &keyblock); + } + } + + if (ret == KRB5KRB_AP_ERR_SKEW || ret == KRB5_KDCREP_SKEW) { + /* Perhaps we have been given an invalid skew, so try again without it */ + time_t t = time(NULL); + krb5_set_real_time(smb_krb5_context->krb5_context, t, 0); + } else { + /* not a skew problem */ + break; + } + } + + if (ret == KRB5KRB_AP_ERR_SKEW || ret == KRB5_KDCREP_SKEW) { + DEBUG(1,("kinit for %s failed (%s)\n", + cli_credentials_get_principal(credentials, mem_ctx), + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + + /* cope with ticket being in the future due to clock skew */ + if ((unsigned)kdc_time > time(NULL)) { + time_t t = time(NULL); + int time_offset =(unsigned)kdc_time-t; + DEBUG(4,("Advancing clock by %d seconds to cope with clock skew\n", time_offset)); + krb5_set_real_time(smb_krb5_context->krb5_context, t + time_offset + 1, 0); + } + + if (ret == KRB5KDC_ERR_PREAUTH_FAILED && cli_credentials_wrong_password(credentials)) { + ret = kinit_to_ccache(parent_ctx, + credentials, + smb_krb5_context, + ccache); + } + if (ret) { + DEBUG(1,("kinit for %s failed (%s)\n", + cli_credentials_get_principal(credentials, mem_ctx), + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + talloc_free(mem_ctx); + return 0; +} + +static int free_keytab(struct keytab_container *ktc) +{ + krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab); + + return 0; +} + +int smb_krb5_open_keytab(TALLOC_CTX *mem_ctx, + struct smb_krb5_context *smb_krb5_context, + const char *keytab_name, struct keytab_container **ktc) +{ + krb5_keytab keytab; + int ret; + ret = krb5_kt_resolve(smb_krb5_context->krb5_context, keytab_name, &keytab); + if (ret) { + DEBUG(1,("failed to open krb5 keytab: %s\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + return ret; + } + + *ktc = talloc(mem_ctx, struct keytab_container); + if (!*ktc) { + return ENOMEM; + } + + (*ktc)->smb_krb5_context = talloc_reference(*ktc, smb_krb5_context); + (*ktc)->keytab = keytab; + talloc_set_destructor(*ktc, free_keytab); + + return 0; +} + +static krb5_error_code keytab_add_keys(TALLOC_CTX *parent_ctx, + const char *princ_string, + krb5_principal princ, + krb5_principal salt_princ, + int kvno, + const char *password_s, + struct smb_krb5_context *smb_krb5_context, + const char **enctype_strings, + krb5_keytab keytab) +{ + int i; + krb5_error_code ret; + krb5_data password; + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + if (!mem_ctx) { + return ENOMEM; + } + + password.data = discard_const_p(char *, password_s); + password.length = strlen(password_s); + + for (i=0; enctype_strings[i]; i++) { + krb5_keytab_entry entry; + krb5_enctype enctype; + ret = krb5_string_to_enctype(smb_krb5_context->krb5_context, enctype_strings[i], &enctype); + if (ret != 0) { + DEBUG(1, ("Failed to interpret %s as a krb5 encryption type: %s\n", + enctype_strings[i], + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + ret = create_kerberos_key_from_string(smb_krb5_context->krb5_context, + salt_princ, &password, &entry.keyblock, enctype); + if (ret != 0) { + talloc_free(mem_ctx); + return ret; + } + + entry.principal = princ; + entry.vno = kvno; + ret = krb5_kt_add_entry(smb_krb5_context->krb5_context, keytab, &entry); + if (ret != 0) { + DEBUG(1, ("Failed to add %s entry for %s(kvno %d) to keytab: %s\n", + enctype_strings[i], + princ_string, + kvno, + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock); + return ret; + } + + DEBUG(5, ("Added %s(kvno %d) to keytab (%s)\n", + princ_string, kvno, + enctype_strings[i])); + + krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock); + } + talloc_free(mem_ctx); + return 0; +} + +static int create_keytab(TALLOC_CTX *parent_ctx, + struct cli_credentials *machine_account, + struct smb_krb5_context *smb_krb5_context, + const char **enctype_strings, + krb5_keytab keytab, + bool add_old) +{ + krb5_error_code ret; + const char *password_s; + const char *old_secret; + int kvno; + krb5_principal salt_princ; + krb5_principal princ; + const char *princ_string; + + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + if (!mem_ctx) { + return ENOMEM; + } + + princ_string = cli_credentials_get_principal(machine_account, mem_ctx); + /* Get the principal we will store the new keytab entries under */ + ret = principal_from_credentials(mem_ctx, machine_account, smb_krb5_context, &princ); + if (ret) { + DEBUG(1,("create_keytab: makeing krb5 principal failed (%s)\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + + /* The salt used to generate these entries may be different however, fetch that */ + ret = salt_principal_from_credentials(mem_ctx, machine_account, + smb_krb5_context, + &salt_princ); + if (ret) { + DEBUG(1,("create_keytab: makeing salt principal failed (%s)\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + + /* Finally, do the dance to get the password to put in the entry */ + password_s = cli_credentials_get_password(machine_account); + if (!password_s) { + krb5_keytab_entry entry; + const struct samr_Password *mach_pwd; + + if (!str_list_check(enctype_strings, "arcfour-hmac-md5")) { + DEBUG(1, ("Asked to create keytab, but with only an NT hash supplied, " + "but not listing arcfour-hmac-md5 as an enc type to include in the keytab!\n")); + talloc_free(mem_ctx); + return EINVAL; + } + + /* If we don't have the plaintext password, try for + * the MD4 password hash */ + mach_pwd = cli_credentials_get_nt_hash(machine_account, mem_ctx); + if (!mach_pwd) { + /* OK, nothing to do here */ + talloc_free(mem_ctx); + return 0; + } + ret = krb5_keyblock_init(smb_krb5_context->krb5_context, + ETYPE_ARCFOUR_HMAC_MD5, + mach_pwd->hash, sizeof(mach_pwd->hash), + &entry.keyblock); + if (ret) { + DEBUG(1, ("create_keytab: krb5_keyblock_init failed: %s\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + + entry.principal = princ; + entry.vno = cli_credentials_get_kvno(machine_account); + ret = krb5_kt_add_entry(smb_krb5_context->krb5_context, keytab, &entry); + if (ret) { + DEBUG(1, ("Failed to add ARCFOUR_HMAC (only) entry for %s to keytab: %s", + cli_credentials_get_principal(machine_account, mem_ctx), + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock); + return ret; + } + + DEBUG(5, ("Added %s(kvno %d) to keytab (arcfour-hmac-md5)\n", + cli_credentials_get_principal(machine_account, mem_ctx), + cli_credentials_get_kvno(machine_account))); + + krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock); + + /* Can't go any further, we only have this one key */ + talloc_free(mem_ctx); + return 0; + } + + kvno = cli_credentials_get_kvno(machine_account); + /* good, we actually have the real plaintext */ + ret = keytab_add_keys(mem_ctx, princ_string, princ, salt_princ, + kvno, password_s, smb_krb5_context, + enctype_strings, keytab); + if (!ret) { + talloc_free(mem_ctx); + return ret; + } + + if (!add_old || kvno == 0) { + talloc_free(mem_ctx); + return 0; + } + + old_secret = cli_credentials_get_old_password(machine_account); + if (!old_secret) { + talloc_free(mem_ctx); + return 0; + } + + ret = keytab_add_keys(mem_ctx, princ_string, princ, salt_princ, + kvno - 1, old_secret, smb_krb5_context, + enctype_strings, keytab); + if (!ret) { + talloc_free(mem_ctx); + return ret; + } + + talloc_free(mem_ctx); + return 0; +} + + +/* + * Walk the keytab, looking for entries of this principal name, with KVNO other than current kvno -1. + * + * These entries are now stale, we only keep the current, and previous entries around. + * + * Inspired by the code in Samba3 for 'use kerberos keytab'. + * + */ + +static krb5_error_code remove_old_entries(TALLOC_CTX *parent_ctx, + struct cli_credentials *machine_account, + struct smb_krb5_context *smb_krb5_context, + krb5_keytab keytab, bool *found_previous) +{ + krb5_error_code ret, ret2; + krb5_kt_cursor cursor; + krb5_principal princ; + int kvno; + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + const char *princ_string; + if (!mem_ctx) { + return ENOMEM; + } + + *found_previous = false; + princ_string = cli_credentials_get_principal(machine_account, mem_ctx); + + /* Get the principal we will store the new keytab entries under */ + ret = principal_from_credentials(mem_ctx, machine_account, smb_krb5_context, &princ); + if (ret) { + DEBUG(1,("update_keytab: makeing krb5 principal failed (%s)\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + + kvno = cli_credentials_get_kvno(machine_account); + + /* for each entry in the keytab */ + ret = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor); + switch (ret) { + case 0: + break; + case HEIM_ERR_OPNOTSUPP: + case ENOENT: + case KRB5_KT_END: + /* no point enumerating if there isn't anything here */ + talloc_free(mem_ctx); + return 0; + default: + DEBUG(1,("failed to open keytab for read of old entries: %s\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + talloc_free(mem_ctx); + return ret; + } + + while (!ret) { + krb5_keytab_entry entry; + ret = krb5_kt_next_entry(smb_krb5_context->krb5_context, keytab, &entry, &cursor); + if (ret) { + break; + } + /* if it matches our principal */ + if (!krb5_kt_compare(smb_krb5_context->krb5_context, &entry, princ, 0, 0)) { + /* Free the entry, it wasn't the one we were looking for anyway */ + krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry); + continue; + } + + /* delete it, if it is not kvno -1 */ + if (entry.vno != (kvno - 1 )) { + /* Release the enumeration. We are going to + * have to start this from the top again, + * because deletes during enumeration may not + * always be consistant. + * + * Also, the enumeration locks a FILE: keytab + */ + + krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor); + + ret = krb5_kt_remove_entry(smb_krb5_context->krb5_context, keytab, &entry); + krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry); + + /* Deleted: Restart from the top */ + ret2 = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor); + if (ret2) { + krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry); + DEBUG(1,("failed to restart enumeration of keytab: %s\n", + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + + talloc_free(mem_ctx); + return ret2; + } + + if (ret) { + break; + } + + } else { + *found_previous = true; + } + + /* Free the entry, we don't need it any more */ + krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry); + + + } + krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor); + + switch (ret) { + case 0: + break; + case ENOENT: + case KRB5_KT_END: + ret = 0; + break; + default: + DEBUG(1,("failed in deleting old entries for principal: %s: %s\n", + princ_string, + smb_get_krb5_error_message(smb_krb5_context->krb5_context, + ret, mem_ctx))); + } + talloc_free(mem_ctx); + return ret; +} + +int smb_krb5_update_keytab(TALLOC_CTX *parent_ctx, + struct cli_credentials *machine_account, + struct smb_krb5_context *smb_krb5_context, + const char **enctype_strings, + struct keytab_container *keytab_container) +{ + krb5_error_code ret; + bool found_previous; + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + if (!mem_ctx) { + return ENOMEM; + } + + ret = remove_old_entries(mem_ctx, machine_account, + smb_krb5_context, keytab_container->keytab, &found_previous); + if (ret != 0) { + talloc_free(mem_ctx); + return ret; + } + + /* Create a new keytab. If during the cleanout we found + * entires for kvno -1, then don't try and duplicate them. + * Otherwise, add kvno, and kvno -1 */ + + ret = create_keytab(mem_ctx, machine_account, smb_krb5_context, + enctype_strings, + keytab_container->keytab, + found_previous ? false : true); + talloc_free(mem_ctx); + return ret; +} + +int smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx, + struct cli_credentials *machine_account, + struct smb_krb5_context *smb_krb5_context, + const char **enctype_strings, + struct keytab_container **keytab_container) +{ + krb5_error_code ret; + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + const char *rand_string; + const char *keytab_name; + if (!mem_ctx) { + return ENOMEM; + } + + *keytab_container = talloc(mem_ctx, struct keytab_container); + + rand_string = generate_random_str(mem_ctx, 16); + if (!rand_string) { + talloc_free(mem_ctx); + return ENOMEM; + } + + keytab_name = talloc_asprintf(mem_ctx, "MEMORY:%s", + rand_string); + if (!keytab_name) { + talloc_free(mem_ctx); + return ENOMEM; + } + + ret = smb_krb5_open_keytab(mem_ctx, smb_krb5_context, keytab_name, keytab_container); + if (ret) { + return ret; + } + + ret = smb_krb5_update_keytab(mem_ctx, machine_account, smb_krb5_context, enctype_strings, *keytab_container); + if (ret == 0) { + talloc_steal(parent_ctx, *keytab_container); + } else { + *keytab_container = NULL; + } + talloc_free(mem_ctx); + return ret; +} + diff --git a/source4/auth/kerberos/krb5_init_context.c b/source4/auth/kerberos/krb5_init_context.c new file mode 100644 index 0000000000..82e42a4560 --- /dev/null +++ b/source4/auth/kerberos/krb5_init_context.c @@ -0,0 +1,482 @@ +/* + Unix SMB/CIFS implementation. + Wrapper for krb5_init_context + + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 + Copyright (C) Andrew Tridgell 2005 + Copyright (C) Stefan Metzmacher 2004 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/kerberos.h" +#include "auth/kerberos/kerberos.h" +#include "lib/socket/socket.h" +#include "lib/stream/packet.h" +#include "system/network.h" +#include "lib/events/events.h" +#include "param/param.h" +#include "libcli/resolve/resolve.h" + +/* + context structure for operations on cldap packets +*/ +struct smb_krb5_socket { + struct socket_context *sock; + + /* the fd event */ + struct fd_event *fde; + + NTSTATUS status; + DATA_BLOB request, reply; + + struct packet_context *packet; + + size_t partial_read; + + krb5_krbhst_info *hi; +}; + +static int smb_krb5_context_destroy_1(struct smb_krb5_context *ctx) +{ + krb5_free_context(ctx->krb5_context); + return 0; +} + +static int smb_krb5_context_destroy_2(struct smb_krb5_context *ctx) +{ + /* Otherwise krb5_free_context will try and close what we have already free()ed */ + krb5_set_warn_dest(ctx->krb5_context, NULL); + krb5_closelog(ctx->krb5_context, ctx->logf); + smb_krb5_context_destroy_1(ctx); + return 0; +} + +/* We never close down the DEBUG system, and no need to unreference the use */ +static void smb_krb5_debug_close(void *private) { + return; +} + +static void smb_krb5_debug_wrapper(const char *timestr, const char *msg, void *private) +{ + DEBUG(2, ("Kerberos: %s\n", msg)); +} + +/* + handle recv events on a smb_krb5 socket +*/ +static void smb_krb5_socket_recv(struct smb_krb5_socket *smb_krb5) +{ + TALLOC_CTX *tmp_ctx = talloc_new(smb_krb5); + DATA_BLOB blob; + size_t nread, dsize; + + smb_krb5->status = socket_pending(smb_krb5->sock, &dsize); + if (!NT_STATUS_IS_OK(smb_krb5->status)) { + talloc_free(tmp_ctx); + return; + } + + blob = data_blob_talloc(tmp_ctx, NULL, dsize); + if (blob.data == NULL && dsize != 0) { + smb_krb5->status = NT_STATUS_NO_MEMORY; + talloc_free(tmp_ctx); + return; + } + + smb_krb5->status = socket_recv(smb_krb5->sock, blob.data, blob.length, &nread); + if (!NT_STATUS_IS_OK(smb_krb5->status)) { + talloc_free(tmp_ctx); + return; + } + blob.length = nread; + + if (nread == 0) { + smb_krb5->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR; + talloc_free(tmp_ctx); + return; + } + + DEBUG(2,("Received smb_krb5 packet of length %d\n", + (int)blob.length)); + + talloc_steal(smb_krb5, blob.data); + smb_krb5->reply = blob; + talloc_free(tmp_ctx); +} + +static NTSTATUS smb_krb5_full_packet(void *private, DATA_BLOB data) +{ + struct smb_krb5_socket *smb_krb5 = talloc_get_type(private, struct smb_krb5_socket); + talloc_steal(smb_krb5, data.data); + smb_krb5->reply = data; + smb_krb5->reply.length -= 4; + smb_krb5->reply.data += 4; + return NT_STATUS_OK; +} + +/* + handle request timeouts +*/ +static void smb_krb5_request_timeout(struct event_context *event_ctx, + struct timed_event *te, struct timeval t, + void *private) +{ + struct smb_krb5_socket *smb_krb5 = talloc_get_type(private, struct smb_krb5_socket); + DEBUG(5,("Timed out smb_krb5 packet\n")); + smb_krb5->status = NT_STATUS_IO_TIMEOUT; +} + +static void smb_krb5_error_handler(void *private, NTSTATUS status) +{ + struct smb_krb5_socket *smb_krb5 = talloc_get_type(private, struct smb_krb5_socket); + smb_krb5->status = status; +} + +/* + handle send events on a smb_krb5 socket +*/ +static void smb_krb5_socket_send(struct smb_krb5_socket *smb_krb5) +{ + NTSTATUS status; + + size_t len; + + len = smb_krb5->request.length; + status = socket_send(smb_krb5->sock, &smb_krb5->request, &len); + + if (!NT_STATUS_IS_OK(status)) return; + + EVENT_FD_READABLE(smb_krb5->fde); + + EVENT_FD_NOT_WRITEABLE(smb_krb5->fde); + return; +} + + +/* + handle fd events on a smb_krb5_socket +*/ +static void smb_krb5_socket_handler(struct event_context *ev, struct fd_event *fde, + uint16_t flags, void *private) +{ + struct smb_krb5_socket *smb_krb5 = talloc_get_type(private, struct smb_krb5_socket); + switch (smb_krb5->hi->proto) { + case KRB5_KRBHST_UDP: + if (flags & EVENT_FD_READ) { + smb_krb5_socket_recv(smb_krb5); + return; + } + if (flags & EVENT_FD_WRITE) { + smb_krb5_socket_send(smb_krb5); + return; + } + /* not reached */ + return; + case KRB5_KRBHST_TCP: + if (flags & EVENT_FD_READ) { + packet_recv(smb_krb5->packet); + return; + } + if (flags & EVENT_FD_WRITE) { + packet_queue_run(smb_krb5->packet); + return; + } + /* not reached */ + return; + case KRB5_KRBHST_HTTP: + /* can't happen */ + break; + } +} + + +krb5_error_code smb_krb5_send_and_recv_func(krb5_context context, + void *data, + krb5_krbhst_info *hi, + time_t timeout, + const krb5_data *send_buf, + krb5_data *recv_buf) +{ + krb5_error_code ret; + NTSTATUS status; + struct socket_address *remote_addr; + const char *name; + struct addrinfo *ai, *a; + struct smb_krb5_socket *smb_krb5; + + struct event_context *ev = talloc_get_type(data, struct event_context); + + DATA_BLOB send_blob = data_blob_const(send_buf->data, send_buf->length); + + ret = krb5_krbhst_get_addrinfo(context, hi, &ai); + if (ret) { + return ret; + } + + for (a = ai; a; a = ai->ai_next) { + smb_krb5 = talloc(NULL, struct smb_krb5_socket); + if (!smb_krb5) { + return ENOMEM; + } + smb_krb5->hi = hi; + + switch (a->ai_family) { + case PF_INET: + name = "ipv4"; + break; +#ifdef HAVE_IPV6 + case PF_INET6: + name = "ipv6"; + break; +#endif + default: + talloc_free(smb_krb5); + return EINVAL; + } + + status = NT_STATUS_INVALID_PARAMETER; + switch (hi->proto) { + case KRB5_KRBHST_UDP: + if (lp_parm_bool(global_loadparm, NULL, "krb5", "udp", true)) { + status = socket_create(name, SOCKET_TYPE_DGRAM, &smb_krb5->sock, 0); + } + break; + case KRB5_KRBHST_TCP: + if (lp_parm_bool(global_loadparm, NULL, "krb5", "tcp", true)) { + status = socket_create(name, SOCKET_TYPE_STREAM, &smb_krb5->sock, 0); + } + break; + case KRB5_KRBHST_HTTP: + talloc_free(smb_krb5); + return EINVAL; + } + if (!NT_STATUS_IS_OK(status)) { + talloc_free(smb_krb5); + continue; + } + + talloc_steal(smb_krb5, smb_krb5->sock); + + remote_addr = socket_address_from_sockaddr(smb_krb5, a->ai_addr, a->ai_addrlen); + if (!remote_addr) { + talloc_free(smb_krb5); + continue; + } + + status = socket_connect_ev(smb_krb5->sock, NULL, remote_addr, 0, + NULL, ev); + if (!NT_STATUS_IS_OK(status)) { + talloc_free(smb_krb5); + continue; + } + talloc_free(remote_addr); + + /* Setup the FDE, start listening for read events + * from the start (otherwise we may miss a socket + * drop) and mark as AUTOCLOSE along with the fde */ + + /* Ths is equivilant to EVENT_FD_READABLE(smb_krb5->fde) */ + smb_krb5->fde = event_add_fd(ev, smb_krb5->sock, + socket_get_fd(smb_krb5->sock), + EVENT_FD_READ|EVENT_FD_AUTOCLOSE, + smb_krb5_socket_handler, smb_krb5); + /* its now the job of the event layer to close the socket */ + socket_set_flags(smb_krb5->sock, SOCKET_FLAG_NOCLOSE); + + event_add_timed(ev, smb_krb5, + timeval_current_ofs(timeout, 0), + smb_krb5_request_timeout, smb_krb5); + + + smb_krb5->status = NT_STATUS_OK; + smb_krb5->reply = data_blob(NULL, 0); + + switch (hi->proto) { + case KRB5_KRBHST_UDP: + EVENT_FD_WRITEABLE(smb_krb5->fde); + smb_krb5->request = send_blob; + break; + case KRB5_KRBHST_TCP: + + smb_krb5->packet = packet_init(smb_krb5); + if (smb_krb5->packet == NULL) { + talloc_free(smb_krb5); + return ENOMEM; + } + packet_set_private(smb_krb5->packet, smb_krb5); + packet_set_socket(smb_krb5->packet, smb_krb5->sock); + packet_set_callback(smb_krb5->packet, smb_krb5_full_packet); + packet_set_full_request(smb_krb5->packet, packet_full_request_u32); + packet_set_error_handler(smb_krb5->packet, smb_krb5_error_handler); + packet_set_event_context(smb_krb5->packet, ev); + packet_set_fde(smb_krb5->packet, smb_krb5->fde); + + smb_krb5->request = data_blob_talloc(smb_krb5, NULL, send_blob.length + 4); + RSIVAL(smb_krb5->request.data, 0, send_blob.length); + memcpy(smb_krb5->request.data+4, send_blob.data, send_blob.length); + packet_send(smb_krb5->packet, smb_krb5->request); + break; + case KRB5_KRBHST_HTTP: + talloc_free(smb_krb5); + return EINVAL; + } + while ((NT_STATUS_IS_OK(smb_krb5->status)) && !smb_krb5->reply.length) { + if (event_loop_once(ev) != 0) { + talloc_free(smb_krb5); + return EINVAL; + } + } + if (NT_STATUS_EQUAL(smb_krb5->status, NT_STATUS_IO_TIMEOUT)) { + talloc_free(smb_krb5); + continue; + } + + if (!NT_STATUS_IS_OK(smb_krb5->status)) { + DEBUG(2,("Error reading smb_krb5 reply packet: %s\n", nt_errstr(smb_krb5->status))); + talloc_free(smb_krb5); + continue; + } + + ret = krb5_data_copy(recv_buf, smb_krb5->reply.data, smb_krb5->reply.length); + if (ret) { + talloc_free(smb_krb5); + return ret; + } + talloc_free(smb_krb5); + + break; + } + if (a) { + return 0; + } + return KRB5_KDC_UNREACH; +} + +krb5_error_code smb_krb5_init_context(void *parent_ctx, + struct event_context *ev, + struct loadparm_context *lp_ctx, + struct smb_krb5_context **smb_krb5_context) +{ + krb5_error_code ret; + TALLOC_CTX *tmp_ctx; + char **config_files; + const char *config_file; + + initialize_krb5_error_table(); + + tmp_ctx = talloc_new(parent_ctx); + *smb_krb5_context = talloc(tmp_ctx, struct smb_krb5_context); + + if (!*smb_krb5_context || !tmp_ctx) { + talloc_free(tmp_ctx); + return ENOMEM; + } + + ret = krb5_init_context(&(*smb_krb5_context)->krb5_context); + if (ret) { + DEBUG(1,("krb5_init_context failed (%s)\n", + error_message(ret))); + talloc_free(tmp_ctx); + return ret; + } + + talloc_set_destructor(*smb_krb5_context, smb_krb5_context_destroy_1); + + config_file = config_path(tmp_ctx, lp_ctx, "krb5.conf"); + if (!config_file) { + talloc_free(tmp_ctx); + return ENOMEM; + } + + /* Use our local krb5.conf file by default */ + ret = krb5_prepend_config_files_default(config_file == NULL?"":config_file, &config_files); + if (ret) { + DEBUG(1,("krb5_prepend_config_files_default failed (%s)\n", + smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx))); + talloc_free(tmp_ctx); + return ret; + } + + ret = krb5_set_config_files((*smb_krb5_context)->krb5_context, + config_files); + krb5_free_config_files(config_files); + if (ret) { + DEBUG(1,("krb5_set_config_files failed (%s)\n", + smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx))); + talloc_free(tmp_ctx); + return ret; + } + + if (lp_realm(lp_ctx) && *lp_realm(lp_ctx)) { + char *upper_realm = strupper_talloc(tmp_ctx, lp_realm(lp_ctx)); + if (!upper_realm) { + DEBUG(1,("gensec_krb5_start: could not uppercase realm: %s\n", lp_realm(lp_ctx))); + talloc_free(tmp_ctx); + return ENOMEM; + } + ret = krb5_set_default_realm((*smb_krb5_context)->krb5_context, upper_realm); + if (ret) { + DEBUG(1,("krb5_set_default_realm failed (%s)\n", + smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx))); + talloc_free(tmp_ctx); + return ret; + } + } + + /* TODO: Should we have a different name here? */ + ret = krb5_initlog((*smb_krb5_context)->krb5_context, "Samba", &(*smb_krb5_context)->logf); + + if (ret) { + DEBUG(1,("krb5_initlog failed (%s)\n", + smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx))); + talloc_free(tmp_ctx); + return ret; + } + + talloc_set_destructor(*smb_krb5_context, smb_krb5_context_destroy_2); + + ret = krb5_addlog_func((*smb_krb5_context)->krb5_context, (*smb_krb5_context)->logf, 0 /* min */, -1 /* max */, + smb_krb5_debug_wrapper, smb_krb5_debug_close, NULL); + if (ret) { + DEBUG(1,("krb5_addlog_func failed (%s)\n", + smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx))); + talloc_free(tmp_ctx); + return ret; + } + krb5_set_warn_dest((*smb_krb5_context)->krb5_context, (*smb_krb5_context)->logf); + + /* Set use of our socket lib */ + ret = krb5_set_send_to_kdc_func((*smb_krb5_context)->krb5_context, + smb_krb5_send_and_recv_func, + ev); + if (ret) { + DEBUG(1,("krb5_set_send_recv_func failed (%s)\n", + smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx))); + talloc_free(tmp_ctx); + return ret; + } + + talloc_steal(parent_ctx, *smb_krb5_context); + talloc_free(tmp_ctx); + + /* Set options in kerberos */ + + krb5_set_dns_canonicalize_hostname((*smb_krb5_context)->krb5_context, + lp_parm_bool(lp_ctx, NULL, "krb5", "set_dns_canonicalize", false)); + + return 0; +} + diff --git a/source4/auth/kerberos/krb5_init_context.h b/source4/auth/kerberos/krb5_init_context.h new file mode 100644 index 0000000000..162a19a4ab --- /dev/null +++ b/source4/auth/kerberos/krb5_init_context.h @@ -0,0 +1,37 @@ +/* + Unix SMB/CIFS implementation. + simple kerberos5 routines for active directory + Copyright (C) Andrew Bartlett 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +struct smb_krb5_context { + krb5_context krb5_context; + krb5_log_facility *logf; +}; + +struct event_context; +struct loadparm_context; +krb5_error_code smb_krb5_init_context(void *parent_ctx, struct event_context *ev, + struct loadparm_context *lp_ctx, + struct smb_krb5_context **smb_krb5_context); +void smb_krb5_free_context(struct smb_krb5_context *smb_krb5_context); + +krb5_error_code smb_krb5_send_and_recv_func(krb5_context context, + void *data, + krb5_krbhst_info *hi, + time_t timeout, + const krb5_data *send_buf, + krb5_data *recv_buf); diff --git a/source4/auth/ntlm/auth.c b/source4/auth/ntlm/auth.c new file mode 100644 index 0000000000..0f1ef3ccdb --- /dev/null +++ b/source4/auth/ntlm/auth.c @@ -0,0 +1,538 @@ +/* + Unix SMB/CIFS implementation. + Password and authentication handling + Copyright (C) Andrew Bartlett 2001-2002 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/util/dlinklist.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "lib/events/events.h" +#include "param/param.h" + +/*************************************************************************** + Set a fixed challenge +***************************************************************************/ +_PUBLIC_ NTSTATUS auth_context_set_challenge(struct auth_context *auth_ctx, const uint8_t chal[8], const char *set_by) +{ + auth_ctx->challenge.set_by = talloc_strdup(auth_ctx, set_by); + NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.set_by); + + auth_ctx->challenge.data = data_blob_talloc(auth_ctx, chal, 8); + NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data); + + return NT_STATUS_OK; +} + +/*************************************************************************** + Set a fixed challenge +***************************************************************************/ +bool auth_challenge_may_be_modified(struct auth_context *auth_ctx) +{ + return auth_ctx->challenge.may_be_modified; +} + +/**************************************************************************** + Try to get a challenge out of the various authentication modules. + Returns a const char of length 8 bytes. +****************************************************************************/ +_PUBLIC_ NTSTATUS auth_get_challenge(struct auth_context *auth_ctx, const uint8_t **_chal) +{ + NTSTATUS nt_status; + struct auth_method_context *method; + + if (auth_ctx->challenge.data.length) { + DEBUG(5, ("auth_get_challenge: returning previous challenge by module %s (normal)\n", + auth_ctx->challenge.set_by)); + *_chal = auth_ctx->challenge.data.data; + return NT_STATUS_OK; + } + + for (method = auth_ctx->methods; method; method = method->next) { + DATA_BLOB challenge = data_blob(NULL,0); + + nt_status = method->ops->get_challenge(method, auth_ctx, &challenge); + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOT_IMPLEMENTED)) { + continue; + } + + NT_STATUS_NOT_OK_RETURN(nt_status); + + if (challenge.length != 8) { + DEBUG(0, ("auth_get_challenge: invalid challenge (length %u) by mothod [%s]\n", + (unsigned)challenge.length, method->ops->name)); + return NT_STATUS_INTERNAL_ERROR; + } + + auth_ctx->challenge.data = challenge; + auth_ctx->challenge.set_by = method->ops->name; + + break; + } + + if (!auth_ctx->challenge.set_by) { + uint8_t chal[8]; + generate_random_buffer(chal, 8); + + auth_ctx->challenge.data = data_blob_talloc(auth_ctx, chal, 8); + NT_STATUS_HAVE_NO_MEMORY(auth_ctx->challenge.data.data); + auth_ctx->challenge.set_by = "random"; + + auth_ctx->challenge.may_be_modified = true; + } + + DEBUG(10,("auth_get_challenge: challenge set by %s\n", + auth_ctx->challenge.set_by)); + + *_chal = auth_ctx->challenge.data.data; + return NT_STATUS_OK; +} + +struct auth_check_password_sync_state { + bool finished; + NTSTATUS status; + struct auth_serversupplied_info *server_info; +}; + +static void auth_check_password_sync_callback(struct auth_check_password_request *req, + void *private_data) +{ + struct auth_check_password_sync_state *s = talloc_get_type(private_data, + struct auth_check_password_sync_state); + + s->finished = true; + s->status = auth_check_password_recv(req, s, &s->server_info); +} + +/** + * Check a user's Plaintext, LM or NTLM password. + * (sync version) + * + * Check a user's password, as given in the user_info struct and return various + * interesting details in the server_info struct. + * + * The return value takes precedence over the contents of the server_info + * struct. When the return is other than NT_STATUS_OK the contents + * of that structure is undefined. + * + * @param auth_ctx Supplies the challenges and some other data. + * Must be created with auth_context_create(), and the challenges should be + * filled in, either at creation or by calling the challenge geneation + * function auth_get_challenge(). + * + * @param user_info Contains the user supplied components, including the passwords. + * + * @param mem_ctx The parent memory context for the server_info structure + * + * @param server_info If successful, contains information about the authentication, + * including a SAM_ACCOUNT struct describing the user. + * + * @return An NTSTATUS with NT_STATUS_OK or an appropriate error. + * + **/ + +_PUBLIC_ NTSTATUS auth_check_password(struct auth_context *auth_ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info) +{ + struct auth_check_password_sync_state *sync_state; + NTSTATUS status; + + sync_state = talloc_zero(auth_ctx, struct auth_check_password_sync_state); + NT_STATUS_HAVE_NO_MEMORY(sync_state); + + auth_check_password_send(auth_ctx, user_info, auth_check_password_sync_callback, sync_state); + + while (!sync_state->finished) { + event_loop_once(auth_ctx->event_ctx); + } + + status = sync_state->status; + + if (NT_STATUS_IS_OK(status)) { + *server_info = talloc_steal(mem_ctx, sync_state->server_info); + } + + talloc_free(sync_state); + return status; +} + +struct auth_check_password_request { + struct auth_context *auth_ctx; + const struct auth_usersupplied_info *user_info; + struct auth_serversupplied_info *server_info; + struct auth_method_context *method; + NTSTATUS status; + struct { + void (*fn)(struct auth_check_password_request *req, void *private_data); + void *private_data; + } callback; +}; + +static void auth_check_password_async_timed_handler(struct event_context *ev, struct timed_event *te, + struct timeval t, void *ptr) +{ + struct auth_check_password_request *req = talloc_get_type(ptr, struct auth_check_password_request); + req->status = req->method->ops->check_password(req->method, req, req->user_info, &req->server_info); + req->callback.fn(req, req->callback.private_data); +} + +/** + * Check a user's Plaintext, LM or NTLM password. + * async send hook + * + * Check a user's password, as given in the user_info struct and return various + * interesting details in the server_info struct. + * + * The return value takes precedence over the contents of the server_info + * struct. When the return is other than NT_STATUS_OK the contents + * of that structure is undefined. + * + * @param auth_ctx Supplies the challenges and some other data. + * Must be created with make_auth_context(), and the challenges should be + * filled in, either at creation or by calling the challenge geneation + * function auth_get_challenge(). + * + * @param user_info Contains the user supplied components, including the passwords. + * + * @param callback A callback function which will be called when the operation is finished. + * The callback function needs to call auth_check_password_recv() to get the return values + * + * @param private_data A private pointer which will ba passed to the callback function + * + **/ + +_PUBLIC_ void auth_check_password_send(struct auth_context *auth_ctx, + const struct auth_usersupplied_info *user_info, + void (*callback)(struct auth_check_password_request *req, void *private_data), + void *private_data) +{ + /* if all the modules say 'not for me' this is reasonable */ + NTSTATUS nt_status; + struct auth_method_context *method; + const uint8_t *challenge; + struct auth_usersupplied_info *user_info_tmp; + struct auth_check_password_request *req = NULL; + + DEBUG(3, ("auth_check_password_send: Checking password for unmapped user [%s]\\[%s]@[%s]\n", + user_info->client.domain_name, user_info->client.account_name, user_info->workstation_name)); + + req = talloc_zero(auth_ctx, struct auth_check_password_request); + if (!req) { + callback(NULL, private_data); + return; + } + req->auth_ctx = auth_ctx; + req->user_info = user_info; + req->callback.fn = callback; + req->callback.private_data = private_data; + + if (!user_info->mapped_state) { + nt_status = map_user_info(req, lp_workgroup(auth_ctx->lp_ctx), user_info, &user_info_tmp); + if (!NT_STATUS_IS_OK(nt_status)) goto failed; + user_info = user_info_tmp; + req->user_info = user_info_tmp; + } + + DEBUGADD(3,("auth_check_password_send: mapped user is: [%s]\\[%s]@[%s]\n", + user_info->mapped.domain_name, user_info->mapped.account_name, user_info->workstation_name)); + + nt_status = auth_get_challenge(auth_ctx, &challenge); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(0, ("auth_check_password_send: Invalid challenge (length %u) stored for this auth context set_by %s - cannot continue: %s\n", + (unsigned)auth_ctx->challenge.data.length, auth_ctx->challenge.set_by, nt_errstr(nt_status))); + goto failed; + } + + if (auth_ctx->challenge.set_by) { + DEBUG(10, ("auth_check_password_send: auth_context challenge created by %s\n", + auth_ctx->challenge.set_by)); + } + + DEBUG(10, ("auth_check_password_send: challenge is: \n")); + dump_data(5, auth_ctx->challenge.data.data, auth_ctx->challenge.data.length); + + nt_status = NT_STATUS_NO_SUCH_USER; /* If all the modules say 'not for me', then this is reasonable */ + for (method = auth_ctx->methods; method; method = method->next) { + NTSTATUS result; + struct timed_event *te = NULL; + + /* check if the module wants to chek the password */ + result = method->ops->want_check(method, req, user_info); + if (NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) { + DEBUG(11,("auth_check_password_send: %s had nothing to say\n", method->ops->name)); + continue; + } + + nt_status = result; + req->method = method; + + if (!NT_STATUS_IS_OK(nt_status)) break; + + te = event_add_timed(auth_ctx->event_ctx, req, + timeval_zero(), + auth_check_password_async_timed_handler, req); + if (!te) { + nt_status = NT_STATUS_NO_MEMORY; + goto failed; + } + return; + } + +failed: + req->status = nt_status; + req->callback.fn(req, req->callback.private_data); +} + +/** + * Check a user's Plaintext, LM or NTLM password. + * async receive function + * + * The return value takes precedence over the contents of the server_info + * struct. When the return is other than NT_STATUS_OK the contents + * of that structure is undefined. + * + * + * @param req The async auth_check_password state, passes to the callers callback function + * + * @param mem_ctx The parent memory context for the server_info structure + * + * @param server_info If successful, contains information about the authentication, + * including a SAM_ACCOUNT struct describing the user. + * + * @return An NTSTATUS with NT_STATUS_OK or an appropriate error. + * + **/ + +_PUBLIC_ NTSTATUS auth_check_password_recv(struct auth_check_password_request *req, + TALLOC_CTX *mem_ctx, + struct auth_serversupplied_info **server_info) +{ + NTSTATUS status; + + NT_STATUS_HAVE_NO_MEMORY(req); + + if (NT_STATUS_IS_OK(req->status)) { + DEBUG(5,("auth_check_password_recv: %s authentication for user [%s\\%s] succeeded\n", + req->method->ops->name, req->server_info->domain_name, req->server_info->account_name)); + + *server_info = talloc_steal(mem_ctx, req->server_info); + } else { + DEBUG(2,("auth_check_password_recv: %s authentication for user [%s\\%s] FAILED with error %s\n", + (req->method ? req->method->ops->name : "NO_METHOD"), + req->user_info->mapped.domain_name, + req->user_info->mapped.account_name, + nt_errstr(req->status))); + } + + status = req->status; + talloc_free(req); + return status; +} + +/*************************************************************************** + Make a auth_info struct for the auth subsystem + - Allow the caller to specify the methods to use +***************************************************************************/ +_PUBLIC_ NTSTATUS auth_context_create_methods(TALLOC_CTX *mem_ctx, const char **methods, + struct event_context *ev, + struct messaging_context *msg, + struct loadparm_context *lp_ctx, + struct auth_context **auth_ctx) +{ + int i; + struct auth_context *ctx; + + if (!methods) { + DEBUG(0,("auth_context_create: No auth method list!?\n")); + return NT_STATUS_INTERNAL_ERROR; + } + + if (!ev) { + DEBUG(0,("auth_context_create: called with out event context\n")); + return NT_STATUS_INTERNAL_ERROR; + } + + if (!msg) { + DEBUG(0,("auth_context_create: called with out messaging context\n")); + return NT_STATUS_INTERNAL_ERROR; + } + + ctx = talloc(mem_ctx, struct auth_context); + NT_STATUS_HAVE_NO_MEMORY(ctx); + ctx->challenge.set_by = NULL; + ctx->challenge.may_be_modified = false; + ctx->challenge.data = data_blob(NULL, 0); + ctx->methods = NULL; + ctx->event_ctx = ev; + ctx->msg_ctx = msg; + ctx->lp_ctx = lp_ctx; + + for (i=0; methods[i] ; i++) { + struct auth_method_context *method; + + method = talloc(ctx, struct auth_method_context); + NT_STATUS_HAVE_NO_MEMORY(method); + + method->ops = auth_backend_byname(methods[i]); + if (!method->ops) { + DEBUG(1,("auth_context_create: failed to find method=%s\n", + methods[i])); + return NT_STATUS_INTERNAL_ERROR; + } + method->auth_ctx = ctx; + method->depth = i; + DLIST_ADD_END(ctx->methods, method, struct auth_method_context *); + } + + if (!ctx->methods) { + return NT_STATUS_INTERNAL_ERROR; + } + + *auth_ctx = ctx; + + return NT_STATUS_OK; +} +/*************************************************************************** + Make a auth_info struct for the auth subsystem + - Uses default auth_methods, depending on server role and smb.conf settings +***************************************************************************/ +_PUBLIC_ NTSTATUS auth_context_create(TALLOC_CTX *mem_ctx, + struct event_context *ev, + struct messaging_context *msg, + struct loadparm_context *lp_ctx, + struct auth_context **auth_ctx) +{ + const char **auth_methods = NULL; + switch (lp_server_role(lp_ctx)) { + case ROLE_STANDALONE: + auth_methods = lp_parm_string_list(mem_ctx, lp_ctx, NULL, "auth methods", "standalone", NULL); + break; + case ROLE_DOMAIN_MEMBER: + auth_methods = lp_parm_string_list(mem_ctx, lp_ctx, NULL, "auth methods", "member server", NULL); + break; + case ROLE_DOMAIN_CONTROLLER: + auth_methods = lp_parm_string_list(mem_ctx, lp_ctx, NULL, "auth methods", "domain controller", NULL); + break; + } + return auth_context_create_methods(mem_ctx, auth_methods, ev, msg, lp_ctx, auth_ctx); +} + + +/* the list of currently registered AUTH backends */ +static struct auth_backend { + const struct auth_operations *ops; +} *backends = NULL; +static int num_backends; + +/* + register a AUTH backend. + + The 'name' can be later used by other backends to find the operations + structure for this backend. +*/ +_PUBLIC_ NTSTATUS auth_register(const struct auth_operations *ops) +{ + struct auth_operations *new_ops; + + if (auth_backend_byname(ops->name) != NULL) { + /* its already registered! */ + DEBUG(0,("AUTH backend '%s' already registered\n", + ops->name)); + return NT_STATUS_OBJECT_NAME_COLLISION; + } + + backends = talloc_realloc(talloc_autofree_context(), backends, + struct auth_backend, num_backends+1); + NT_STATUS_HAVE_NO_MEMORY(backends); + + new_ops = talloc_memdup(backends, ops, sizeof(*ops)); + NT_STATUS_HAVE_NO_MEMORY(new_ops); + new_ops->name = talloc_strdup(new_ops, ops->name); + NT_STATUS_HAVE_NO_MEMORY(new_ops->name); + + backends[num_backends].ops = new_ops; + + num_backends++; + + DEBUG(3,("AUTH backend '%s' registered\n", + ops->name)); + + return NT_STATUS_OK; +} + +/* + return the operations structure for a named backend of the specified type +*/ +const struct auth_operations *auth_backend_byname(const char *name) +{ + int i; + + for (i=0;i<num_backends;i++) { + if (strcmp(backends[i].ops->name, name) == 0) { + return backends[i].ops; + } + } + + return NULL; +} + +/* + return the AUTH interface version, and the size of some critical types + This can be used by backends to either detect compilation errors, or provide + multiple implementations for different smbd compilation options in one module +*/ +const struct auth_critical_sizes *auth_interface_version(void) +{ + static const struct auth_critical_sizes critical_sizes = { + AUTH_INTERFACE_VERSION, + sizeof(struct auth_operations), + sizeof(struct auth_method_context), + sizeof(struct auth_context), + sizeof(struct auth_usersupplied_info), + sizeof(struct auth_serversupplied_info) + }; + + return &critical_sizes; +} + +_PUBLIC_ NTSTATUS auth_init(void) +{ + static bool initialized = false; + extern NTSTATUS auth_developer_init(void); + extern NTSTATUS auth_winbind_init(void); + extern NTSTATUS auth_anonymous_init(void); + extern NTSTATUS auth_unix_init(void); + extern NTSTATUS auth_sam_init(void); + extern NTSTATUS auth_server_init(void); + + init_module_fn static_init[] = { STATIC_auth_MODULES }; + + if (initialized) return NT_STATUS_OK; + initialized = true; + + run_init_functions(static_init); + + return NT_STATUS_OK; +} + +NTSTATUS server_service_auth_init(void) +{ + return auth_init(); +} diff --git a/source4/auth/ntlm/auth_anonymous.c b/source4/auth/ntlm/auth_anonymous.c new file mode 100644 index 0000000000..c889071878 --- /dev/null +++ b/source4/auth/ntlm/auth_anonymous.c @@ -0,0 +1,78 @@ +/* + Unix SMB/CIFS implementation. + + Anonymous Authentification + + Copyright (C) Stefan Metzmacher 2004-2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "param/param.h" + +/** + * Return a anonymous logon for anonymous users (username = "") + * + * Typically used as the first module in the auth chain, this allows + * anonymou logons to be dealt with in one place. Non-anonymou logons 'fail' + * and pass onto the next module. + **/ +static NTSTATUS anonymous_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + if (user_info->client.account_name && *user_info->client.account_name) { + return NT_STATUS_NOT_IMPLEMENTED; + } + + return NT_STATUS_OK; +} + +/** + * Return a anonymous logon for anonymous users (username = "") + * + * Typically used as the first module in the auth chain, this allows + * anonymou logons to be dealt with in one place. Non-anonymou logons 'fail' + * and pass onto the next module. + **/ +static NTSTATUS anonymous_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **_server_info) +{ + return auth_anonymous_server_info(mem_ctx, lp_netbios_name(ctx->auth_ctx->lp_ctx), _server_info); +} + +static const struct auth_operations anonymous_auth_ops = { + .name = "anonymous", + .get_challenge = auth_get_challenge_not_implemented, + .want_check = anonymous_want_check, + .check_password = anonymous_check_password +}; + +_PUBLIC_ NTSTATUS auth_anonymous_init(void) +{ + NTSTATUS ret; + + ret = auth_register(&anonymous_auth_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'anonymous' auth backend!\n")); + return ret; + } + + return ret; +} diff --git a/source4/auth/ntlm/auth_developer.c b/source4/auth/ntlm/auth_developer.c new file mode 100644 index 0000000000..3b8c83c349 --- /dev/null +++ b/source4/auth/ntlm/auth_developer.c @@ -0,0 +1,207 @@ +/* + Unix SMB/CIFS implementation. + Generic authentication types + Copyright (C) Andrew Bartlett 2001-2002 + Copyright (C) Jelmer Vernooij 2002 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "libcli/security/security.h" +#include "librpc/gen_ndr/ndr_samr.h" + +static NTSTATUS name_to_ntstatus_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + return NT_STATUS_OK; +} + +/** + * Return an error based on username + * + * This function allows the testing of obsure errors, as well as the generation + * of NT_STATUS -> DOS error mapping tables. + * + * This module is of no value to end-users. + * + * The password is ignored. + * + * @return An NTSTATUS value based on the username + **/ + +static NTSTATUS name_to_ntstatus_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **_server_info) +{ + NTSTATUS nt_status; + struct auth_serversupplied_info *server_info; + uint32_t error_num; + const char *user; + + user = user_info->client.account_name; + + if (strncasecmp("NT_STATUS", user, strlen("NT_STATUS")) == 0) { + nt_status = nt_status_string_to_code(user); + } else { + error_num = strtoul(user, NULL, 16); + DEBUG(5,("name_to_ntstatus_check_password: Error for user %s was 0x%08X\n", user, error_num)); + nt_status = NT_STATUS(error_num); + } + NT_STATUS_NOT_OK_RETURN(nt_status); + + server_info = talloc(mem_ctx, struct auth_serversupplied_info); + NT_STATUS_HAVE_NO_MEMORY(server_info); + + server_info->account_sid = dom_sid_parse_talloc(server_info, SID_NT_ANONYMOUS); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_sid); + + /* is this correct? */ + server_info->primary_group_sid = dom_sid_parse_talloc(server_info, SID_BUILTIN_GUESTS); + NT_STATUS_HAVE_NO_MEMORY(server_info->primary_group_sid); + + server_info->n_domain_groups = 0; + server_info->domain_groups = NULL; + + /* annoying, but the Anonymous really does have a session key, + and it is all zeros! */ + server_info->user_session_key = data_blob_talloc(server_info, NULL, 16); + NT_STATUS_HAVE_NO_MEMORY(server_info->user_session_key.data); + + server_info->lm_session_key = data_blob_talloc(server_info, NULL, 16); + NT_STATUS_HAVE_NO_MEMORY(server_info->lm_session_key.data); + + data_blob_clear(&server_info->user_session_key); + data_blob_clear(&server_info->lm_session_key); + + server_info->account_name = talloc_asprintf(server_info, "NAME TO NTSTATUS %s ANONYMOUS LOGON", user); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_name); + + server_info->domain_name = talloc_strdup(server_info, "NT AUTHORITY"); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_name); + + server_info->full_name = talloc_asprintf(server_info, "NAME TO NTSTATUS %s Anonymous Logon", user); + NT_STATUS_HAVE_NO_MEMORY(server_info->full_name); + + server_info->logon_script = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_script); + + server_info->profile_path = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->profile_path); + + server_info->home_directory = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_directory); + + server_info->home_drive = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_drive); + + server_info->last_logon = 0; + server_info->last_logoff = 0; + server_info->acct_expiry = 0; + server_info->last_password_change = 0; + server_info->allow_password_change = 0; + server_info->force_password_change = 0; + + server_info->logon_count = 0; + server_info->bad_password_count = 0; + + server_info->acct_flags = ACB_NORMAL; + + server_info->authenticated = false; + + *_server_info = server_info; + + return nt_status; +} + +static const struct auth_operations name_to_ntstatus_auth_ops = { + .name = "name_to_ntstatus", + .get_challenge = auth_get_challenge_not_implemented, + .want_check = name_to_ntstatus_want_check, + .check_password = name_to_ntstatus_check_password +}; + +/** + * Return a 'fixed' challenge instead of a variable one. + * + * The idea of this function is to make packet snifs consistant + * with a fixed challenge, so as to aid debugging. + * + * This module is of no value to end-users. + * + * This module does not actually authenticate the user, but + * just pretenteds to need a specified challenge. + * This module removes *all* security from the challenge-response system + * + * @return NT_STATUS_UNSUCCESSFUL + **/ +static NTSTATUS fixed_challenge_get_challenge(struct auth_method_context *ctx, TALLOC_CTX *mem_ctx, DATA_BLOB *_blob) +{ + DATA_BLOB blob; + const char *challenge = "I am a teapot"; + + blob = data_blob_talloc(mem_ctx, challenge, 8); + NT_STATUS_HAVE_NO_MEMORY(blob.data); + + *_blob = blob; + return NT_STATUS_OK; +} + +static NTSTATUS fixed_challenge_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + /* don't handle any users */ + return NT_STATUS_NOT_IMPLEMENTED; +} + +static NTSTATUS fixed_challenge_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **_server_info) +{ + /* don't handle any users */ + return NT_STATUS_NO_SUCH_USER; +} + +static const struct auth_operations fixed_challenge_auth_ops = { + .name = "fixed_challenge", + .get_challenge = fixed_challenge_get_challenge, + .want_check = fixed_challenge_want_check, + .check_password = fixed_challenge_check_password +}; + +_PUBLIC_ NTSTATUS auth_developer_init(void) +{ + NTSTATUS ret; + + ret = auth_register(&name_to_ntstatus_auth_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'name_to_ntstatus' auth backend!\n")); + return ret; + } + + ret = auth_register(&fixed_challenge_auth_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'fixed_challenge' auth backend!\n")); + return ret; + } + + return ret; +} diff --git a/source4/auth/ntlm/auth_proto.h b/source4/auth/ntlm/auth_proto.h new file mode 100644 index 0000000000..572c1a4ca7 --- /dev/null +++ b/source4/auth/ntlm/auth_proto.h @@ -0,0 +1,50 @@ +#ifndef __AUTH_NTLM_AUTH_PROTO_H__ +#define __AUTH_NTLM_AUTH_PROTO_H__ + +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) PRINTF_ATTRIBUTE(a1, a2) +/* This file was automatically generated by mkproto.pl. DO NOT EDIT */ + +/* this file contains prototypes for functions that are private + * to this subsystem or library. These functions should not be + * used outside this particular subsystem! */ + + +/* The following definitions come from auth/ntlm/auth.c */ + + +/*************************************************************************** + Set a fixed challenge +***************************************************************************/ +bool auth_challenge_may_be_modified(struct auth_context *auth_ctx) ; +const struct auth_operations *auth_backend_byname(const char *name); +const struct auth_critical_sizes *auth_interface_version(void); +NTSTATUS server_service_auth_init(void); + +/* The following definitions come from auth/ntlm/auth_util.c */ + +NTSTATUS auth_get_challenge_not_implemented(struct auth_method_context *ctx, TALLOC_CTX *mem_ctx, DATA_BLOB *challenge); + +/**************************************************************************** + Create an auth_usersupplied_data structure after appropriate mapping. +****************************************************************************/ +NTSTATUS map_user_info(TALLOC_CTX *mem_ctx, + const char *default_domain, + const struct auth_usersupplied_info *user_info, + struct auth_usersupplied_info **user_info_mapped); + +/**************************************************************************** + Create an auth_usersupplied_data structure after appropriate mapping. +****************************************************************************/ +NTSTATUS encrypt_user_info(TALLOC_CTX *mem_ctx, struct auth_context *auth_context, + enum auth_password_state to_state, + const struct auth_usersupplied_info *user_info_in, + const struct auth_usersupplied_info **user_info_encrypted); + +/* The following definitions come from auth/ntlm/auth_simple.c */ + +#undef _PRINTF_ATTRIBUTE +#define _PRINTF_ATTRIBUTE(a1, a2) + +#endif /* __AUTH_NTLM_AUTH_PROTO_H__ */ + diff --git a/source4/auth/ntlm/auth_sam.c b/source4/auth/ntlm/auth_sam.c new file mode 100644 index 0000000000..1b8233b8a4 --- /dev/null +++ b/source4/auth/ntlm/auth_sam.c @@ -0,0 +1,451 @@ +/* + Unix SMB/CIFS implementation. + Password and authentication handling + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2004 + Copyright (C) Gerald Carter 2003 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "librpc/gen_ndr/ndr_netlogon.h" +#include "system/time.h" +#include "lib/ldb/include/ldb.h" +#include "util/util_ldb.h" +#include "auth/auth.h" +#include "auth/ntlm/ntlm_check.h" +#include "auth/ntlm/auth_proto.h" +#include "auth/auth_sam.h" +#include "dsdb/samdb/samdb.h" +#include "libcli/security/security.h" +#include "libcli/ldap/ldap_ndr.h" +#include "param/param.h" + +extern const char *user_attrs[]; +extern const char *domain_ref_attrs[]; + +/**************************************************************************** + Look for the specified user in the sam, return ldb result structures +****************************************************************************/ + +static NTSTATUS authsam_search_account(TALLOC_CTX *mem_ctx, struct ldb_context *sam_ctx, + const char *account_name, + const char *domain_name, + struct ldb_message ***ret_msgs, + struct ldb_message ***ret_msgs_domain_ref) +{ + struct ldb_message **msgs_tmp; + struct ldb_message **msgs; + struct ldb_message **msgs_domain_ref; + struct ldb_dn *partitions_basedn = samdb_partitions_dn(sam_ctx, mem_ctx); + + int ret; + int ret_domain; + + struct ldb_dn *domain_dn = NULL; + + if (domain_name) { + domain_dn = samdb_domain_to_dn(sam_ctx, mem_ctx, domain_name); + if (!domain_dn) { + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + } + + /* pull the user attributes */ + ret = gendb_search(sam_ctx, mem_ctx, domain_dn, &msgs, user_attrs, + "(&(sAMAccountName=%s)(objectclass=user))", + ldb_binary_encode_string(mem_ctx, account_name)); + if (ret == -1) { + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + if (ret == 0) { + DEBUG(3,("sam_search_user: Couldn't find user [%s\\%s] in samdb, under %s\n", + domain_name, account_name, ldb_dn_get_linearized(domain_dn))); + return NT_STATUS_NO_SUCH_USER; + } + + if (ret > 1) { + DEBUG(0,("Found %d records matching user [%s]\n", ret, account_name)); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + if (!domain_dn) { + struct dom_sid *domain_sid; + + domain_sid = samdb_result_sid_prefix(mem_ctx, msgs[0], "objectSid"); + if (!domain_sid) { + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + /* find the domain's DN */ + ret = gendb_search(sam_ctx, mem_ctx, NULL, &msgs_tmp, NULL, + "(&(objectSid=%s)(objectClass=domain))", + ldap_encode_ndr_dom_sid(mem_ctx, domain_sid)); + if (ret == -1) { + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + if (ret == 0) { + DEBUG(3,("check_sam_security: Couldn't find domain_sid [%s] in passdb file.\n", + dom_sid_string(mem_ctx, domain_sid))); + return NT_STATUS_NO_SUCH_USER; + } + + if (ret > 1) { + DEBUG(0,("Found %d records matching domain_sid [%s]\n", + ret, dom_sid_string(mem_ctx, domain_sid))); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + domain_dn = msgs_tmp[0]->dn; + } + + ret_domain = gendb_search(sam_ctx, mem_ctx, partitions_basedn, &msgs_domain_ref, domain_ref_attrs, + "(nCName=%s)", ldb_dn_get_linearized(domain_dn)); + if (ret_domain == -1) { + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + if (ret_domain == 0) { + DEBUG(3,("check_sam_security: Couldn't find domain [%s] in passdb file.\n", + ldb_dn_get_linearized(msgs_tmp[0]->dn))); + return NT_STATUS_NO_SUCH_USER; + } + + if (ret_domain > 1) { + DEBUG(0,("Found %d records matching domain [%s]\n", + ret_domain, ldb_dn_get_linearized(msgs_tmp[0]->dn))); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + *ret_msgs = msgs; + *ret_msgs_domain_ref = msgs_domain_ref; + + return NT_STATUS_OK; +} + +/**************************************************************************** + Do a specific test for an smb password being correct, given a smb_password and + the lanman and NT responses. +****************************************************************************/ +static NTSTATUS authsam_password_ok(struct auth_context *auth_context, + TALLOC_CTX *mem_ctx, + uint16_t acct_flags, + const struct samr_Password *lm_pwd, + const struct samr_Password *nt_pwd, + const struct auth_usersupplied_info *user_info, + DATA_BLOB *user_sess_key, + DATA_BLOB *lm_sess_key) +{ + NTSTATUS status; + + if (acct_flags & ACB_PWNOTREQ) { + if (lp_null_passwords(auth_context->lp_ctx)) { + DEBUG(3,("Account for user '%s' has no password and null passwords are allowed.\n", + user_info->mapped.account_name)); + *lm_sess_key = data_blob(NULL, 0); + *user_sess_key = data_blob(NULL, 0); + return NT_STATUS_OK; + } else { + DEBUG(3,("Account for user '%s' has no password and null passwords are NOT allowed.\n", + user_info->mapped.account_name)); + return NT_STATUS_LOGON_FAILURE; + } + } + + switch (user_info->password_state) { + case AUTH_PASSWORD_PLAIN: + { + const struct auth_usersupplied_info *user_info_temp; + status = encrypt_user_info(mem_ctx, auth_context, + AUTH_PASSWORD_HASH, + user_info, &user_info_temp); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("Failed to convert plaintext password to password HASH: %s\n", nt_errstr(status))); + return status; + } + user_info = user_info_temp; + + /*fall through*/ + } + case AUTH_PASSWORD_HASH: + *lm_sess_key = data_blob(NULL, 0); + *user_sess_key = data_blob(NULL, 0); + status = hash_password_check(mem_ctx, + auth_context->lp_ctx, + user_info->password.hash.lanman, + user_info->password.hash.nt, + user_info->mapped.account_name, + lm_pwd, nt_pwd); + NT_STATUS_NOT_OK_RETURN(status); + break; + + case AUTH_PASSWORD_RESPONSE: + status = ntlm_password_check(mem_ctx, + auth_context->lp_ctx, + user_info->logon_parameters, + &auth_context->challenge.data, + &user_info->password.response.lanman, + &user_info->password.response.nt, + user_info->mapped.account_name, + user_info->client.account_name, + user_info->client.domain_name, + lm_pwd, nt_pwd, + user_sess_key, lm_sess_key); + NT_STATUS_NOT_OK_RETURN(status); + break; + } + + if (user_sess_key && user_sess_key->data) { + talloc_steal(auth_context, user_sess_key->data); + } + if (lm_sess_key && lm_sess_key->data) { + talloc_steal(auth_context, lm_sess_key->data); + } + + return NT_STATUS_OK; +} + + + +static NTSTATUS authsam_authenticate(struct auth_context *auth_context, + TALLOC_CTX *mem_ctx, struct ldb_context *sam_ctx, + struct ldb_message **msgs, + struct ldb_message **msgs_domain_ref, + const struct auth_usersupplied_info *user_info, + DATA_BLOB *user_sess_key, DATA_BLOB *lm_sess_key) +{ + struct samr_Password *lm_pwd, *nt_pwd; + NTSTATUS nt_status; + struct ldb_dn *domain_dn = samdb_result_dn(sam_ctx, mem_ctx, msgs_domain_ref[0], "nCName", NULL); + + uint16_t acct_flags = samdb_result_acct_flags(sam_ctx, mem_ctx, msgs[0], domain_dn); + + /* Quit if the account was locked out. */ + if (acct_flags & ACB_AUTOLOCK) { + DEBUG(3,("check_sam_security: Account for user %s was locked out.\n", + user_info->mapped.account_name)); + return NT_STATUS_ACCOUNT_LOCKED_OUT; + } + + /* You can only do an interactive login to normal accounts */ + if (user_info->flags & USER_INFO_INTERACTIVE_LOGON) { + if (!(acct_flags & ACB_NORMAL)) { + return NT_STATUS_NO_SUCH_USER; + } + } + + nt_status = samdb_result_passwords(mem_ctx, msgs[0], &lm_pwd, &nt_pwd); + NT_STATUS_NOT_OK_RETURN(nt_status); + + nt_status = authsam_password_ok(auth_context, mem_ctx, + acct_flags, lm_pwd, nt_pwd, + user_info, user_sess_key, lm_sess_key); + NT_STATUS_NOT_OK_RETURN(nt_status); + + nt_status = authsam_account_ok(mem_ctx, sam_ctx, + user_info->logon_parameters, + msgs[0], + msgs_domain_ref[0], + user_info->workstation_name, + user_info->mapped.account_name); + + return nt_status; +} + + + +static NTSTATUS authsam_check_password_internals(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const char *domain, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info) +{ + NTSTATUS nt_status; + const char *account_name = user_info->mapped.account_name; + struct ldb_message **msgs; + struct ldb_message **domain_ref_msgs; + struct ldb_context *sam_ctx; + DATA_BLOB user_sess_key, lm_sess_key; + TALLOC_CTX *tmp_ctx; + + if (!account_name || !*account_name) { + /* 'not for me' */ + return NT_STATUS_NOT_IMPLEMENTED; + } + + tmp_ctx = talloc_new(mem_ctx); + if (!tmp_ctx) { + return NT_STATUS_NO_MEMORY; + } + + sam_ctx = samdb_connect(tmp_ctx, ctx->auth_ctx->event_ctx, ctx->auth_ctx->lp_ctx, system_session(mem_ctx, ctx->auth_ctx->lp_ctx)); + if (sam_ctx == NULL) { + talloc_free(tmp_ctx); + return NT_STATUS_INVALID_SYSTEM_SERVICE; + } + + nt_status = authsam_search_account(tmp_ctx, sam_ctx, account_name, domain, &msgs, &domain_ref_msgs); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(tmp_ctx); + return nt_status; + } + + nt_status = authsam_authenticate(ctx->auth_ctx, tmp_ctx, sam_ctx, msgs, domain_ref_msgs, user_info, + &user_sess_key, &lm_sess_key); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(tmp_ctx); + return nt_status; + } + + nt_status = authsam_make_server_info(tmp_ctx, sam_ctx, lp_netbios_name(ctx->auth_ctx->lp_ctx), + msgs[0], domain_ref_msgs[0], + user_sess_key, lm_sess_key, + server_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(tmp_ctx); + return nt_status; + } + + talloc_steal(mem_ctx, *server_info); + talloc_free(tmp_ctx); + + return NT_STATUS_OK; +} + +static NTSTATUS authsam_ignoredomain_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + if (!user_info->mapped.account_name || !*user_info->mapped.account_name) { + return NT_STATUS_NOT_IMPLEMENTED; + } + + return NT_STATUS_OK; +} + +static NTSTATUS authsam_ignoredomain_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info) +{ + return authsam_check_password_internals(ctx, mem_ctx, NULL, user_info, server_info); +} + +/**************************************************************************** +Check SAM security (above) but with a few extra checks. +****************************************************************************/ +static NTSTATUS authsam_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + bool is_local_name, is_my_domain; + + if (!user_info->mapped.account_name || !*user_info->mapped.account_name) { + return NT_STATUS_NOT_IMPLEMENTED; + } + + is_local_name = lp_is_myname(ctx->auth_ctx->lp_ctx, + user_info->mapped.domain_name); + is_my_domain = lp_is_mydomain(ctx->auth_ctx->lp_ctx, + user_info->mapped.domain_name); + + /* check whether or not we service this domain/workgroup name */ + switch (lp_server_role(ctx->auth_ctx->lp_ctx)) { + case ROLE_STANDALONE: + return NT_STATUS_OK; + + case ROLE_DOMAIN_MEMBER: + if (!is_local_name) { + DEBUG(6,("authsam_check_password: %s is not one of my local names (DOMAIN_MEMBER)\n", + user_info->mapped.domain_name)); + return NT_STATUS_NOT_IMPLEMENTED; + } + return NT_STATUS_OK; + + case ROLE_DOMAIN_CONTROLLER: + if (!is_local_name && !is_my_domain) { + DEBUG(6,("authsam_check_password: %s is not one of my local names or domain name (DC)\n", + user_info->mapped.domain_name)); + return NT_STATUS_NOT_IMPLEMENTED; + } + return NT_STATUS_OK; + } + + DEBUG(6,("authsam_check_password: lp_server_role() has an undefined value\n")); + return NT_STATUS_NOT_IMPLEMENTED; +} + +/**************************************************************************** +Check SAM security (above) but with a few extra checks. +****************************************************************************/ +static NTSTATUS authsam_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info) +{ + const char *domain; + + /* check whether or not we service this domain/workgroup name */ + switch (lp_server_role(ctx->auth_ctx->lp_ctx)) { + case ROLE_STANDALONE: + case ROLE_DOMAIN_MEMBER: + domain = lp_netbios_name(ctx->auth_ctx->lp_ctx); + break; + + case ROLE_DOMAIN_CONTROLLER: + domain = lp_workgroup(ctx->auth_ctx->lp_ctx); + break; + + default: + return NT_STATUS_NO_SUCH_USER; + } + + return authsam_check_password_internals(ctx, mem_ctx, domain, user_info, server_info); +} + +static const struct auth_operations sam_ignoredomain_ops = { + .name = "sam_ignoredomain", + .get_challenge = auth_get_challenge_not_implemented, + .want_check = authsam_ignoredomain_want_check, + .check_password = authsam_ignoredomain_check_password +}; + +static const struct auth_operations sam_ops = { + .name = "sam", + .get_challenge = auth_get_challenge_not_implemented, + .want_check = authsam_want_check, + .check_password = authsam_check_password +}; + +_PUBLIC_ NTSTATUS auth_sam_init(void) +{ + NTSTATUS ret; + + ret = auth_register(&sam_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'sam' auth backend!\n")); + return ret; + } + + ret = auth_register(&sam_ignoredomain_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'sam_ignoredomain' auth backend!\n")); + return ret; + } + + return ret; +} diff --git a/source4/auth/ntlm/auth_server.c b/source4/auth/ntlm/auth_server.c new file mode 100644 index 0000000000..bb8773e75e --- /dev/null +++ b/source4/auth/ntlm/auth_server.c @@ -0,0 +1,229 @@ +/* + Unix SMB/CIFS implementation. + Authenticate by using a remote server + Copyright (C) Andrew Bartlett 2001-2002, 2008 + Copyright (C) Jelmer Vernooij 2002 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "auth/credentials/credentials.h" +#include "libcli/security/security.h" +#include "librpc/gen_ndr/ndr_samr.h" +#include "libcli/smb_composite/smb_composite.h" +#include "param/param.h" +#include "libcli/resolve/resolve.h" + +/* This version of 'security=server' rewirtten from scratch for Samba4 + * libraries in 2008 */ + + +static NTSTATUS server_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + return NT_STATUS_OK; +} +/** + * The challenge from the target server, when operating in security=server + **/ +static NTSTATUS server_get_challenge(struct auth_method_context *ctx, TALLOC_CTX *mem_ctx, DATA_BLOB *_blob) +{ + struct smb_composite_connect io; + struct smbcli_options smb_options; + const char **host_list; + NTSTATUS status; + + /* Make a connection to the target server, found by 'password server' in smb.conf */ + + lp_smbcli_options(ctx->auth_ctx->lp_ctx, &smb_options); + + /* Make a negprot, WITHOUT SPNEGO, so we get a challenge nice an easy */ + io.in.options.use_spnego = false; + + /* Hope we don't get * (the default), as this won't work... */ + host_list = lp_passwordserver(ctx->auth_ctx->lp_ctx); + if (!host_list) { + return NT_STATUS_INTERNAL_ERROR; + } + io.in.dest_host = host_list[0]; + if (strequal(io.in.dest_host, "*")) { + return NT_STATUS_INTERNAL_ERROR; + } + io.in.dest_ports = lp_smb_ports(ctx->auth_ctx->lp_ctx); + + io.in.called_name = strupper_talloc(mem_ctx, io.in.dest_host); + + /* We don't want to get as far as the session setup */ + io.in.credentials = cli_credentials_init_anon(mem_ctx); + cli_credentials_set_workstation(io.in.credentials, + lp_netbios_name(ctx->auth_ctx->lp_ctx), + CRED_SPECIFIED); + + io.in.service = NULL; + + io.in.workgroup = ""; /* only used with SPNEGO, disabled above */ + + io.in.options = smb_options; + + status = smb_composite_connect(&io, mem_ctx, lp_resolve_context(ctx->auth_ctx->lp_ctx), + ctx->auth_ctx->event_ctx); + NT_STATUS_NOT_OK_RETURN(status); + + *_blob = io.out.tree->session->transport->negotiate.secblob; + ctx->private_data = talloc_steal(ctx, io.out.tree->session); + return NT_STATUS_OK; +} + +/** + * Return an error based on username + * + * This function allows the testing of obsure errors, as well as the generation + * of NT_STATUS -> DOS error mapping tables. + * + * This module is of no value to end-users. + * + * The password is ignored. + * + * @return An NTSTATUS value based on the username + **/ + +static NTSTATUS server_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **_server_info) +{ + NTSTATUS nt_status; + struct auth_serversupplied_info *server_info; + struct cli_credentials *creds; + const char *user; + struct smb_composite_sesssetup session_setup; + + struct smbcli_session *session = talloc_get_type(ctx->private_data, struct smbcli_session); + + creds = cli_credentials_init(mem_ctx); + + NT_STATUS_HAVE_NO_MEMORY(creds); + + cli_credentials_set_username(creds, user_info->client.account_name, CRED_SPECIFIED); + cli_credentials_set_domain(creds, user_info->client.domain_name, CRED_SPECIFIED); + + switch (user_info->password_state) { + case AUTH_PASSWORD_PLAIN: + cli_credentials_set_password(creds, user_info->password.plaintext, + CRED_SPECIFIED); + break; + case AUTH_PASSWORD_HASH: + cli_credentials_set_nt_hash(creds, user_info->password.hash.nt, + CRED_SPECIFIED); + break; + + case AUTH_PASSWORD_RESPONSE: + cli_credentials_set_ntlm_response(creds, &user_info->password.response.lanman, &user_info->password.response.nt, CRED_SPECIFIED); + break; + } + + session_setup.in.sesskey = session->transport->negotiate.sesskey; + session_setup.in.capabilities = session->transport->negotiate.capabilities; + + session_setup.in.credentials = creds; + session_setup.in.workgroup = ""; /* Only used with SPNEGO, which we are not doing */ + + /* Check password with remove server - this should be async some day */ + nt_status = smb_composite_sesssetup(session, &session_setup); + + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + server_info = talloc(mem_ctx, struct auth_serversupplied_info); + NT_STATUS_HAVE_NO_MEMORY(server_info); + + server_info->account_sid = dom_sid_parse_talloc(server_info, SID_NT_ANONYMOUS); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_sid); + + /* is this correct? */ + server_info->primary_group_sid = dom_sid_parse_talloc(server_info, SID_BUILTIN_GUESTS); + NT_STATUS_HAVE_NO_MEMORY(server_info->primary_group_sid); + + server_info->n_domain_groups = 0; + server_info->domain_groups = NULL; + + /* annoying, but the Anonymous really does have a session key, + and it is all zeros! */ + server_info->user_session_key = data_blob(NULL, 0); + server_info->lm_session_key = data_blob(NULL, 0); + + server_info->account_name = talloc_strdup(server_info, user_info->client.account_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_name); + + server_info->domain_name = talloc_strdup(server_info, user_info->client.domain_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_name); + + server_info->full_name = NULL; + + server_info->logon_script = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_script); + + server_info->profile_path = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->profile_path); + + server_info->home_directory = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_directory); + + server_info->home_drive = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_drive); + + server_info->last_logon = 0; + server_info->last_logoff = 0; + server_info->acct_expiry = 0; + server_info->last_password_change = 0; + server_info->allow_password_change = 0; + server_info->force_password_change = 0; + + server_info->logon_count = 0; + server_info->bad_password_count = 0; + + server_info->acct_flags = ACB_NORMAL; + + server_info->authenticated = false; + + *_server_info = server_info; + + return nt_status; +} + +static const struct auth_operations server_auth_ops = { + .name = "server", + .get_challenge = server_get_challenge, + .want_check = server_want_check, + .check_password = server_check_password +}; + +_PUBLIC_ NTSTATUS auth_server_init(void) +{ + NTSTATUS ret; + + ret = auth_register(&server_auth_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'server' auth backend!\n")); + return ret; + } + + return ret; +} diff --git a/source4/auth/ntlm/auth_simple.c b/source4/auth/ntlm/auth_simple.c new file mode 100644 index 0000000000..e7039c3657 --- /dev/null +++ b/source4/auth/ntlm/auth_simple.c @@ -0,0 +1,103 @@ +/* + Unix SMB/CIFS implementation. + + auth functions + + Copyright (C) Simo Sorce 2005 + Copyright (C) Andrew Tridgell 2005 + Copyright (C) Andrew Bartlett 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "lib/events/events.h" +#include "param/param.h" +#include "auth/session_proto.h" + +/* + It's allowed to pass NULL as session_info, + when the caller doesn't need a session_info +*/ +_PUBLIC_ NTSTATUS authenticate_username_pw(TALLOC_CTX *mem_ctx, + struct event_context *ev, + struct messaging_context *msg, + struct loadparm_context *lp_ctx, + const char *nt4_domain, + const char *nt4_username, + const char *password, + struct auth_session_info **session_info) +{ + struct auth_context *auth_context; + struct auth_usersupplied_info *user_info; + struct auth_serversupplied_info *server_info; + NTSTATUS nt_status; + TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); + + if (!tmp_ctx) { + return NT_STATUS_NO_MEMORY; + } + + nt_status = auth_context_create(tmp_ctx, + ev, msg, + lp_ctx, + &auth_context); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(tmp_ctx); + return nt_status; + } + + user_info = talloc(tmp_ctx, struct auth_usersupplied_info); + if (!user_info) { + talloc_free(tmp_ctx); + return NT_STATUS_NO_MEMORY; + } + + user_info->mapped_state = true; + user_info->client.account_name = nt4_username; + user_info->mapped.account_name = nt4_username; + user_info->client.domain_name = nt4_domain; + user_info->mapped.domain_name = nt4_domain; + + user_info->workstation_name = NULL; + + user_info->remote_host = NULL; + + user_info->password_state = AUTH_PASSWORD_PLAIN; + user_info->password.plaintext = talloc_strdup(user_info, password); + + user_info->flags = USER_INFO_CASE_INSENSITIVE_USERNAME | + USER_INFO_DONT_CHECK_UNIX_ACCOUNT; + + user_info->logon_parameters = 0; + + nt_status = auth_check_password(auth_context, tmp_ctx, user_info, &server_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(tmp_ctx); + return nt_status; + } + + if (session_info) { + nt_status = auth_generate_session_info(tmp_ctx, ev, lp_ctx, server_info, session_info); + + if (NT_STATUS_IS_OK(nt_status)) { + talloc_steal(mem_ctx, *session_info); + } + } + + talloc_free(tmp_ctx); + return nt_status; +} + diff --git a/source4/auth/ntlm/auth_unix.c b/source4/auth/ntlm/auth_unix.c new file mode 100644 index 0000000000..1717b9d0e1 --- /dev/null +++ b/source4/auth/ntlm/auth_unix.c @@ -0,0 +1,844 @@ +/* + Unix SMB/CIFS implementation. + Password and authentication handling + Copyright (C) Andrew Bartlett 2001 + Copyright (C) Jeremy Allison 2001 + Copyright (C) Simo Sorce 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "system/passwd.h" /* needed by some systems for struct passwd */ +#include "lib/socket/socket.h" +#include "auth/ntlm/pam_errors.h" +#include "param/param.h" + +/* TODO: look at how to best fill in parms retrieveing a struct passwd info + * except in case USER_INFO_DONT_CHECK_UNIX_ACCOUNT is set + */ +static NTSTATUS authunix_make_server_info(TALLOC_CTX *mem_ctx, + const char *netbios_name, + const struct auth_usersupplied_info *user_info, + struct passwd *pwd, + struct auth_serversupplied_info **_server_info) +{ + struct auth_serversupplied_info *server_info; + NTSTATUS status; + + /* This is a real, real hack */ + if (pwd->pw_uid == 0) { + status = auth_system_server_info(mem_ctx, netbios_name, &server_info); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + + server_info->account_name = talloc_steal(server_info, pwd->pw_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_name); + + server_info->domain_name = talloc_strdup(server_info, "unix"); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_name); + } else { + server_info = talloc(mem_ctx, struct auth_serversupplied_info); + NT_STATUS_HAVE_NO_MEMORY(server_info); + + server_info->authenticated = true; + + server_info->account_name = talloc_steal(server_info, pwd->pw_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_name); + + server_info->domain_name = talloc_strdup(server_info, "unix"); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_name); + + /* This isn't in any way correct.. */ + server_info->account_sid = NULL; + server_info->primary_group_sid = NULL; + server_info->n_domain_groups = 0; + server_info->domain_groups = NULL; + } + server_info->user_session_key = data_blob(NULL,0); + server_info->lm_session_key = data_blob(NULL,0); + + server_info->full_name = talloc_steal(server_info, pwd->pw_gecos); + NT_STATUS_HAVE_NO_MEMORY(server_info->full_name); + server_info->logon_script = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_script); + server_info->profile_path = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->profile_path); + server_info->home_directory = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_directory); + server_info->home_drive = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_drive); + + server_info->last_logon = 0; + server_info->last_logoff = 0; + server_info->acct_expiry = 0; + server_info->last_password_change = 0; + server_info->allow_password_change = 0; + server_info->force_password_change = 0; + server_info->logon_count = 0; + server_info->bad_password_count = 0; + server_info->acct_flags = 0; + + *_server_info = server_info; + + return NT_STATUS_OK; +} + +static NTSTATUS talloc_getpwnam(TALLOC_CTX *ctx, const char *username, struct passwd **pws) +{ + struct passwd *ret; + struct passwd *from; + + *pws = NULL; + + ret = talloc(ctx, struct passwd); + NT_STATUS_HAVE_NO_MEMORY(ret); + + from = getpwnam(username); + if (!from) { + return NT_STATUS_NO_SUCH_USER; + } + + ret->pw_name = talloc_strdup(ctx, from->pw_name); + NT_STATUS_HAVE_NO_MEMORY(ret->pw_name); + + ret->pw_passwd = talloc_strdup(ctx, from->pw_passwd); + NT_STATUS_HAVE_NO_MEMORY(ret->pw_passwd); + + ret->pw_uid = from->pw_uid; + ret->pw_gid = from->pw_gid; + ret->pw_gecos = talloc_strdup(ctx, from->pw_gecos); + NT_STATUS_HAVE_NO_MEMORY(ret->pw_gecos); + + ret->pw_dir = talloc_strdup(ctx, from->pw_dir); + NT_STATUS_HAVE_NO_MEMORY(ret->pw_dir); + + ret->pw_shell = talloc_strdup(ctx, from->pw_shell); + NT_STATUS_HAVE_NO_MEMORY(ret->pw_shell); + + *pws = ret; + + return NT_STATUS_OK; +} + + +#ifdef HAVE_SECURITY_PAM_APPL_H +#include <security/pam_appl.h> + +struct smb_pam_user_info { + const char *account_name; + const char *plaintext_password; +}; + +#define COPY_STRING(s) (s) ? strdup(s) : NULL + +/* + * Check user password + * Currently it uses PAM only and fails on systems without PAM + * Samba3 code located in pass_check.c is to ugly to be used directly it will + * need major rework that's why pass_check.c is still there. +*/ + +static int smb_pam_conv(int num_msg, const struct pam_message **msg, + struct pam_response **reply, void *appdata_ptr) +{ + struct smb_pam_user_info *info = (struct smb_pam_user_info *)appdata_ptr; + int num; + + if (num_msg <= 0) { + *reply = NULL; + return PAM_CONV_ERR; + } + + /* + * Apparantly HPUX has a buggy PAM that doesn't support the + * data pointer. Fail if this is the case. JRA. + */ + + if (info == NULL) { + *reply = NULL; + return PAM_CONV_ERR; + } + + /* + * PAM frees memory in reply messages by itself + * so use malloc instead of talloc here. + */ + *reply = malloc_array_p(struct pam_response, num_msg); + if (*reply == NULL) { + return PAM_CONV_ERR; + } + + for (num = 0; num < num_msg; num++) { + switch (msg[num]->msg_style) { + case PAM_PROMPT_ECHO_ON: + (*reply)[num].resp_retcode = PAM_SUCCESS; + (*reply)[num].resp = COPY_STRING(info->account_name); + break; + + case PAM_PROMPT_ECHO_OFF: + (*reply)[num].resp_retcode = PAM_SUCCESS; + (*reply)[num].resp = COPY_STRING(info->plaintext_password); + break; + + case PAM_TEXT_INFO: + (*reply)[num].resp_retcode = PAM_SUCCESS; + (*reply)[num].resp = NULL; + DEBUG(4,("PAM Info message in conversation function: %s\n", (msg[num]->msg))); + break; + + case PAM_ERROR_MSG: + (*reply)[num].resp_retcode = PAM_SUCCESS; + (*reply)[num].resp = NULL; + DEBUG(4,("PAM Error message in conversation function: %s\n", (msg[num]->msg))); + break; + + default: + while (num > 0) { + SAFE_FREE((*reply)[num-1].resp); + num--; + } + SAFE_FREE(*reply); + *reply = NULL; + DEBUG(1,("Error: PAM subsystme sent an UNKNOWN message type to the conversation function!\n")); + return PAM_CONV_ERR; + } + } + + return PAM_SUCCESS; +} + +/* + * Start PAM authentication for specified account + */ + +static NTSTATUS smb_pam_start(pam_handle_t **pamh, const char *account_name, const char *remote_host, struct pam_conv *pconv) +{ + int pam_error; + + if (account_name == NULL || remote_host == NULL) { + return NT_STATUS_INVALID_PARAMETER; + } + + DEBUG(4,("smb_pam_start: PAM: Init user: %s\n", account_name)); + + pam_error = pam_start("samba", account_name, pconv, pamh); + if (pam_error != PAM_SUCCESS) { + /* no valid pamh here, can we reliably call pam_strerror ? */ + DEBUG(4,("smb_pam_start: pam_start failed!\n")); + return NT_STATUS_UNSUCCESSFUL; + } + +#ifdef PAM_RHOST + DEBUG(4,("smb_pam_start: PAM: setting rhost to: %s\n", remote_host)); + pam_error = pam_set_item(*pamh, PAM_RHOST, remote_host); + if (pam_error != PAM_SUCCESS) { + NTSTATUS nt_status; + + DEBUG(4,("smb_pam_start: setting rhost failed with error: %s\n", + pam_strerror(*pamh, pam_error))); + nt_status = pam_to_nt_status(pam_error); + + pam_error = pam_end(*pamh, 0); + if (pam_error != PAM_SUCCESS) { + /* no vaild pamh here, can we reliably call pam_strerror ? */ + DEBUG(4,("smb_pam_start: clean up failed, pam_end gave error %d.\n", + pam_error)); + return pam_to_nt_status(pam_error); + } + return nt_status; + } +#endif +#ifdef PAM_TTY + DEBUG(4,("smb_pam_start: PAM: setting tty\n")); + pam_error = pam_set_item(*pamh, PAM_TTY, "samba"); + if (pam_error != PAM_SUCCESS) { + NTSTATUS nt_status; + + DEBUG(4,("smb_pam_start: setting tty failed with error: %s\n", + pam_strerror(*pamh, pam_error))); + nt_status = pam_to_nt_status(pam_error); + + pam_error = pam_end(*pamh, 0); + if (pam_error != PAM_SUCCESS) { + /* no vaild pamh here, can we reliably call pam_strerror ? */ + DEBUG(4,("smb_pam_start: clean up failed, pam_end gave error %d.\n", + pam_error)); + return pam_to_nt_status(pam_error); + } + return nt_status; + } +#endif + DEBUG(4,("smb_pam_start: PAM: Init passed for user: %s\n", account_name)); + + return NT_STATUS_OK; +} + +static NTSTATUS smb_pam_end(pam_handle_t *pamh) +{ + int pam_error; + + if (pamh != NULL) { + pam_error = pam_end(pamh, 0); + if (pam_error != PAM_SUCCESS) { + /* no vaild pamh here, can we reliably call pam_strerror ? */ + DEBUG(4,("smb_pam_end: clean up failed, pam_end gave error %d.\n", + pam_error)); + return pam_to_nt_status(pam_error); + } + return NT_STATUS_OK; + } + + DEBUG(2,("smb_pam_end: pamh is NULL, PAM not initialized ?\n")); + return NT_STATUS_UNSUCCESSFUL; +} + +/* + * PAM Authentication Handler + */ +static NTSTATUS smb_pam_auth(pam_handle_t *pamh, bool allow_null_passwords, const char *user) +{ + int pam_error; + + /* + * To enable debugging set in /etc/pam.d/samba: + * auth required /lib/security/pam_pwdb.so nullok shadow audit + */ + + DEBUG(4,("smb_pam_auth: PAM: Authenticate User: %s\n", user)); + + pam_error = pam_authenticate(pamh, PAM_SILENT | allow_null_passwords ? 0 : PAM_DISALLOW_NULL_AUTHTOK); + switch( pam_error ){ + case PAM_AUTH_ERR: + DEBUG(2, ("smb_pam_auth: PAM: Authentication Error for user %s\n", user)); + break; + case PAM_CRED_INSUFFICIENT: + DEBUG(2, ("smb_pam_auth: PAM: Insufficient Credentials for user %s\n", user)); + break; + case PAM_AUTHINFO_UNAVAIL: + DEBUG(2, ("smb_pam_auth: PAM: Authentication Information Unavailable for user %s\n", user)); + break; + case PAM_USER_UNKNOWN: + DEBUG(2, ("smb_pam_auth: PAM: Username %s NOT known to Authentication system\n", user)); + break; + case PAM_MAXTRIES: + DEBUG(2, ("smb_pam_auth: PAM: One or more authentication modules reports user limit for user %s exceeeded\n", user)); + break; + case PAM_ABORT: + DEBUG(0, ("smb_pam_auth: PAM: One or more PAM modules failed to load for user %s\n", user)); + break; + case PAM_SUCCESS: + DEBUG(4, ("smb_pam_auth: PAM: User %s Authenticated OK\n", user)); + break; + default: + DEBUG(0, ("smb_pam_auth: PAM: UNKNOWN ERROR while authenticating user %s\n", user)); + break; + } + + return pam_to_nt_status(pam_error); +} + +/* + * PAM Account Handler + */ +static NTSTATUS smb_pam_account(pam_handle_t *pamh, const char * user) +{ + int pam_error; + + DEBUG(4,("smb_pam_account: PAM: Account Management for User: %s\n", user)); + + pam_error = pam_acct_mgmt(pamh, PAM_SILENT); /* Is user account enabled? */ + switch( pam_error ) { + case PAM_AUTHTOK_EXPIRED: + DEBUG(2, ("smb_pam_account: PAM: User %s is valid but password is expired\n", user)); + break; + case PAM_ACCT_EXPIRED: + DEBUG(2, ("smb_pam_account: PAM: User %s no longer permitted to access system\n", user)); + break; + case PAM_AUTH_ERR: + DEBUG(2, ("smb_pam_account: PAM: There was an authentication error for user %s\n", user)); + break; + case PAM_PERM_DENIED: + DEBUG(0, ("smb_pam_account: PAM: User %s is NOT permitted to access system at this time\n", user)); + break; + case PAM_USER_UNKNOWN: + DEBUG(0, ("smb_pam_account: PAM: User \"%s\" is NOT known to account management\n", user)); + break; + case PAM_SUCCESS: + DEBUG(4, ("smb_pam_account: PAM: Account OK for User: %s\n", user)); + break; + default: + DEBUG(0, ("smb_pam_account: PAM: UNKNOWN PAM ERROR (%d) during Account Management for User: %s\n", pam_error, user)); + break; + } + + return pam_to_nt_status(pam_error); +} + +/* + * PAM Credential Setting + */ + +static NTSTATUS smb_pam_setcred(pam_handle_t *pamh, const char * user) +{ + int pam_error; + + /* + * This will allow samba to aquire a kerberos token. And, when + * exporting an AFS cell, be able to /write/ to this cell. + */ + + DEBUG(4,("PAM: Account Management SetCredentials for User: %s\n", user)); + + pam_error = pam_setcred(pamh, (PAM_ESTABLISH_CRED|PAM_SILENT)); + switch( pam_error ) { + case PAM_CRED_UNAVAIL: + DEBUG(0, ("smb_pam_setcred: PAM: Credentials not found for user:%s\n", user )); + break; + case PAM_CRED_EXPIRED: + DEBUG(0, ("smb_pam_setcred: PAM: Credentials for user: \"%s\" EXPIRED!\n", user )); + break; + case PAM_USER_UNKNOWN: + DEBUG(0, ("smb_pam_setcred: PAM: User: \"%s\" is NOT known so can not set credentials!\n", user )); + break; + case PAM_CRED_ERR: + DEBUG(0, ("smb_pam_setcred: PAM: Unknown setcredentials error - unable to set credentials for %s\n", user )); + break; + case PAM_SUCCESS: + DEBUG(4, ("smb_pam_setcred: PAM: SetCredentials OK for User: %s\n", user)); + break; + default: + DEBUG(0, ("smb_pam_setcred: PAM: UNKNOWN PAM ERROR (%d) during SetCredentials for User: %s\n", pam_error, user)); + break; + } + + return pam_to_nt_status(pam_error); +} + +static NTSTATUS check_unix_password(TALLOC_CTX *ctx, struct loadparm_context *lp_ctx, + const struct auth_usersupplied_info *user_info, struct passwd **pws) +{ + struct smb_pam_user_info *info; + struct pam_conv *pamconv; + pam_handle_t *pamh; + NTSTATUS nt_status; + + info = talloc(ctx, struct smb_pam_user_info); + if (info == NULL) { + return NT_STATUS_NO_MEMORY; + } + + info->account_name = user_info->mapped.account_name; + info->plaintext_password = user_info->password.plaintext; + + pamconv = talloc(ctx, struct pam_conv); + if (pamconv == NULL) { + return NT_STATUS_NO_MEMORY; + } + + pamconv->conv = smb_pam_conv; + pamconv->appdata_ptr = (void *)info; + + /* TODO: + * check for user_info->flags & USER_INFO_CASE_INSENSITIVE_USERNAME + * if true set up a crack name routine. + */ + + nt_status = smb_pam_start(&pamh, user_info->mapped.account_name, user_info->remote_host ? user_info->remote_host->addr : NULL, pamconv); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + nt_status = smb_pam_auth(pamh, lp_null_passwords(lp_ctx), user_info->mapped.account_name); + if (!NT_STATUS_IS_OK(nt_status)) { + smb_pam_end(pamh); + return nt_status; + } + + if ( ! (user_info->flags & USER_INFO_DONT_CHECK_UNIX_ACCOUNT)) { + + nt_status = smb_pam_account(pamh, user_info->mapped.account_name); + if (!NT_STATUS_IS_OK(nt_status)) { + smb_pam_end(pamh); + return nt_status; + } + + nt_status = smb_pam_setcred(pamh, user_info->mapped.account_name); + if (!NT_STATUS_IS_OK(nt_status)) { + smb_pam_end(pamh); + return nt_status; + } + } + + smb_pam_end(pamh); + + nt_status = talloc_getpwnam(ctx, user_info->mapped.account_name, pws); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + return NT_STATUS_OK; +} + +#else + +/**************************************************************************** +core of password checking routine +****************************************************************************/ +static NTSTATUS password_check(const char *username, const char *password, + const char *crypted, const char *salt) +{ + bool ret; + +#ifdef WITH_AFS + if (afs_auth(username, password)) + return NT_STATUS_OK; +#endif /* WITH_AFS */ + +#ifdef WITH_DFS + if (dfs_auth(username, password)) + return NT_STATUS_OK; +#endif /* WITH_DFS */ + +#ifdef OSF1_ENH_SEC + + ret = (strcmp(osf1_bigcrypt(password, salt), crypted) == 0); + + if (!ret) { + DEBUG(2, + ("OSF1_ENH_SEC failed. Trying normal crypt.\n")); + ret = (strcmp((char *)crypt(password, salt), crypted) == 0); + } + if (ret) { + return NT_STATUS_OK; + } else { + return NT_STATUS_WRONG_PASSWORD; + } + +#endif /* OSF1_ENH_SEC */ + +#ifdef ULTRIX_AUTH + ret = (strcmp((char *)crypt16(password, salt), crypted) == 0); + if (ret) { + return NT_STATUS_OK; + } else { + return NT_STATUS_WRONG_PASSWORD; + } + +#endif /* ULTRIX_AUTH */ + +#ifdef LINUX_BIGCRYPT + ret = (linux_bigcrypt(password, salt, crypted)); + if (ret) { + return NT_STATUS_OK; + } else { + return NT_STATUS_WRONG_PASSWORD; + } +#endif /* LINUX_BIGCRYPT */ + +#if defined(HAVE_BIGCRYPT) && defined(HAVE_CRYPT) && defined(USE_BOTH_CRYPT_CALLS) + + /* + * Some systems have bigcrypt in the C library but might not + * actually use it for the password hashes (HPUX 10.20) is + * a noteable example. So we try bigcrypt first, followed + * by crypt. + */ + + if (strcmp(bigcrypt(password, salt), crypted) == 0) + return NT_STATUS_OK; + else + ret = (strcmp((char *)crypt(password, salt), crypted) == 0); + if (ret) { + return NT_STATUS_OK; + } else { + return NT_STATUS_WRONG_PASSWORD; + } +#else /* HAVE_BIGCRYPT && HAVE_CRYPT && USE_BOTH_CRYPT_CALLS */ + +#ifdef HAVE_BIGCRYPT + ret = (strcmp(bigcrypt(password, salt), crypted) == 0); + if (ret) { + return NT_STATUS_OK; + } else { + return NT_STATUS_WRONG_PASSWORD; + } +#endif /* HAVE_BIGCRYPT */ + +#ifndef HAVE_CRYPT + DEBUG(1, ("Warning - no crypt available\n")); + return NT_STATUS_LOGON_FAILURE; +#else /* HAVE_CRYPT */ + ret = (strcmp((char *)crypt(password, salt), crypted) == 0); + if (ret) { + return NT_STATUS_OK; + } else { + return NT_STATUS_WRONG_PASSWORD; + } +#endif /* HAVE_CRYPT */ +#endif /* HAVE_BIGCRYPT && HAVE_CRYPT && USE_BOTH_CRYPT_CALLS */ +} + +static NTSTATUS check_unix_password(TALLOC_CTX *ctx, struct loadparm_context *lp_ctx, + const struct auth_usersupplied_info *user_info, struct passwd **ret_passwd) +{ + char *username; + char *password; + char *pwcopy; + char *salt; + char *crypted; + struct passwd *pws; + NTSTATUS nt_status; + int level = lp_passwordlevel(lp_ctx); + + *ret_passwd = NULL; + + username = talloc_strdup(ctx, user_info->mapped.account_name); + password = talloc_strdup(ctx, user_info->password.plaintext); + + nt_status = talloc_getpwnam(ctx, username, &pws); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + crypted = pws->pw_passwd; + salt = pws->pw_passwd; + +#ifdef HAVE_GETSPNAM + { + struct spwd *spass; + + /* many shadow systems require you to be root to get + the password, in most cases this should already be + the case when this function is called, except + perhaps for IPC password changing requests */ + + spass = getspnam(pws->pw_name); + if (spass && spass->sp_pwdp) { + crypted = talloc_strdup(ctx, spass->sp_pwdp); + NT_STATUS_HAVE_NO_MEMORY(crypted); + salt = talloc_strdup(ctx, spass->sp_pwdp); + NT_STATUS_HAVE_NO_MEMORY(salt); + } + } +#elif defined(IA_UINFO) + { + char *ia_password; + /* Need to get password with SVR4.2's ia_ functions + instead of get{sp,pw}ent functions. Required by + UnixWare 2.x, tested on version + 2.1. (tangent@cyberport.com) */ + uinfo_t uinfo; + if (ia_openinfo(pws->pw_name, &uinfo) != -1) { + ia_get_logpwd(uinfo, &ia_password); + crypted = talloc_strdup(ctx, ia_password); + NT_STATUS_HAVE_NO_MEMORY(crypted); + } + } +#endif + +#ifdef HAVE_GETPRPWNAM + { + struct pr_passwd *pr_pw = getprpwnam(pws->pw_name); + if (pr_pw && pr_pw->ufld.fd_encrypt) { + crypted = talloc_strdup(ctx, pr_pw->ufld.fd_encrypt); + NT_STATUS_HAVE_NO_MEMORY(crypted); + } + } +#endif + +#ifdef HAVE_GETPWANAM + { + struct passwd_adjunct *pwret; + pwret = getpwanam(s); + if (pwret && pwret->pwa_passwd) { + crypted = talloc_strdup(ctx, pwret->pwa_passwd); + NT_STATUS_HAVE_NO_MEMORY(crypted); + } + } +#endif + +#ifdef OSF1_ENH_SEC + { + struct pr_passwd *mypasswd; + DEBUG(5,("Checking password for user %s in OSF1_ENH_SEC\n", username)); + mypasswd = getprpwnam(username); + if (mypasswd) { + username = talloc_strdup(ctx, mypasswd->ufld.fd_name); + NT_STATUS_HAVE_NO_MEMORY(username); + crypted = talloc_strdup(ctx, mypasswd->ufld.fd_encrypt); + NT_STATUS_HAVE_NO_MEMORY(crypted); + } else { + DEBUG(5,("OSF1_ENH_SEC: No entry for user %s in protected database !\n", username)); + } + } +#endif + +#ifdef ULTRIX_AUTH + { + AUTHORIZATION *ap = getauthuid(pws->pw_uid); + if (ap) { + crypted = talloc_strdup(ctx, ap->a_password); + endauthent(); + NT_STATUS_HAVE_NO_MEMORY(crypted); + } + } +#endif + +#if defined(HAVE_TRUNCATED_SALT) + /* crypt on some platforms (HPUX in particular) + won't work with more than 2 salt characters. */ + salt[2] = 0; +#endif + + if (crypted[0] == '\0') { + if (!lp_null_passwords(lp_ctx)) { + DEBUG(2, ("Disallowing %s with null password\n", username)); + return NT_STATUS_LOGON_FAILURE; + } + if (password == NULL) { + DEBUG(3, ("Allowing access to %s with null password\n", username)); + *ret_passwd = pws; + return NT_STATUS_OK; + } + } + + /* try it as it came to us */ + nt_status = password_check(username, password, crypted, salt); + if (NT_STATUS_IS_OK(nt_status)) { + *ret_passwd = pws; + return nt_status; + } + else if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD)) { + /* No point continuing if its not the password thats to blame (ie PAM disabled). */ + return nt_status; + } + + if ( user_info->flags | USER_INFO_CASE_INSENSITIVE_PASSWORD) { + return nt_status; + } + + /* if the password was given to us with mixed case then we don't + * need to proceed as we know it hasn't been case modified by the + * client */ + if (strhasupper(password) && strhaslower(password)) { + return nt_status; + } + + /* make a copy of it */ + pwcopy = talloc_strdup(ctx, password); + if (!pwcopy) + return NT_STATUS_NO_MEMORY; + + /* try all lowercase if it's currently all uppercase */ + if (strhasupper(pwcopy)) { + strlower(pwcopy); + nt_status = password_check(username, pwcopy, crypted, salt); + if NT_STATUS_IS_OK(nt_status) { + *ret_passwd = pws; + return nt_status; + } + } + + /* give up? */ + if (level < 1) { + return NT_STATUS_WRONG_PASSWORD; + } + + /* last chance - all combinations of up to level chars upper! */ + strlower(pwcopy); + +#if 0 + if (NT_STATUS_IS_OK(nt_status = string_combinations(pwcopy, password_check, level))) { + *ret_passwd = pws; + return nt_status; + } +#endif + return NT_STATUS_WRONG_PASSWORD; +} + +#endif + +/** Check a plaintext username/password + * + **/ + +static NTSTATUS authunix_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + if (!user_info->mapped.account_name || !*user_info->mapped.account_name) { + return NT_STATUS_NOT_IMPLEMENTED; + } + + return NT_STATUS_OK; +} + +static NTSTATUS authunix_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info) +{ + TALLOC_CTX *check_ctx; + NTSTATUS nt_status; + struct passwd *pwd; + + if (user_info->password_state != AUTH_PASSWORD_PLAIN) { + return NT_STATUS_INVALID_PARAMETER; + } + + check_ctx = talloc_named_const(mem_ctx, 0, "check_unix_password"); + if (check_ctx == NULL) { + return NT_STATUS_NO_MEMORY; + } + + nt_status = check_unix_password(check_ctx, ctx->auth_ctx->lp_ctx, user_info, &pwd); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(check_ctx); + return nt_status; + } + + nt_status = authunix_make_server_info(mem_ctx, lp_netbios_name(ctx->auth_ctx->lp_ctx), + user_info, pwd, server_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(check_ctx); + return nt_status; + } + + talloc_free(check_ctx); + return NT_STATUS_OK; +} + +static const struct auth_operations unix_ops = { + .name = "unix", + .get_challenge = auth_get_challenge_not_implemented, + .want_check = authunix_want_check, + .check_password = authunix_check_password +}; + +_PUBLIC_ NTSTATUS auth_unix_init(void) +{ + NTSTATUS ret; + + ret = auth_register(&unix_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register unix auth backend!\n")); + return ret; + } + + return ret; +} diff --git a/source4/auth/ntlm/auth_util.c b/source4/auth/ntlm/auth_util.c new file mode 100644 index 0000000000..1d86b858cf --- /dev/null +++ b/source4/auth/ntlm/auth_util.c @@ -0,0 +1,260 @@ +/* + Unix SMB/CIFS implementation. + Authentication utility functions + Copyright (C) Andrew Tridgell 1992-1998 + Copyright (C) Andrew Bartlett 2001 + Copyright (C) Jeremy Allison 2000-2001 + Copyright (C) Rafal Szczesniak 2002 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "libcli/security/security.h" +#include "libcli/auth/libcli_auth.h" +#include "dsdb/samdb/samdb.h" +#include "auth/credentials/credentials.h" +#include "param/param.h" + +/* this default function can be used by mostly all backends + * which don't want to set a challenge + */ +NTSTATUS auth_get_challenge_not_implemented(struct auth_method_context *ctx, TALLOC_CTX *mem_ctx, DATA_BLOB *challenge) +{ + /* we don't want to set a challenge */ + return NT_STATUS_NOT_IMPLEMENTED; +} + +/**************************************************************************** + Create an auth_usersupplied_data structure after appropriate mapping. +****************************************************************************/ + +NTSTATUS map_user_info(TALLOC_CTX *mem_ctx, + const char *default_domain, + const struct auth_usersupplied_info *user_info, + struct auth_usersupplied_info **user_info_mapped) +{ + const char *domain; + char *account_name; + char *d; + DEBUG(5,("map_user_info: Mapping user [%s]\\[%s] from workstation [%s]\n", + user_info->client.domain_name, user_info->client.account_name, user_info->workstation_name)); + + account_name = talloc_strdup(mem_ctx, user_info->client.account_name); + if (!account_name) { + return NT_STATUS_NO_MEMORY; + } + + /* don't allow "" as a domain, fixes a Win9X bug + where it doesn't supply a domain for logon script + 'net use' commands. */ + + /* Split user@realm names into user and realm components. This is TODO to fix with proper userprincipalname support */ + if (user_info->client.domain_name && *user_info->client.domain_name) { + domain = user_info->client.domain_name; + } else if (strchr_m(user_info->client.account_name, '@')) { + d = strchr_m(account_name, '@'); + if (!d) { + return NT_STATUS_INTERNAL_ERROR; + } + d[0] = '\0'; + d++; + domain = d; + } else { + domain = default_domain; + } + + *user_info_mapped = talloc(mem_ctx, struct auth_usersupplied_info); + if (!*user_info_mapped) { + return NT_STATUS_NO_MEMORY; + } + if (!talloc_reference(*user_info_mapped, user_info)) { + return NT_STATUS_NO_MEMORY; + } + **user_info_mapped = *user_info; + (*user_info_mapped)->mapped_state = true; + (*user_info_mapped)->mapped.domain_name = talloc_strdup(*user_info_mapped, domain); + (*user_info_mapped)->mapped.account_name = talloc_strdup(*user_info_mapped, account_name); + talloc_free(account_name); + if (!(*user_info_mapped)->mapped.domain_name + || !(*user_info_mapped)->mapped.account_name) { + return NT_STATUS_NO_MEMORY; + } + + return NT_STATUS_OK; +} + +/**************************************************************************** + Create an auth_usersupplied_data structure after appropriate mapping. +****************************************************************************/ + +NTSTATUS encrypt_user_info(TALLOC_CTX *mem_ctx, struct auth_context *auth_context, + enum auth_password_state to_state, + const struct auth_usersupplied_info *user_info_in, + const struct auth_usersupplied_info **user_info_encrypted) +{ + NTSTATUS nt_status; + struct auth_usersupplied_info *user_info_temp; + switch (to_state) { + case AUTH_PASSWORD_RESPONSE: + switch (user_info_in->password_state) { + case AUTH_PASSWORD_PLAIN: + { + const struct auth_usersupplied_info *user_info_temp2; + nt_status = encrypt_user_info(mem_ctx, auth_context, + AUTH_PASSWORD_HASH, + user_info_in, &user_info_temp2); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + user_info_in = user_info_temp2; + /* fall through */ + } + case AUTH_PASSWORD_HASH: + { + const uint8_t *challenge; + DATA_BLOB chall_blob; + user_info_temp = talloc(mem_ctx, struct auth_usersupplied_info); + if (!user_info_temp) { + return NT_STATUS_NO_MEMORY; + } + if (!talloc_reference(user_info_temp, user_info_in)) { + return NT_STATUS_NO_MEMORY; + } + *user_info_temp = *user_info_in; + user_info_temp->mapped_state = to_state; + + nt_status = auth_get_challenge(auth_context, &challenge); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + chall_blob = data_blob_talloc(mem_ctx, challenge, 8); + if (lp_client_ntlmv2_auth(auth_context->lp_ctx)) { + DATA_BLOB names_blob = NTLMv2_generate_names_blob(mem_ctx, lp_iconv_convenience(auth_context->lp_ctx), lp_netbios_name(auth_context->lp_ctx), lp_workgroup(auth_context->lp_ctx)); + DATA_BLOB lmv2_response, ntlmv2_response, lmv2_session_key, ntlmv2_session_key; + + if (!SMBNTLMv2encrypt_hash(user_info_temp, + user_info_in->client.account_name, + user_info_in->client.domain_name, + user_info_in->password.hash.nt->hash, &chall_blob, + &names_blob, + &lmv2_response, &ntlmv2_response, + &lmv2_session_key, &ntlmv2_session_key)) { + data_blob_free(&names_blob); + return NT_STATUS_NO_MEMORY; + } + data_blob_free(&names_blob); + user_info_temp->password.response.lanman = lmv2_response; + user_info_temp->password.response.nt = ntlmv2_response; + + data_blob_free(&lmv2_session_key); + data_blob_free(&ntlmv2_session_key); + } else { + DATA_BLOB blob = data_blob_talloc(mem_ctx, NULL, 24); + SMBOWFencrypt(user_info_in->password.hash.nt->hash, challenge, blob.data); + + user_info_temp->password.response.nt = blob; + if (lp_client_lanman_auth(auth_context->lp_ctx) && user_info_in->password.hash.lanman) { + DATA_BLOB lm_blob = data_blob_talloc(mem_ctx, NULL, 24); + SMBOWFencrypt(user_info_in->password.hash.lanman->hash, challenge, blob.data); + user_info_temp->password.response.lanman = lm_blob; + } else { + /* if not sending the LM password, send the NT password twice */ + user_info_temp->password.response.lanman = user_info_temp->password.response.nt; + } + } + + user_info_in = user_info_temp; + /* fall through */ + } + case AUTH_PASSWORD_RESPONSE: + *user_info_encrypted = user_info_in; + } + break; + case AUTH_PASSWORD_HASH: + { + switch (user_info_in->password_state) { + case AUTH_PASSWORD_PLAIN: + { + struct samr_Password lanman; + struct samr_Password nt; + + user_info_temp = talloc(mem_ctx, struct auth_usersupplied_info); + if (!user_info_temp) { + return NT_STATUS_NO_MEMORY; + } + if (!talloc_reference(user_info_temp, user_info_in)) { + return NT_STATUS_NO_MEMORY; + } + *user_info_temp = *user_info_in; + user_info_temp->mapped_state = to_state; + + if (E_deshash(user_info_in->password.plaintext, lanman.hash)) { + user_info_temp->password.hash.lanman = talloc(user_info_temp, + struct samr_Password); + *user_info_temp->password.hash.lanman = lanman; + } else { + user_info_temp->password.hash.lanman = NULL; + } + + E_md4hash(user_info_in->password.plaintext, nt.hash); + user_info_temp->password.hash.nt = talloc(user_info_temp, + struct samr_Password); + *user_info_temp->password.hash.nt = nt; + + user_info_in = user_info_temp; + /* fall through */ + } + case AUTH_PASSWORD_HASH: + *user_info_encrypted = user_info_in; + break; + default: + return NT_STATUS_INVALID_PARAMETER; + break; + } + break; + } + default: + return NT_STATUS_INVALID_PARAMETER; + } + + return NT_STATUS_OK; +} + + +/** + * Squash an NT_STATUS in line with security requirements. + * In an attempt to avoid giving the whole game away when users + * are authenticating, NT replaces both NT_STATUS_NO_SUCH_USER and + * NT_STATUS_WRONG_PASSWORD with NT_STATUS_LOGON_FAILURE in certain situations + * (session setups in particular). + * + * @param nt_status NTSTATUS input for squashing. + * @return the 'squashed' nt_status + **/ +_PUBLIC_ NTSTATUS auth_nt_status_squash(NTSTATUS nt_status) +{ + if NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER) { + /* Match WinXP and don't give the game away */ + return NT_STATUS_LOGON_FAILURE; + } else if NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD) { + /* Match WinXP and don't give the game away */ + return NT_STATUS_LOGON_FAILURE; + } + + return nt_status; +} diff --git a/source4/auth/ntlm/auth_winbind.c b/source4/auth/ntlm/auth_winbind.c new file mode 100644 index 0000000000..ac63b242e4 --- /dev/null +++ b/source4/auth/ntlm/auth_winbind.c @@ -0,0 +1,282 @@ +/* + Unix SMB/CIFS implementation. + + Winbind authentication mechnism + + Copyright (C) Tim Potter 2000 + Copyright (C) Andrew Bartlett 2001 - 2002 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "auth/session_proto.h" +#include "nsswitch/winbind_client.h" +#include "librpc/gen_ndr/ndr_netlogon.h" +#include "librpc/gen_ndr/ndr_winbind.h" +#include "lib/messaging/irpc.h" +#include "param/param.h" + +static NTSTATUS get_info3_from_ndr(TALLOC_CTX *mem_ctx, struct smb_iconv_convenience *iconv_convenience, struct winbindd_response *response, struct netr_SamInfo3 *info3) +{ + size_t len = response->length - sizeof(struct winbindd_response); + if (len > 4) { + enum ndr_err_code ndr_err; + DATA_BLOB blob; + blob.length = len - 4; + blob.data = (uint8_t *)(((char *)response->extra_data.data) + 4); + + ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, + iconv_convenience, info3, + (ndr_pull_flags_fn_t)ndr_pull_netr_SamInfo3); + if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { + return ndr_map_error2ntstatus(ndr_err); + } + + return NT_STATUS_OK; + } else { + DEBUG(2, ("get_info3_from_ndr: No info3 struct found!\n")); + return NT_STATUS_UNSUCCESSFUL; + } +} + +static NTSTATUS winbind_want_check(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info) +{ + if (!user_info->mapped.account_name || !*user_info->mapped.account_name) { + return NT_STATUS_NOT_IMPLEMENTED; + } + + /* TODO: maybe limit the user scope to remote users only */ + return NT_STATUS_OK; +} + +/* + Authenticate a user with a challenge/response + using the samba3 winbind protocol +*/ +static NTSTATUS winbind_check_password_samba3(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info) +{ + struct winbindd_request request; + struct winbindd_response response; + NSS_STATUS result; + NTSTATUS nt_status; + struct netr_SamInfo3 info3; + + /* Send off request */ + const struct auth_usersupplied_info *user_info_temp; + nt_status = encrypt_user_info(mem_ctx, ctx->auth_ctx, + AUTH_PASSWORD_RESPONSE, + user_info, &user_info_temp); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + user_info = user_info_temp; + + ZERO_STRUCT(request); + ZERO_STRUCT(response); + request.flags = WBFLAG_PAM_INFO3_NDR; + + request.data.auth_crap.logon_parameters = user_info->logon_parameters; + + safe_strcpy(request.data.auth_crap.user, + user_info->client.account_name, sizeof(fstring)); + safe_strcpy(request.data.auth_crap.domain, + user_info->client.domain_name, sizeof(fstring)); + safe_strcpy(request.data.auth_crap.workstation, + user_info->workstation_name, sizeof(fstring)); + + memcpy(request.data.auth_crap.chal, ctx->auth_ctx->challenge.data.data, sizeof(request.data.auth_crap.chal)); + + request.data.auth_crap.lm_resp_len = MIN(user_info->password.response.lanman.length, + sizeof(request.data.auth_crap.lm_resp)); + request.data.auth_crap.nt_resp_len = MIN(user_info->password.response.nt.length, + sizeof(request.data.auth_crap.nt_resp)); + + memcpy(request.data.auth_crap.lm_resp, user_info->password.response.lanman.data, + request.data.auth_crap.lm_resp_len); + memcpy(request.data.auth_crap.nt_resp, user_info->password.response.nt.data, + request.data.auth_crap.nt_resp_len); + + result = winbindd_request_response(WINBINDD_PAM_AUTH_CRAP, &request, &response); + + nt_status = NT_STATUS(response.data.auth.nt_status); + NT_STATUS_NOT_OK_RETURN(nt_status); + + if (result == NSS_STATUS_SUCCESS && response.extra_data.data) { + union netr_Validation validation; + + nt_status = get_info3_from_ndr(mem_ctx, lp_iconv_convenience(ctx->auth_ctx->lp_ctx), &response, &info3); + SAFE_FREE(response.extra_data.data); + NT_STATUS_NOT_OK_RETURN(nt_status); + + validation.sam3 = &info3; + nt_status = make_server_info_netlogon_validation(mem_ctx, + user_info->client.account_name, + 3, &validation, + server_info); + return nt_status; + } else if (result == NSS_STATUS_SUCCESS && !response.extra_data.data) { + DEBUG(0, ("Winbindd authenticated the user [%s]\\[%s], " + "but did not include the required info3 reply!\n", + user_info->client.domain_name, user_info->client.account_name)); + return NT_STATUS_INSUFFICIENT_LOGON_INFO; + } else if (NT_STATUS_IS_OK(nt_status)) { + DEBUG(1, ("Winbindd authentication for [%s]\\[%s] failed, " + "but no error code is available!\n", + user_info->client.domain_name, user_info->client.account_name)); + return NT_STATUS_NO_LOGON_SERVERS; + } + + return nt_status; +} + +struct winbind_check_password_state { + struct winbind_SamLogon req; +}; + +/* + Authenticate a user with a challenge/response + using IRPC to the winbind task +*/ +static NTSTATUS winbind_check_password(struct auth_method_context *ctx, + TALLOC_CTX *mem_ctx, + const struct auth_usersupplied_info *user_info, + struct auth_serversupplied_info **server_info) +{ + NTSTATUS status; + struct server_id *winbind_servers; + struct winbind_check_password_state *s; + const struct auth_usersupplied_info *user_info_new; + struct netr_IdentityInfo *identity_info; + + s = talloc(mem_ctx, struct winbind_check_password_state); + NT_STATUS_HAVE_NO_MEMORY(s); + + winbind_servers = irpc_servers_byname(ctx->auth_ctx->msg_ctx, s, "winbind_server"); + if ((winbind_servers == NULL) || (winbind_servers[0].id == 0)) { + DEBUG(0, ("Winbind authentication for [%s]\\[%s] failed, " + "no winbind_server running!\n", + user_info->client.domain_name, user_info->client.account_name)); + return NT_STATUS_NO_LOGON_SERVERS; + } + + if (user_info->flags & USER_INFO_INTERACTIVE_LOGON) { + struct netr_PasswordInfo *password_info; + + status = encrypt_user_info(s, ctx->auth_ctx, AUTH_PASSWORD_HASH, + user_info, &user_info_new); + NT_STATUS_NOT_OK_RETURN(status); + user_info = user_info_new; + + password_info = talloc(s, struct netr_PasswordInfo); + NT_STATUS_HAVE_NO_MEMORY(password_info); + + password_info->lmpassword = *user_info->password.hash.lanman; + password_info->ntpassword = *user_info->password.hash.nt; + + identity_info = &password_info->identity_info; + s->req.in.logon_level = 1; + s->req.in.logon.password= password_info; + } else { + struct netr_NetworkInfo *network_info; + const uint8_t *challenge; + + status = encrypt_user_info(s, ctx->auth_ctx, AUTH_PASSWORD_RESPONSE, + user_info, &user_info_new); + NT_STATUS_NOT_OK_RETURN(status); + user_info = user_info_new; + + network_info = talloc(s, struct netr_NetworkInfo); + NT_STATUS_HAVE_NO_MEMORY(network_info); + + status = auth_get_challenge(ctx->auth_ctx, &challenge); + NT_STATUS_NOT_OK_RETURN(status); + + memcpy(network_info->challenge, challenge, sizeof(network_info->challenge)); + + network_info->nt.length = user_info->password.response.nt.length; + network_info->nt.data = user_info->password.response.nt.data; + + network_info->lm.length = user_info->password.response.lanman.length; + network_info->lm.data = user_info->password.response.lanman.data; + + identity_info = &network_info->identity_info; + s->req.in.logon_level = 2; + s->req.in.logon.network = network_info; + } + + identity_info->domain_name.string = user_info->client.domain_name; + identity_info->parameter_control = user_info->logon_parameters; /* see MSV1_0_* */ + identity_info->logon_id_low = 0; + identity_info->logon_id_high = 0; + identity_info->account_name.string = user_info->client.account_name; + identity_info->workstation.string = user_info->workstation_name; + + s->req.in.validation_level = 3; + + status = IRPC_CALL(ctx->auth_ctx->msg_ctx, winbind_servers[0], + winbind, WINBIND_SAMLOGON, + &s->req, s); + NT_STATUS_NOT_OK_RETURN(status); + + status = make_server_info_netlogon_validation(mem_ctx, + user_info->client.account_name, + s->req.in.validation_level, + &s->req.out.validation, + server_info); + NT_STATUS_NOT_OK_RETURN(status); + + return NT_STATUS_OK; +} + +static const struct auth_operations winbind_samba3_ops = { + .name = "winbind_samba3", + .get_challenge = auth_get_challenge_not_implemented, + .want_check = winbind_want_check, + .check_password = winbind_check_password_samba3 +}; + +static const struct auth_operations winbind_ops = { + .name = "winbind", + .get_challenge = auth_get_challenge_not_implemented, + .want_check = winbind_want_check, + .check_password = winbind_check_password +}; + +_PUBLIC_ NTSTATUS auth_winbind_init(void) +{ + NTSTATUS ret; + + ret = auth_register(&winbind_samba3_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'winbind_samba3' auth backend!\n")); + return ret; + } + + ret = auth_register(&winbind_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register 'winbind' auth backend!\n")); + return ret; + } + + return NT_STATUS_OK; +} diff --git a/source4/auth/ntlm/config.mk b/source4/auth/ntlm/config.mk new file mode 100644 index 0000000000..4792a26bfd --- /dev/null +++ b/source4/auth/ntlm/config.mk @@ -0,0 +1,85 @@ +# NTLM auth server subsystem + +[SUBSYSTEM::ntlm_check] +PRIVATE_DEPENDENCIES = LIBSAMBA-UTIL + +ntlm_check_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, ntlm_check.o) + +####################### +# Start MODULE auth_sam +[MODULE::auth_sam_module] +# gensec_krb5 and gensec_gssapi depend on it +INIT_FUNCTION = auth_sam_init +SUBSYSTEM = auth +PRIVATE_DEPENDENCIES = \ + SAMDB auth_sam ntlm_check +# End MODULE auth_sam +####################### + +auth_sam_module_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, auth_sam.o) + +####################### +# Start MODULE auth_anonymous +[MODULE::auth_anonymous] +INIT_FUNCTION = auth_anonymous_init +SUBSYSTEM = auth +# End MODULE auth_anonymous +####################### + +auth_anonymous_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, auth_anonymous.o) + +####################### +# Start MODULE auth_anonymous +[MODULE::auth_server] +INIT_FUNCTION = auth_server_init +SUBSYSTEM = auth +PRIVATE_DEPENDENCIES = LIBSAMBA-UTIL LIBCLI_SMB +# End MODULE auth_server +####################### + +auth_server_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, auth_server.o) + +####################### +# Start MODULE auth_winbind +[MODULE::auth_winbind] +INIT_FUNCTION = auth_winbind_init +SUBSYSTEM = auth +PRIVATE_DEPENDENCIES = NDR_WINBIND MESSAGING LIBWINBIND-CLIENT +# End MODULE auth_winbind +####################### + +auth_winbind_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, auth_winbind.o) + +####################### +# Start MODULE auth_developer +[MODULE::auth_developer] +INIT_FUNCTION = auth_developer_init +SUBSYSTEM = auth +# End MODULE auth_developer +####################### + +auth_developer_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, auth_developer.o) + +[MODULE::auth_unix] +INIT_FUNCTION = auth_unix_init +SUBSYSTEM = auth +PRIVATE_DEPENDENCIES = CRYPT PAM PAM_ERRORS NSS_WRAPPER + +auth_unix_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, auth_unix.o) + +[SUBSYSTEM::PAM_ERRORS] + +#VERSION = 0.0.1 +#SO_VERSION = 0 +PAM_ERRORS_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, pam_errors.o) + +[MODULE::auth] +INIT_FUNCTION = server_service_auth_init +SUBSYSTEM = service +PRIVATE_DEPENDENCIES = LIBSAMBA-UTIL LIBSECURITY SAMDB CREDENTIALS + +auth_OBJ_FILES = $(addprefix $(authsrcdir)/ntlm/, auth.o auth_util.o auth_simple.o) +$(eval $(call proto_header_template,$(authsrcdir)/auth_proto.h,$(auth_OBJ_FILES:.o=.c))) + +# PUBLIC_HEADERS += auth/auth.h + diff --git a/source4/auth/ntlm/ntlm_check.c b/source4/auth/ntlm/ntlm_check.c new file mode 100644 index 0000000000..0dbbce0edc --- /dev/null +++ b/source4/auth/ntlm/ntlm_check.c @@ -0,0 +1,603 @@ +/* + Unix SMB/CIFS implementation. + Password and authentication handling + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2004 + Copyright (C) Gerald Carter 2003 + Copyright (C) Luke Kenneth Casson Leighton 1996-2000 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "lib/crypto/crypto.h" +#include "librpc/gen_ndr/netlogon.h" +#include "libcli/auth/libcli_auth.h" +#include "param/param.h" +#include "auth/ntlm/ntlm_check.h" + +/**************************************************************************** + Core of smb password checking routine. +****************************************************************************/ + +static bool smb_pwd_check_ntlmv1(TALLOC_CTX *mem_ctx, + const DATA_BLOB *nt_response, + const uint8_t *part_passwd, + const DATA_BLOB *sec_blob, + DATA_BLOB *user_sess_key) +{ + /* Finish the encryption of part_passwd. */ + uint8_t p24[24]; + + if (part_passwd == NULL) { + DEBUG(10,("No password set - DISALLOWING access\n")); + /* No password set - always false ! */ + return false; + } + + if (sec_blob->length != 8) { + DEBUG(0, ("smb_pwd_check_ntlmv1: incorrect challenge size (%lu)\n", + (unsigned long)sec_blob->length)); + return false; + } + + if (nt_response->length != 24) { + DEBUG(0, ("smb_pwd_check_ntlmv1: incorrect password length (%lu)\n", + (unsigned long)nt_response->length)); + return false; + } + + SMBOWFencrypt(part_passwd, sec_blob->data, p24); + +#if DEBUG_PASSWORD + DEBUG(100,("Part password (P16) was |\n")); + dump_data(100, part_passwd, 16); + DEBUGADD(100,("Password from client was |\n")); + dump_data(100, nt_response->data, nt_response->length); + DEBUGADD(100,("Given challenge was |\n")); + dump_data(100, sec_blob->data, sec_blob->length); + DEBUGADD(100,("Value from encryption was |\n")); + dump_data(100, p24, 24); +#endif + if (memcmp(p24, nt_response->data, 24) == 0) { + if (user_sess_key != NULL) { + *user_sess_key = data_blob_talloc(mem_ctx, NULL, 16); + SMBsesskeygen_ntv1(part_passwd, user_sess_key->data); + } + return true; + } + return false; +} + +/**************************************************************************** + Core of smb password checking routine. (NTLMv2, LMv2) + Note: The same code works with both NTLMv2 and LMv2. +****************************************************************************/ + +static bool smb_pwd_check_ntlmv2(TALLOC_CTX *mem_ctx, + const DATA_BLOB *ntv2_response, + const uint8_t *part_passwd, + const DATA_BLOB *sec_blob, + const char *user, const char *domain, + bool upper_case_domain, /* should the domain be transformed into upper case? */ + DATA_BLOB *user_sess_key) +{ + /* Finish the encryption of part_passwd. */ + uint8_t kr[16]; + uint8_t value_from_encryption[16]; + DATA_BLOB client_key_data; + + if (part_passwd == NULL) { + DEBUG(10,("No password set - DISALLOWING access\n")); + /* No password set - always false */ + return false; + } + + if (sec_blob->length != 8) { + DEBUG(0, ("smb_pwd_check_ntlmv2: incorrect challenge size (%lu)\n", + (unsigned long)sec_blob->length)); + return false; + } + + if (ntv2_response->length < 24) { + /* We MUST have more than 16 bytes, or the stuff below will go + crazy. No known implementation sends less than the 24 bytes + for LMv2, let alone NTLMv2. */ + DEBUG(0, ("smb_pwd_check_ntlmv2: incorrect password length (%lu)\n", + (unsigned long)ntv2_response->length)); + return false; + } + + client_key_data = data_blob_talloc(mem_ctx, ntv2_response->data+16, ntv2_response->length-16); + /* + todo: should we be checking this for anything? We can't for LMv2, + but for NTLMv2 it is meant to contain the current time etc. + */ + + if (!ntv2_owf_gen(part_passwd, user, domain, upper_case_domain, kr)) { + return false; + } + + SMBOWFencrypt_ntv2(kr, sec_blob, &client_key_data, value_from_encryption); + +#if DEBUG_PASSWORD + DEBUG(100,("Part password (P16) was |\n")); + dump_data(100, part_passwd, 16); + DEBUGADD(100,("Password from client was |\n")); + dump_data(100, ntv2_response->data, ntv2_response->length); + DEBUGADD(100,("Variable data from client was |\n")); + dump_data(100, client_key_data.data, client_key_data.length); + DEBUGADD(100,("Given challenge was |\n")); + dump_data(100, sec_blob->data, sec_blob->length); + DEBUGADD(100,("Value from encryption was |\n")); + dump_data(100, value_from_encryption, 16); +#endif + data_blob_clear_free(&client_key_data); + if (memcmp(value_from_encryption, ntv2_response->data, 16) == 0) { + if (user_sess_key != NULL) { + *user_sess_key = data_blob_talloc(mem_ctx, NULL, 16); + SMBsesskeygen_ntv2(kr, value_from_encryption, user_sess_key->data); + } + return true; + } + return false; +} + +/**************************************************************************** + Core of smb password checking routine. (NTLMv2, LMv2) + Note: The same code works with both NTLMv2 and LMv2. +****************************************************************************/ + +static bool smb_sess_key_ntlmv2(TALLOC_CTX *mem_ctx, + const DATA_BLOB *ntv2_response, + const uint8_t *part_passwd, + const DATA_BLOB *sec_blob, + const char *user, const char *domain, + bool upper_case_domain, /* should the domain be transformed into upper case? */ + DATA_BLOB *user_sess_key) +{ + /* Finish the encryption of part_passwd. */ + uint8_t kr[16]; + uint8_t value_from_encryption[16]; + DATA_BLOB client_key_data; + + if (part_passwd == NULL) { + DEBUG(10,("No password set - DISALLOWING access\n")); + /* No password set - always false */ + return false; + } + + if (sec_blob->length != 8) { + DEBUG(0, ("smb_sess_key_ntlmv2: incorrect challenge size (%lu)\n", + (unsigned long)sec_blob->length)); + return false; + } + + if (ntv2_response->length < 24) { + /* We MUST have more than 16 bytes, or the stuff below will go + crazy. No known implementation sends less than the 24 bytes + for LMv2, let alone NTLMv2. */ + DEBUG(0, ("smb_sess_key_ntlmv2: incorrect password length (%lu)\n", + (unsigned long)ntv2_response->length)); + return false; + } + + client_key_data = data_blob_talloc(mem_ctx, ntv2_response->data+16, ntv2_response->length-16); + + if (!ntv2_owf_gen(part_passwd, user, domain, upper_case_domain, kr)) { + return false; + } + + SMBOWFencrypt_ntv2(kr, sec_blob, &client_key_data, value_from_encryption); + *user_sess_key = data_blob_talloc(mem_ctx, NULL, 16); + SMBsesskeygen_ntv2(kr, value_from_encryption, user_sess_key->data); + return true; +} + +/** + * Compare password hashes against those from the SAM + * + * @param mem_ctx talloc context + * @param client_lanman LANMAN password hash, as supplied by the client + * @param client_nt NT (MD4) password hash, as supplied by the client + * @param username internal Samba username, for log messages + * @param client_username username the client used + * @param client_domain domain name the client used (may be mapped) + * @param stored_lanman LANMAN password hash, as stored on the SAM + * @param stored_nt NT (MD4) password hash, as stored on the SAM + * @param user_sess_key User session key + * @param lm_sess_key LM session key (first 8 bytes of the LM hash) + */ + +NTSTATUS hash_password_check(TALLOC_CTX *mem_ctx, + struct loadparm_context *lp_ctx, + const struct samr_Password *client_lanman, + const struct samr_Password *client_nt, + const char *username, + const struct samr_Password *stored_lanman, + const struct samr_Password *stored_nt) +{ + if (stored_nt == NULL) { + DEBUG(3,("ntlm_password_check: NO NT password stored for user %s.\n", + username)); + } + + if (client_nt && stored_nt) { + if (memcmp(client_nt->hash, stored_nt->hash, sizeof(stored_nt->hash)) == 0) { + return NT_STATUS_OK; + } else { + DEBUG(3,("ntlm_password_check: Interactive logon: NT password check failed for user %s\n", + username)); + return NT_STATUS_WRONG_PASSWORD; + } + + } else if (client_lanman && stored_lanman) { + if (!lp_lanman_auth(lp_ctx)) { + DEBUG(3,("ntlm_password_check: Interactive logon: only LANMAN password supplied for user %s, and LM passwords are disabled!\n", + username)); + return NT_STATUS_WRONG_PASSWORD; + } + if (strchr_m(username, '@')) { + return NT_STATUS_NOT_FOUND; + } + + if (memcmp(client_lanman->hash, stored_lanman->hash, sizeof(stored_lanman->hash)) == 0) { + return NT_STATUS_OK; + } else { + DEBUG(3,("ntlm_password_check: Interactive logon: LANMAN password check failed for user %s\n", + username)); + return NT_STATUS_WRONG_PASSWORD; + } + } + if (strchr_m(username, '@')) { + return NT_STATUS_NOT_FOUND; + } + return NT_STATUS_WRONG_PASSWORD; +} + +/** + * Check a challenge-response password against the value of the NT or + * LM password hash. + * + * @param mem_ctx talloc context + * @param challenge 8-byte challenge. If all zero, forces plaintext comparison + * @param nt_response 'unicode' NT response to the challenge, or unicode password + * @param lm_response ASCII or LANMAN response to the challenge, or password in DOS code page + * @param username internal Samba username, for log messages + * @param client_username username the client used + * @param client_domain domain name the client used (may be mapped) + * @param stored_lanman LANMAN ASCII password from our passdb or similar + * @param stored_nt MD4 unicode password from our passdb or similar + * @param user_sess_key User session key + * @param lm_sess_key LM session key (first 8 bytes of the LM hash) + */ + +NTSTATUS ntlm_password_check(TALLOC_CTX *mem_ctx, + struct loadparm_context *lp_ctx, + uint32_t logon_parameters, + const DATA_BLOB *challenge, + const DATA_BLOB *lm_response, + const DATA_BLOB *nt_response, + const char *username, + const char *client_username, + const char *client_domain, + const struct samr_Password *stored_lanman, + const struct samr_Password *stored_nt, + DATA_BLOB *user_sess_key, + DATA_BLOB *lm_sess_key) +{ + const static uint8_t zeros[8]; + DATA_BLOB tmp_sess_key; + + if (stored_nt == NULL) { + DEBUG(3,("ntlm_password_check: NO NT password stored for user %s.\n", + username)); + } + + *lm_sess_key = data_blob(NULL, 0); + *user_sess_key = data_blob(NULL, 0); + + /* Check for cleartext netlogon. Used by Exchange 5.5. */ + if ((logon_parameters & MSV1_0_CLEARTEXT_PASSWORD_ALLOWED) + && challenge->length == sizeof(zeros) + && (memcmp(challenge->data, zeros, challenge->length) == 0 )) { + struct samr_Password client_nt; + struct samr_Password client_lm; + char *unix_pw = NULL; + bool lm_ok; + + DEBUG(4,("ntlm_password_check: checking plaintext passwords for user %s\n", + username)); + mdfour(client_nt.hash, nt_response->data, nt_response->length); + + if (lm_response->length && + (convert_string_talloc(mem_ctx, lp_iconv_convenience(lp_ctx), CH_DOS, CH_UNIX, + lm_response->data, lm_response->length, + (void **)&unix_pw) != -1)) { + if (E_deshash(unix_pw, client_lm.hash)) { + lm_ok = true; + } else { + lm_ok = false; + } + } else { + lm_ok = false; + } + return hash_password_check(mem_ctx, + lp_ctx, + lm_ok ? &client_lm : NULL, + nt_response->length ? &client_nt : NULL, + username, + stored_lanman, stored_nt); + } + + if (nt_response->length != 0 && nt_response->length < 24) { + DEBUG(2,("ntlm_password_check: invalid NT password length (%lu) for user %s\n", + (unsigned long)nt_response->length, username)); + } + + if (nt_response->length > 24 && stored_nt) { + /* We have the NT MD4 hash challenge available - see if we can + use it + */ + DEBUG(4,("ntlm_password_check: Checking NTLMv2 password with domain [%s]\n", client_domain)); + if (smb_pwd_check_ntlmv2(mem_ctx, + nt_response, + stored_nt->hash, challenge, + client_username, + client_domain, + false, + user_sess_key)) { + *lm_sess_key = *user_sess_key; + if (user_sess_key->length) { + lm_sess_key->length = 8; + } + return NT_STATUS_OK; + } + + DEBUG(4,("ntlm_password_check: Checking NTLMv2 password with uppercased version of domain [%s]\n", client_domain)); + if (smb_pwd_check_ntlmv2(mem_ctx, + nt_response, + stored_nt->hash, challenge, + client_username, + client_domain, + true, + user_sess_key)) { + *lm_sess_key = *user_sess_key; + if (user_sess_key->length) { + lm_sess_key->length = 8; + } + return NT_STATUS_OK; + } + + DEBUG(4,("ntlm_password_check: Checking NTLMv2 password without a domain\n")); + if (smb_pwd_check_ntlmv2(mem_ctx, + nt_response, + stored_nt->hash, challenge, + client_username, + "", + false, + user_sess_key)) { + *lm_sess_key = *user_sess_key; + if (user_sess_key->length) { + lm_sess_key->length = 8; + } + return NT_STATUS_OK; + } else { + DEBUG(3,("ntlm_password_check: NTLMv2 password check failed\n")); + } + } else if (nt_response->length == 24 && stored_nt) { + if (lp_ntlm_auth(lp_ctx)) { + /* We have the NT MD4 hash challenge available - see if we can + use it (ie. does it exist in the smbpasswd file). + */ + DEBUG(4,("ntlm_password_check: Checking NT MD4 password\n")); + if (smb_pwd_check_ntlmv1(mem_ctx, + nt_response, + stored_nt->hash, challenge, + user_sess_key)) { + /* The LM session key for this response is not very secure, + so use it only if we otherwise allow LM authentication */ + + if (lp_lanman_auth(lp_ctx) && stored_lanman) { + *lm_sess_key = data_blob_talloc(mem_ctx, stored_lanman->hash, 8); + } + return NT_STATUS_OK; + } else { + DEBUG(3,("ntlm_password_check: NT MD4 password check failed for user %s\n", + username)); + return NT_STATUS_WRONG_PASSWORD; + } + } else { + DEBUG(2,("ntlm_password_check: NTLMv1 passwords NOT PERMITTED for user %s\n", + username)); + /* no return, becouse we might pick up LMv2 in the LM field */ + } + } + + if (lm_response->length == 0) { + DEBUG(3,("ntlm_password_check: NEITHER LanMan nor NT password supplied for user %s\n", + username)); + return NT_STATUS_WRONG_PASSWORD; + } + + if (lm_response->length < 24) { + DEBUG(2,("ntlm_password_check: invalid LanMan password length (%lu) for user %s\n", + (unsigned long)nt_response->length, username)); + return NT_STATUS_WRONG_PASSWORD; + } + + if (!lp_lanman_auth(lp_ctx)) { + DEBUG(3,("ntlm_password_check: Lanman passwords NOT PERMITTED for user %s\n", + username)); + } else if (!stored_lanman) { + DEBUG(3,("ntlm_password_check: NO LanMan password set for user %s (and no NT password supplied)\n", + username)); + } else if (strchr_m(username, '@')) { + DEBUG(3,("ntlm_password_check: NO LanMan password allowed for username@realm logins (user: %s)\n", + username)); + } else { + DEBUG(4,("ntlm_password_check: Checking LM password\n")); + if (smb_pwd_check_ntlmv1(mem_ctx, + lm_response, + stored_lanman->hash, challenge, + NULL)) { + /* The session key for this response is still very odd. + It not very secure, so use it only if we otherwise + allow LM authentication */ + + if (lp_lanman_auth(lp_ctx) && stored_lanman) { + uint8_t first_8_lm_hash[16]; + memcpy(first_8_lm_hash, stored_lanman->hash, 8); + memset(first_8_lm_hash + 8, '\0', 8); + *user_sess_key = data_blob_talloc(mem_ctx, first_8_lm_hash, 16); + *lm_sess_key = data_blob_talloc(mem_ctx, stored_lanman->hash, 8); + } + return NT_STATUS_OK; + } + } + + if (!stored_nt) { + DEBUG(4,("ntlm_password_check: LM password check failed for user, no NT password %s\n",username)); + return NT_STATUS_WRONG_PASSWORD; + } + + /* This is for 'LMv2' authentication. almost NTLMv2 but limited to 24 bytes. + - related to Win9X, legacy NAS pass-though authentication + */ + DEBUG(4,("ntlm_password_check: Checking LMv2 password with domain %s\n", client_domain)); + if (smb_pwd_check_ntlmv2(mem_ctx, + lm_response, + stored_nt->hash, challenge, + client_username, + client_domain, + false, + &tmp_sess_key)) { + if (nt_response->length > 24) { + /* If NTLMv2 authentication has preceeded us + * (even if it failed), then use the session + * key from that. See the RPC-SAMLOGON + * torture test */ + smb_sess_key_ntlmv2(mem_ctx, + nt_response, + stored_nt->hash, challenge, + client_username, + client_domain, + false, + user_sess_key); + } else { + /* Otherwise, use the LMv2 session key */ + *user_sess_key = tmp_sess_key; + } + *lm_sess_key = *user_sess_key; + if (user_sess_key->length) { + lm_sess_key->length = 8; + } + return NT_STATUS_OK; + } + + DEBUG(4,("ntlm_password_check: Checking LMv2 password with upper-cased version of domain %s\n", client_domain)); + if (smb_pwd_check_ntlmv2(mem_ctx, + lm_response, + stored_nt->hash, challenge, + client_username, + client_domain, + true, + &tmp_sess_key)) { + if (nt_response->length > 24) { + /* If NTLMv2 authentication has preceeded us + * (even if it failed), then use the session + * key from that. See the RPC-SAMLOGON + * torture test */ + smb_sess_key_ntlmv2(mem_ctx, + nt_response, + stored_nt->hash, challenge, + client_username, + client_domain, + true, + user_sess_key); + } else { + /* Otherwise, use the LMv2 session key */ + *user_sess_key = tmp_sess_key; + } + *lm_sess_key = *user_sess_key; + if (user_sess_key->length) { + lm_sess_key->length = 8; + } + return NT_STATUS_OK; + } + + DEBUG(4,("ntlm_password_check: Checking LMv2 password without a domain\n")); + if (smb_pwd_check_ntlmv2(mem_ctx, + lm_response, + stored_nt->hash, challenge, + client_username, + "", + false, + &tmp_sess_key)) { + if (nt_response->length > 24) { + /* If NTLMv2 authentication has preceeded us + * (even if it failed), then use the session + * key from that. See the RPC-SAMLOGON + * torture test */ + smb_sess_key_ntlmv2(mem_ctx, + nt_response, + stored_nt->hash, challenge, + client_username, + "", + false, + user_sess_key); + } else { + /* Otherwise, use the LMv2 session key */ + *user_sess_key = tmp_sess_key; + } + *lm_sess_key = *user_sess_key; + if (user_sess_key->length) { + lm_sess_key->length = 8; + } + return NT_STATUS_OK; + } + + /* Apparently NT accepts NT responses in the LM field + - I think this is related to Win9X pass-though authentication + */ + DEBUG(4,("ntlm_password_check: Checking NT MD4 password in LM field\n")); + if (lp_ntlm_auth(lp_ctx)) { + if (smb_pwd_check_ntlmv1(mem_ctx, + lm_response, + stored_nt->hash, challenge, + NULL)) { + /* The session key for this response is still very odd. + It not very secure, so use it only if we otherwise + allow LM authentication */ + + if (lp_lanman_auth(lp_ctx) && stored_lanman) { + uint8_t first_8_lm_hash[16]; + memcpy(first_8_lm_hash, stored_lanman->hash, 8); + memset(first_8_lm_hash + 8, '\0', 8); + *user_sess_key = data_blob_talloc(mem_ctx, first_8_lm_hash, 16); + *lm_sess_key = data_blob_talloc(mem_ctx, stored_lanman->hash, 8); + } + return NT_STATUS_OK; + } + DEBUG(3,("ntlm_password_check: LM password, NT MD4 password in LM field and LMv2 failed for user %s\n",username)); + } else { + DEBUG(3,("ntlm_password_check: LM password and LMv2 failed for user %s, and NT MD4 password in LM field not permitted\n",username)); + } + + /* Try and match error codes */ + if (strchr_m(username, '@')) { + return NT_STATUS_NOT_FOUND; + } + return NT_STATUS_WRONG_PASSWORD; +} + diff --git a/source4/auth/ntlm/ntlm_check.h b/source4/auth/ntlm/ntlm_check.h new file mode 100644 index 0000000000..eb115b74d6 --- /dev/null +++ b/source4/auth/ntlm/ntlm_check.h @@ -0,0 +1,75 @@ +/* + Unix SMB/CIFS implementation. + Password and authentication handling + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2004 + Copyright (C) Gerald Carter 2003 + Copyright (C) Luke Kenneth Casson Leighton 1996-2000 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + + +/** + * Compare password hashes against those from the SAM + * + * @param mem_ctx talloc context + * @param client_lanman LANMAN password hash, as supplied by the client + * @param client_nt NT (MD4) password hash, as supplied by the client + * @param username internal Samba username, for log messages + * @param client_username username the client used + * @param client_domain domain name the client used (may be mapped) + * @param stored_lanman LANMAN password hash, as stored on the SAM + * @param stored_nt NT (MD4) password hash, as stored on the SAM + * @param user_sess_key User session key + * @param lm_sess_key LM session key (first 8 bytes of the LM hash) + */ + +NTSTATUS hash_password_check(TALLOC_CTX *mem_ctx, + struct loadparm_context *lp_ctx, + const struct samr_Password *client_lanman, + const struct samr_Password *client_nt, + const char *username, + const struct samr_Password *stored_lanman, + const struct samr_Password *stored_nt); + +/** + * Check a challenge-response password against the value of the NT or + * LM password hash. + * + * @param mem_ctx talloc context + * @param challenge 8-byte challenge. If all zero, forces plaintext comparison + * @param nt_response 'unicode' NT response to the challenge, or unicode password + * @param lm_response ASCII or LANMAN response to the challenge, or password in DOS code page + * @param username internal Samba username, for log messages + * @param client_username username the client used + * @param client_domain domain name the client used (may be mapped) + * @param stored_lanman LANMAN ASCII password from our passdb or similar + * @param stored_nt MD4 unicode password from our passdb or similar + * @param user_sess_key User session key + * @param lm_sess_key LM session key (first 8 bytes of the LM hash) + */ + +NTSTATUS ntlm_password_check(TALLOC_CTX *mem_ctx, + struct loadparm_context *lp_ctx, + uint32_t logon_parameters, + const DATA_BLOB *challenge, + const DATA_BLOB *lm_response, + const DATA_BLOB *nt_response, + const char *username, + const char *client_username, + const char *client_domain, + const struct samr_Password *stored_lanman, + const struct samr_Password *stored_nt, + DATA_BLOB *user_sess_key, + DATA_BLOB *lm_sess_key); diff --git a/source4/auth/ntlm/pam_errors.c b/source4/auth/ntlm/pam_errors.c new file mode 100644 index 0000000000..9774ad8727 --- /dev/null +++ b/source4/auth/ntlm/pam_errors.c @@ -0,0 +1,125 @@ +/* + * Unix SMB/CIFS implementation. + * PAM error mapping functions + * Copyright (C) Andrew Bartlett 2002 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "includes.h" + +#ifdef WITH_HAVE_SECURITY_PAM_APPL_H +#include <security/pam_appl.h> + +#if defined(PAM_AUTHTOK_RECOVERY_ERR) && !defined(PAM_AUTHTOK_RECOVER_ERR) +#define PAM_AUTHTOK_RECOVER_ERR PAM_AUTHTOK_RECOVERY_ERR +#endif + +/* PAM -> NT_STATUS map */ +static const struct { + int pam_code; + NTSTATUS ntstatus; +} pam_to_nt_status_map[] = { + {PAM_OPEN_ERR, NT_STATUS_UNSUCCESSFUL}, + {PAM_SYMBOL_ERR, NT_STATUS_UNSUCCESSFUL}, + {PAM_SERVICE_ERR, NT_STATUS_UNSUCCESSFUL}, + {PAM_SYSTEM_ERR, NT_STATUS_UNSUCCESSFUL}, + {PAM_BUF_ERR, NT_STATUS_UNSUCCESSFUL}, + {PAM_PERM_DENIED, NT_STATUS_ACCESS_DENIED}, + {PAM_AUTH_ERR, NT_STATUS_WRONG_PASSWORD}, + {PAM_CRED_INSUFFICIENT, NT_STATUS_INSUFFICIENT_LOGON_INFO}, /* FIXME: Is this correct? */ + {PAM_AUTHINFO_UNAVAIL, NT_STATUS_LOGON_FAILURE}, + {PAM_USER_UNKNOWN, NT_STATUS_NO_SUCH_USER}, + {PAM_MAXTRIES, NT_STATUS_REMOTE_SESSION_LIMIT}, /* FIXME: Is this correct? */ + {PAM_NEW_AUTHTOK_REQD, NT_STATUS_PASSWORD_MUST_CHANGE}, + {PAM_ACCT_EXPIRED, NT_STATUS_ACCOUNT_EXPIRED}, + {PAM_SESSION_ERR, NT_STATUS_INSUFFICIENT_RESOURCES}, + {PAM_CRED_UNAVAIL, NT_STATUS_NO_TOKEN}, /* FIXME: Is this correct? */ + {PAM_CRED_EXPIRED, NT_STATUS_PASSWORD_EXPIRED}, /* FIXME: Is this correct? */ + {PAM_CRED_ERR, NT_STATUS_UNSUCCESSFUL}, + {PAM_AUTHTOK_ERR, NT_STATUS_UNSUCCESSFUL}, +#ifdef PAM_AUTHTOK_RECOVER_ERR + {PAM_AUTHTOK_RECOVER_ERR, NT_STATUS_UNSUCCESSFUL}, +#endif + {PAM_AUTHTOK_EXPIRED, NT_STATUS_PASSWORD_EXPIRED}, + {PAM_SUCCESS, NT_STATUS_OK} +}; + +/* NT_STATUS -> PAM map */ +static const struct { + NTSTATUS ntstatus; + int pam_code; +} nt_status_to_pam_map[] = { + {NT_STATUS_UNSUCCESSFUL, PAM_SYSTEM_ERR}, + {NT_STATUS_NO_SUCH_USER, PAM_USER_UNKNOWN}, + {NT_STATUS_WRONG_PASSWORD, PAM_AUTH_ERR}, + {NT_STATUS_LOGON_FAILURE, PAM_AUTH_ERR}, + {NT_STATUS_ACCOUNT_EXPIRED, PAM_ACCT_EXPIRED}, + {NT_STATUS_PASSWORD_EXPIRED, PAM_AUTHTOK_EXPIRED}, + {NT_STATUS_PASSWORD_MUST_CHANGE, PAM_NEW_AUTHTOK_REQD}, + {NT_STATUS_OK, PAM_SUCCESS} +}; + +/***************************************************************************** +convert a PAM error to a NT status32 code + *****************************************************************************/ +NTSTATUS pam_to_nt_status(int pam_error) +{ + int i; + if (pam_error == 0) return NT_STATUS_OK; + + for (i=0; NT_STATUS_V(pam_to_nt_status_map[i].ntstatus); i++) { + if (pam_error == pam_to_nt_status_map[i].pam_code) + return pam_to_nt_status_map[i].ntstatus; + } + return NT_STATUS_UNSUCCESSFUL; +} + +/***************************************************************************** +convert an NT status32 code to a PAM error + *****************************************************************************/ +int nt_status_to_pam(NTSTATUS nt_status) +{ + int i; + if NT_STATUS_IS_OK(nt_status) return PAM_SUCCESS; + + for (i=0; NT_STATUS_V(nt_status_to_pam_map[i].ntstatus); i++) { + if (NT_STATUS_EQUAL(nt_status,nt_status_to_pam_map[i].ntstatus)) + return nt_status_to_pam_map[i].pam_code; + } + return PAM_SYSTEM_ERR; +} + +#else + +/***************************************************************************** +convert a PAM error to a NT status32 code + *****************************************************************************/ +NTSTATUS pam_to_nt_status(int pam_error) +{ + if (pam_error == 0) return NT_STATUS_OK; + return NT_STATUS_UNSUCCESSFUL; +} + +/***************************************************************************** +convert an NT status32 code to a PAM error + *****************************************************************************/ +int nt_status_to_pam(NTSTATUS nt_status) +{ + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_OK)) return 0; + return 4; /* PAM_SYSTEM_ERR */ +} + +#endif + diff --git a/source4/auth/ntlm/pam_errors.h b/source4/auth/ntlm/pam_errors.h new file mode 100644 index 0000000000..959e1f3517 --- /dev/null +++ b/source4/auth/ntlm/pam_errors.h @@ -0,0 +1,47 @@ +/* + * Unix SMB/CIFS implementation. + * PAM error mapping functions + * Copyright (C) Andrew Bartlett 2002 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef __AUTH_NTLM_PAM_ERRORS_H__ +#define __AUTH_NTLM_PAM_ERRORS_H__ + +/* The following definitions come from auth/pam_errors.c */ + + +/***************************************************************************** +convert a PAM error to a NT status32 code + *****************************************************************************/ +NTSTATUS pam_to_nt_status(int pam_error); + +/***************************************************************************** +convert an NT status32 code to a PAM error + *****************************************************************************/ +int nt_status_to_pam(NTSTATUS nt_status); + +/***************************************************************************** +convert a PAM error to a NT status32 code + *****************************************************************************/ +NTSTATUS pam_to_nt_status(int pam_error); + +/***************************************************************************** +convert an NT status32 code to a PAM error + *****************************************************************************/ +int nt_status_to_pam(NTSTATUS nt_status); + +#endif /* __AUTH_NTLM_PAM_ERRORS_H__ */ + diff --git a/source4/auth/ntlmssp/config.mk b/source4/auth/ntlmssp/config.mk new file mode 100644 index 0000000000..129f58de83 --- /dev/null +++ b/source4/auth/ntlmssp/config.mk @@ -0,0 +1,19 @@ +[SUBSYSTEM::MSRPC_PARSE] + +MSRPC_PARSE_OBJ_FILES = $(addprefix $(authsrcdir)/ntlmssp/, ntlmssp_parse.o) + +$(eval $(call proto_header_template,$(authsrcdir)/ntlmssp/msrpc_parse.h,$(MSRPC_PARSE_OBJ_FILES:.o=.c))) + +################################################ +# Start MODULE gensec_ntlmssp +[MODULE::gensec_ntlmssp] +SUBSYSTEM = gensec +INIT_FUNCTION = gensec_ntlmssp_init +PRIVATE_DEPENDENCIES = MSRPC_PARSE CREDENTIALS auth +OUTPUT_TYPE = MERGED_OBJ +# End MODULE gensec_ntlmssp +################################################ + +gensec_ntlmssp_OBJ_FILES = $(addprefix $(authsrcdir)/ntlmssp/, ntlmssp.o ntlmssp_sign.o ntlmssp_client.o ntlmssp_server.o) + +$(eval $(call proto_header_template,$(authsrcdir)/ntlmssp/proto.h,$(gensec_ntlmssp_OBJ_FILES:.o=.c))) diff --git a/source4/auth/ntlmssp/ntlmssp.c b/source4/auth/ntlmssp/ntlmssp.c new file mode 100644 index 0000000000..0b7f0da9af --- /dev/null +++ b/source4/auth/ntlmssp/ntlmssp.c @@ -0,0 +1,444 @@ +/* + Unix SMB/Netbios implementation. + Version 3.0 + handle NLTMSSP, client server side parsing + + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2005 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/ntlmssp/ntlmssp.h" +#include "auth/ntlmssp/msrpc_parse.h" +#include "librpc/gen_ndr/ndr_dcerpc.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "auth/gensec/gensec_proto.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "param/param.h" + +/** + * Callbacks for NTLMSSP - for both client and server operating modes + * + */ + +static const struct ntlmssp_callbacks { + enum ntlmssp_role role; + enum ntlmssp_message_type command; + NTSTATUS (*sync_fn)(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + DATA_BLOB in, DATA_BLOB *out); +} ntlmssp_callbacks[] = { + { + .role = NTLMSSP_CLIENT, + .command = NTLMSSP_INITIAL, + .sync_fn = ntlmssp_client_initial, + },{ + .role = NTLMSSP_SERVER, + .command = NTLMSSP_NEGOTIATE, + .sync_fn = ntlmssp_server_negotiate, + },{ + .role = NTLMSSP_CLIENT, + .command = NTLMSSP_CHALLENGE, + .sync_fn = ntlmssp_client_challenge, + },{ + .role = NTLMSSP_SERVER, + .command = NTLMSSP_AUTH, + .sync_fn = ntlmssp_server_auth, + } +}; + + +/** + * Print out the NTLMSSP flags for debugging + * @param neg_flags The flags from the packet + */ + +void debug_ntlmssp_flags(uint32_t neg_flags) +{ + DEBUG(3,("Got NTLMSSP neg_flags=0x%08x\n", neg_flags)); + + if (neg_flags & NTLMSSP_NEGOTIATE_UNICODE) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_UNICODE\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_OEM) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_OEM\n")); + if (neg_flags & NTLMSSP_REQUEST_TARGET) + DEBUGADD(4, (" NTLMSSP_REQUEST_TARGET\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_SIGN) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_SIGN\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_SEAL) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_SEAL\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_DATAGRAM_STYLE) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_DATAGRAM_STYLE\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_LM_KEY\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_NETWARE) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_NETWARE\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_NTLM) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_NTLM\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_THIS_IS_LOCAL_CALL) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_THIS_IS_LOCAL_CALL\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n")); + if (neg_flags & NTLMSSP_CHAL_ACCEPT_RESPONSE) + DEBUGADD(4, (" NTLMSSP_CHAL_ACCEPT_RESPONSE\n")); + if (neg_flags & NTLMSSP_CHAL_NON_NT_SESSION_KEY) + DEBUGADD(4, (" NTLMSSP_CHAL_NON_NT_SESSION_KEY\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_NTLM2) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_NTLM2\n")); + if (neg_flags & NTLMSSP_CHAL_TARGET_INFO) + DEBUGADD(4, (" NTLMSSP_CHAL_TARGET_INFO\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_128) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_128\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_KEY_EXCH\n")); + if (neg_flags & NTLMSSP_NEGOTIATE_56) + DEBUGADD(4, (" NTLMSSP_NEGOTIATE_56\n")); +} + +static NTSTATUS gensec_ntlmssp_magic(struct gensec_security *gensec_security, + const DATA_BLOB *first_packet) +{ + if (first_packet->length > 8 && memcmp("NTLMSSP\0", first_packet->data, 8) == 0) { + return NT_STATUS_OK; + } else { + return NT_STATUS_INVALID_PARAMETER; + } +} + +static NTSTATUS gensec_ntlmssp_update_find(struct gensec_ntlmssp_state *gensec_ntlmssp_state, + const DATA_BLOB input, uint32_t *idx) +{ + struct gensec_security *gensec_security = gensec_ntlmssp_state->gensec_security; + uint32_t ntlmssp_command; + uint32_t i; + + if (gensec_ntlmssp_state->expected_state == NTLMSSP_DONE) { + /* We are strict here because other modules, which we + * don't fully control (such as GSSAPI) are also + * strict, but are tested less often */ + + DEBUG(1, ("Called NTLMSSP after state machine was 'done'\n")); + return NT_STATUS_INVALID_PARAMETER; + } + + if (!input.length) { + switch (gensec_ntlmssp_state->role) { + case NTLMSSP_CLIENT: + ntlmssp_command = NTLMSSP_INITIAL; + break; + case NTLMSSP_SERVER: + if (gensec_security->want_features & GENSEC_FEATURE_DATAGRAM_MODE) { + /* 'datagram' mode - no neg packet */ + ntlmssp_command = NTLMSSP_NEGOTIATE; + } else { + /* This is normal in SPNEGO mech negotiation fallback */ + DEBUG(2, ("Failed to parse NTLMSSP packet: zero length\n")); + return NT_STATUS_INVALID_PARAMETER; + } + break; + } + } else { + if (!msrpc_parse(gensec_ntlmssp_state, + lp_iconv_convenience(gensec_security->lp_ctx), + &input, "Cd", + "NTLMSSP", + &ntlmssp_command)) { + DEBUG(1, ("Failed to parse NTLMSSP packet, could not extract NTLMSSP command\n")); + dump_data(2, input.data, input.length); + return NT_STATUS_INVALID_PARAMETER; + } + } + + if (ntlmssp_command != gensec_ntlmssp_state->expected_state) { + DEBUG(2, ("got NTLMSSP command %u, expected %u\n", ntlmssp_command, gensec_ntlmssp_state->expected_state)); + return NT_STATUS_INVALID_PARAMETER; + } + + for (i=0; i < ARRAY_SIZE(ntlmssp_callbacks); i++) { + if (ntlmssp_callbacks[i].role == gensec_ntlmssp_state->role && + ntlmssp_callbacks[i].command == ntlmssp_command) { + *idx = i; + return NT_STATUS_OK; + } + } + + DEBUG(1, ("failed to find NTLMSSP callback for NTLMSSP mode %u, command %u\n", + gensec_ntlmssp_state->role, ntlmssp_command)); + + return NT_STATUS_INVALID_PARAMETER; +} + +/** + * Next state function for the wrapped NTLMSSP state machine + * + * @param gensec_security GENSEC state, initialised to NTLMSSP + * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on + * @param in The request, as a DATA_BLOB + * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx + * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, + * or NT_STATUS_OK if the user is authenticated. + */ + +static NTSTATUS gensec_ntlmssp_update(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB input, DATA_BLOB *out) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + NTSTATUS status; + uint32_t i; + + *out = data_blob(NULL, 0); + + if (!out_mem_ctx) { + /* if the caller doesn't want to manage/own the memory, + we can put it on our context */ + out_mem_ctx = gensec_ntlmssp_state; + } + + status = gensec_ntlmssp_update_find(gensec_ntlmssp_state, input, &i); + NT_STATUS_NOT_OK_RETURN(status); + + status = ntlmssp_callbacks[i].sync_fn(gensec_security, out_mem_ctx, input, out); + NT_STATUS_NOT_OK_RETURN(status); + + return NT_STATUS_OK; +} + +/** + * Return the NTLMSSP master session key + * + * @param gensec_ntlmssp_state NTLMSSP State + */ + +NTSTATUS gensec_ntlmssp_session_key(struct gensec_security *gensec_security, + DATA_BLOB *session_key) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + + if (!gensec_ntlmssp_state->session_key.data) { + return NT_STATUS_NO_USER_SESSION_KEY; + } + *session_key = gensec_ntlmssp_state->session_key; + + return NT_STATUS_OK; +} + +void ntlmssp_handle_neg_flags(struct gensec_ntlmssp_state *gensec_ntlmssp_state, + uint32_t neg_flags, bool allow_lm) +{ + if (neg_flags & NTLMSSP_NEGOTIATE_UNICODE) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_UNICODE; + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_OEM; + gensec_ntlmssp_state->unicode = true; + } else { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_UNICODE; + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_OEM; + gensec_ntlmssp_state->unicode = false; + } + + if ((neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) && allow_lm && !gensec_ntlmssp_state->use_ntlmv2) { + /* other end forcing us to use LM */ + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_LM_KEY; + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2; + } else { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY; + } + + if (!(neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_ALWAYS_SIGN; + } + + if (!(neg_flags & NTLMSSP_NEGOTIATE_SIGN)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SIGN; + } + + if (!(neg_flags & NTLMSSP_NEGOTIATE_SEAL)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_SEAL; + } + + if (!(neg_flags & NTLMSSP_NEGOTIATE_NTLM2)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2; + } + + if (!(neg_flags & NTLMSSP_NEGOTIATE_128)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_128; + } + + if (!(neg_flags & NTLMSSP_NEGOTIATE_56)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_56; + } + + if (!(neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_KEY_EXCH; + } + + /* Woop Woop - unknown flag for Windows compatibility... + What does this really do ? JRA. */ + if (!(neg_flags & NTLMSSP_UNKNOWN_02000000)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_UNKNOWN_02000000; + } + + if ((neg_flags & NTLMSSP_REQUEST_TARGET)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_REQUEST_TARGET; + } + +} + +/** + Weaken NTLMSSP keys to cope with down-level clients and servers. + + We probably should have some parameters to control this, but as + it only occours for LM_KEY connections, and this is controlled + by the client lanman auth/lanman auth parameters, it isn't too bad. +*/ + +DATA_BLOB ntlmssp_weakend_key(struct gensec_ntlmssp_state *gensec_ntlmssp_state, + TALLOC_CTX *mem_ctx) +{ + DATA_BLOB weakened_key = data_blob_talloc(mem_ctx, + gensec_ntlmssp_state->session_key.data, + gensec_ntlmssp_state->session_key.length); + /* Nothing to weaken. We certainly don't want to 'extend' the length... */ + if (weakened_key.length < 16) { + /* perhaps there was no key? */ + return weakened_key; + } + + /* Key weakening not performed on the master key for NTLM2 + and does not occour for NTLM1. Therefore we only need + to do this for the LM_KEY. + */ + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) { + /* LM key doesn't support 128 bit crypto, so this is + * the best we can do. If you negotiate 128 bit, but + * not 56, you end up with 40 bit... */ + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_56) { + weakened_key.data[7] = 0xa0; + weakened_key.length = 8; + } else { /* forty bits */ + weakened_key.data[5] = 0xe5; + weakened_key.data[6] = 0x38; + weakened_key.data[7] = 0xb0; + weakened_key.length = 8; + } + } + return weakened_key; +} + +static bool gensec_ntlmssp_have_feature(struct gensec_security *gensec_security, + uint32_t feature) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + if (feature & GENSEC_FEATURE_SIGN) { + if (!gensec_ntlmssp_state->session_key.length) { + return false; + } + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_SIGN) { + return true; + } + } + if (feature & GENSEC_FEATURE_SEAL) { + if (!gensec_ntlmssp_state->session_key.length) { + return false; + } + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_SEAL) { + return true; + } + } + if (feature & GENSEC_FEATURE_SESSION_KEY) { + if (gensec_ntlmssp_state->session_key.length) { + return true; + } + } + if (feature & GENSEC_FEATURE_DCE_STYLE) { + return true; + } + if (feature & GENSEC_FEATURE_ASYNC_REPLIES) { + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) { + return true; + } + } + return false; +} + +NTSTATUS gensec_ntlmssp_start(struct gensec_security *gensec_security) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state; + + gensec_ntlmssp_state = talloc_zero(gensec_security, struct gensec_ntlmssp_state); + if (!gensec_ntlmssp_state) { + return NT_STATUS_NO_MEMORY; + } + + gensec_ntlmssp_state->gensec_security = gensec_security; + gensec_ntlmssp_state->auth_context = NULL; + gensec_ntlmssp_state->server_info = NULL; + + gensec_security->private_data = gensec_ntlmssp_state; + return NT_STATUS_OK; +} + +static const char *gensec_ntlmssp_oids[] = { + GENSEC_OID_NTLMSSP, + NULL +}; + +static const struct gensec_security_ops gensec_ntlmssp_security_ops = { + .name = "ntlmssp", + .sasl_name = "NTLM", + .auth_type = DCERPC_AUTH_TYPE_NTLMSSP, + .oid = gensec_ntlmssp_oids, + .client_start = gensec_ntlmssp_client_start, + .server_start = gensec_ntlmssp_server_start, + .magic = gensec_ntlmssp_magic, + .update = gensec_ntlmssp_update, + .sig_size = gensec_ntlmssp_sig_size, + .sign_packet = gensec_ntlmssp_sign_packet, + .check_packet = gensec_ntlmssp_check_packet, + .seal_packet = gensec_ntlmssp_seal_packet, + .unseal_packet = gensec_ntlmssp_unseal_packet, + .wrap = gensec_ntlmssp_wrap, + .unwrap = gensec_ntlmssp_unwrap, + .session_key = gensec_ntlmssp_session_key, + .session_info = gensec_ntlmssp_session_info, + .have_feature = gensec_ntlmssp_have_feature, + .enabled = true, + .priority = GENSEC_NTLMSSP +}; + + +_PUBLIC_ NTSTATUS gensec_ntlmssp_init(void) +{ + NTSTATUS ret; + + auth_init(); + + ret = gensec_register(&gensec_ntlmssp_security_ops); + if (!NT_STATUS_IS_OK(ret)) { + DEBUG(0,("Failed to register '%s' gensec backend!\n", + gensec_ntlmssp_security_ops.name)); + return ret; + } + + return ret; +} diff --git a/source4/auth/ntlmssp/ntlmssp.h b/source4/auth/ntlmssp/ntlmssp.h new file mode 100644 index 0000000000..df950e4756 --- /dev/null +++ b/source4/auth/ntlmssp/ntlmssp.h @@ -0,0 +1,190 @@ +/* + Unix SMB/CIFS implementation. + SMB parameters and setup + Copyright (C) Andrew Tridgell 1992-1997 + Copyright (C) Luke Kenneth Casson Leighton 1996-1997 + Copyright (C) Paul Ashton 1997 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "librpc/gen_ndr/samr.h" + +/* NTLMSSP mode */ +enum ntlmssp_role +{ + NTLMSSP_SERVER, + NTLMSSP_CLIENT +}; + +/* NTLMSSP message types */ +enum ntlmssp_message_type +{ + NTLMSSP_INITIAL = 0 /* samba internal state */, + NTLMSSP_NEGOTIATE = 1, + NTLMSSP_CHALLENGE = 2, + NTLMSSP_AUTH = 3, + NTLMSSP_UNKNOWN = 4, + NTLMSSP_DONE = 5 /* samba final state */ +}; + +/* NTLMSSP negotiation flags */ +#define NTLMSSP_NEGOTIATE_UNICODE 0x00000001 +#define NTLMSSP_NEGOTIATE_OEM 0x00000002 +#define NTLMSSP_REQUEST_TARGET 0x00000004 +#define NTLMSSP_NEGOTIATE_SIGN 0x00000010 /* Message integrity */ +#define NTLMSSP_NEGOTIATE_SEAL 0x00000020 /* Message confidentiality */ +#define NTLMSSP_NEGOTIATE_DATAGRAM_STYLE 0x00000040 +#define NTLMSSP_NEGOTIATE_LM_KEY 0x00000080 +#define NTLMSSP_NEGOTIATE_NETWARE 0x00000100 +#define NTLMSSP_NEGOTIATE_NTLM 0x00000200 +#define NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED 0x00001000 +#define NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED 0x00002000 +#define NTLMSSP_NEGOTIATE_THIS_IS_LOCAL_CALL 0x00004000 +#define NTLMSSP_NEGOTIATE_ALWAYS_SIGN 0x00008000 +#define NTLMSSP_TARGET_TYPE_DOMAIN 0x10000 +#define NTLMSSP_TARGET_TYPE_SERVER 0x20000 +#define NTLMSSP_CHAL_INIT_RESPONSE 0x00010000 + +#define NTLMSSP_CHAL_ACCEPT_RESPONSE 0x00020000 +#define NTLMSSP_CHAL_NON_NT_SESSION_KEY 0x00040000 +#define NTLMSSP_NEGOTIATE_NTLM2 0x00080000 +#define NTLMSSP_CHAL_TARGET_INFO 0x00800000 +#define NTLMSSP_UNKNOWN_02000000 0x02000000 +#define NTLMSSP_NEGOTIATE_128 0x20000000 /* 128-bit encryption */ +#define NTLMSSP_NEGOTIATE_KEY_EXCH 0x40000000 +#define NTLMSSP_NEGOTIATE_56 0x80000000 + +#define NTLMSSP_NAME_TYPE_SERVER 0x01 +#define NTLMSSP_NAME_TYPE_DOMAIN 0x02 +#define NTLMSSP_NAME_TYPE_SERVER_DNS 0x03 +#define NTLMSSP_NAME_TYPE_DOMAIN_DNS 0x04 + +#define NTLMSSP_SIGN_VERSION 1 + +#define NTLMSSP_SIG_SIZE 16 + +struct gensec_ntlmssp_state +{ + struct gensec_security *gensec_security; + + enum ntlmssp_role role; + enum samr_Role server_role; + uint32_t expected_state; + + bool unicode; + bool use_ntlmv2; + bool use_nt_response; /* Set to 'False' to debug what happens when the NT response is omited */ + bool allow_lm_key; /* The LM_KEY code is not functional at this point, and it's not + very secure anyway */ + + bool server_multiple_authentications; /* Set to 'True' to allow squid 2.5 + style 'challenge caching' */ + + char *user; + const char *domain; + const char *workstation; + char *server_domain; + + DATA_BLOB internal_chal; /* Random challenge as supplied to the client for NTLM authentication */ + + DATA_BLOB chal; /* Random challenge as input into the actual NTLM (or NTLM2) authentication */ + DATA_BLOB lm_resp; + DATA_BLOB nt_resp; + DATA_BLOB session_key; + + uint32_t neg_flags; /* the current state of negotiation with the NTLMSSP partner */ + + /* internal variables used by KEY_EXCH (client-supplied user session key */ + DATA_BLOB encrypted_session_key; + + /** + * Callback to get the 'challenge' used for NTLM authentication. + * + * @param ntlmssp_state This structure + * @return 8 bytes of challenge data, determined by the server to be the challenge for NTLM authentication + * + */ + const uint8_t *(*get_challenge)(const struct gensec_ntlmssp_state *); + + /** + * Callback to find if the challenge used by NTLM authentication may be modified + * + * The NTLM2 authentication scheme modifies the effective challenge, but this is not compatiable with the + * current 'security=server' implementation.. + * + * @param ntlmssp_state This structure + * @return Can the challenge be set to arbitary values? + * + */ + bool (*may_set_challenge)(const struct gensec_ntlmssp_state *); + + /** + * Callback to set the 'challenge' used for NTLM authentication. + * + * The callback may use the void *auth_context to store state information, but the same value is always available + * from the DATA_BLOB chal on this structure. + * + * @param ntlmssp_state This structure + * @param challenge 8 bytes of data, agreed by the client and server to be the effective challenge for NTLM2 authentication + * + */ + NTSTATUS (*set_challenge)(struct gensec_ntlmssp_state *, DATA_BLOB *challenge); + + /** + * Callback to check the user's password. + * + * The callback must reads the feilds of this structure for the information it needs on the user + * @param ntlmssp_state This structure + * @param nt_session_key If an NT session key is returned by the authentication process, return it here + * @param lm_session_key If an LM session key is returned by the authentication process, return it here + * + */ + NTSTATUS (*check_password)(struct gensec_ntlmssp_state *, + TALLOC_CTX *mem_ctx, + DATA_BLOB *nt_session_key, DATA_BLOB *lm_session_key); + + const char *server_name; + + bool doing_ntlm2; + + union { + /* NTLM */ + struct { + uint32_t seq_num; + struct arcfour_state *arcfour_state; + } ntlm; + + /* NTLM2 */ + struct { + uint32_t send_seq_num; + uint32_t recv_seq_num; + DATA_BLOB send_sign_key; + DATA_BLOB recv_sign_key; + struct arcfour_state *send_seal_arcfour_state; + struct arcfour_state *recv_seal_arcfour_state; + + /* internal variables used by NTLM2 */ + uint8_t session_nonce[16]; + } ntlm2; + } crypt; + + struct auth_context *auth_context; + struct auth_serversupplied_info *server_info; +}; + +struct loadparm_context; +struct auth_session_info; + +#include "auth/ntlmssp/proto.h" diff --git a/source4/auth/ntlmssp/ntlmssp_client.c b/source4/auth/ntlmssp/ntlmssp_client.c new file mode 100644 index 0000000000..891761860c --- /dev/null +++ b/source4/auth/ntlmssp/ntlmssp_client.c @@ -0,0 +1,383 @@ +/* + Unix SMB/Netbios implementation. + Version 3.0 + handle NLTMSSP, client server side parsing + + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2005 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/ntlmssp/ntlmssp.h" +#include "auth/ntlmssp/msrpc_parse.h" +#include "lib/crypto/crypto.h" +#include "libcli/auth/libcli_auth.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "param/param.h" + +/********************************************************************* + Client side NTLMSSP +*********************************************************************/ + +/** + * Next state function for the Initial packet + * + * @param ntlmssp_state NTLMSSP State + * @param out_mem_ctx The DATA_BLOB *out will be allocated on this context + * @param in A NULL data blob (input ignored) + * @param out The initial negotiate request to the server, as an talloc()ed DATA_BLOB, on out_mem_ctx + * @return Errors or NT_STATUS_OK. + */ + +NTSTATUS ntlmssp_client_initial(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + DATA_BLOB in, DATA_BLOB *out) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + const char *domain = gensec_ntlmssp_state->domain; + const char *workstation = cli_credentials_get_workstation(gensec_security->credentials); + + /* These don't really matter in the initial packet, so don't panic if they are not set */ + if (!domain) { + domain = ""; + } + + if (!workstation) { + workstation = ""; + } + + if (gensec_ntlmssp_state->unicode) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_UNICODE; + } else { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_OEM; + } + + if (gensec_ntlmssp_state->use_ntlmv2) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_NTLM2; + } + + /* generate the ntlmssp negotiate packet */ + msrpc_gen(out_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + out, "CddAA", + "NTLMSSP", + NTLMSSP_NEGOTIATE, + gensec_ntlmssp_state->neg_flags, + domain, + workstation); + + gensec_ntlmssp_state->expected_state = NTLMSSP_CHALLENGE; + + return NT_STATUS_MORE_PROCESSING_REQUIRED; +} + +/** + * Next state function for the Challenge Packet. Generate an auth packet. + * + * @param gensec_security GENSEC state + * @param out_mem_ctx Memory context for *out + * @param in The server challnege, as a DATA_BLOB. reply.data must be NULL + * @param out The next request (auth packet) to the server, as an allocated DATA_BLOB, on the out_mem_ctx context + * @return Errors or NT_STATUS_OK. + */ + +NTSTATUS ntlmssp_client_challenge(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + uint32_t chal_flags, ntlmssp_command, unkn1, unkn2; + DATA_BLOB server_domain_blob; + DATA_BLOB challenge_blob; + DATA_BLOB target_info = data_blob(NULL, 0); + char *server_domain; + const char *chal_parse_string; + const char *auth_gen_string; + DATA_BLOB lm_response = data_blob(NULL, 0); + DATA_BLOB nt_response = data_blob(NULL, 0); + DATA_BLOB session_key = data_blob(NULL, 0); + DATA_BLOB lm_session_key = data_blob(NULL, 0); + DATA_BLOB encrypted_session_key = data_blob(NULL, 0); + NTSTATUS nt_status; + int flags = 0; + const char *user, *domain; + + TALLOC_CTX *mem_ctx = talloc_new(out_mem_ctx); + if (!mem_ctx) { + return NT_STATUS_NO_MEMORY; + } + + if (!msrpc_parse(mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + &in, "CdBd", + "NTLMSSP", + &ntlmssp_command, + &server_domain_blob, + &chal_flags)) { + DEBUG(1, ("Failed to parse the NTLMSSP Challenge: (#1)\n")); + dump_data(2, in.data, in.length); + talloc_free(mem_ctx); + + return NT_STATUS_INVALID_PARAMETER; + } + + data_blob_free(&server_domain_blob); + + DEBUG(3, ("Got challenge flags:\n")); + debug_ntlmssp_flags(chal_flags); + + ntlmssp_handle_neg_flags(gensec_ntlmssp_state, chal_flags, gensec_ntlmssp_state->allow_lm_key); + + if (gensec_ntlmssp_state->unicode) { + if (chal_flags & NTLMSSP_CHAL_TARGET_INFO) { + chal_parse_string = "CdUdbddB"; + } else { + chal_parse_string = "CdUdbdd"; + } + auth_gen_string = "CdBBUUUBd"; + } else { + if (chal_flags & NTLMSSP_CHAL_TARGET_INFO) { + chal_parse_string = "CdAdbddB"; + } else { + chal_parse_string = "CdAdbdd"; + } + + auth_gen_string = "CdBBAAABd"; + } + + if (!msrpc_parse(mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + &in, chal_parse_string, + "NTLMSSP", + &ntlmssp_command, + &server_domain, + &chal_flags, + &challenge_blob, 8, + &unkn1, &unkn2, + &target_info)) { + DEBUG(1, ("Failed to parse the NTLMSSP Challenge: (#2)\n")); + dump_data(2, in.data, in.length); + talloc_free(mem_ctx); + return NT_STATUS_INVALID_PARAMETER; + } + + gensec_ntlmssp_state->server_domain = server_domain; + + if (challenge_blob.length != 8) { + talloc_free(mem_ctx); + return NT_STATUS_INVALID_PARAMETER; + } + + cli_credentials_get_ntlm_username_domain(gensec_security->credentials, mem_ctx, + &user, &domain); + + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) { + flags |= CLI_CRED_NTLM2; + } + if (gensec_ntlmssp_state->use_ntlmv2) { + flags |= CLI_CRED_NTLMv2_AUTH; + } + if (gensec_ntlmssp_state->use_nt_response) { + flags |= CLI_CRED_NTLM_AUTH; + } + if (lp_client_lanman_auth(gensec_security->lp_ctx)) { + flags |= CLI_CRED_LANMAN_AUTH; + } + + nt_status = cli_credentials_get_ntlm_response(gensec_security->credentials, mem_ctx, + &flags, challenge_blob, target_info, + &lm_response, &nt_response, + &lm_session_key, &session_key); + + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + if (!(flags & CLI_CRED_LANMAN_AUTH)) { + /* LM Key is still possible, just silly. Fortunetly + * we require command line options to end up here */ + /* gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY; */ + } + + if (!(flags & CLI_CRED_NTLM2)) { + /* NTLM2 is incompatible... */ + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2; + } + + if ((gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) + && lp_client_lanman_auth(gensec_security->lp_ctx) && lm_session_key.length == 16) { + DATA_BLOB new_session_key = data_blob_talloc(mem_ctx, NULL, 16); + if (lm_response.length == 24) { + SMBsesskeygen_lm_sess_key(lm_session_key.data, lm_response.data, + new_session_key.data); + } else { + static const uint8_t zeros[24]; + SMBsesskeygen_lm_sess_key(lm_session_key.data, zeros, + new_session_key.data); + } + session_key = new_session_key; + dump_data_pw("LM session key\n", session_key.data, session_key.length); + } + + + /* Key exchange encryptes a new client-generated session key with + the password-derived key */ + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) { + /* Make up a new session key */ + uint8_t client_session_key[16]; + generate_secret_buffer(client_session_key, sizeof(client_session_key)); + + /* Encrypt the new session key with the old one */ + encrypted_session_key = data_blob_talloc(gensec_ntlmssp_state, + client_session_key, sizeof(client_session_key)); + dump_data_pw("KEY_EXCH session key:\n", encrypted_session_key.data, encrypted_session_key.length); + arcfour_crypt(encrypted_session_key.data, session_key.data, encrypted_session_key.length); + dump_data_pw("KEY_EXCH session key (enc):\n", encrypted_session_key.data, encrypted_session_key.length); + + /* Mark the new session key as the 'real' session key */ + session_key = data_blob_talloc(mem_ctx, client_session_key, sizeof(client_session_key)); + } + + DEBUG(3, ("NTLMSSP: Set final flags:\n")); + debug_ntlmssp_flags(gensec_ntlmssp_state->neg_flags); + + /* this generates the actual auth packet */ + if (!msrpc_gen(mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + out, auth_gen_string, + "NTLMSSP", + NTLMSSP_AUTH, + lm_response.data, lm_response.length, + nt_response.data, nt_response.length, + domain, + user, + cli_credentials_get_workstation(gensec_security->credentials), + encrypted_session_key.data, encrypted_session_key.length, + gensec_ntlmssp_state->neg_flags)) { + talloc_free(mem_ctx); + return NT_STATUS_NO_MEMORY; + } + + gensec_ntlmssp_state->session_key = session_key; + talloc_steal(gensec_ntlmssp_state, session_key.data); + + talloc_steal(out_mem_ctx, out->data); + + gensec_ntlmssp_state->chal = challenge_blob; + gensec_ntlmssp_state->lm_resp = lm_response; + talloc_steal(gensec_ntlmssp_state->lm_resp.data, lm_response.data); + gensec_ntlmssp_state->nt_resp = nt_response; + talloc_steal(gensec_ntlmssp_state->nt_resp.data, nt_response.data); + + gensec_ntlmssp_state->expected_state = NTLMSSP_DONE; + + if (gensec_security->want_features & (GENSEC_FEATURE_SIGN|GENSEC_FEATURE_SEAL)) { + nt_status = ntlmssp_sign_init(gensec_ntlmssp_state); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(1, ("Could not setup NTLMSSP signing/sealing system (error was: %s)\n", + nt_errstr(nt_status))); + talloc_free(mem_ctx); + return nt_status; + } + } + + talloc_free(mem_ctx); + return NT_STATUS_OK; +} + +NTSTATUS gensec_ntlmssp_client_start(struct gensec_security *gensec_security) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state; + NTSTATUS nt_status; + + nt_status = gensec_ntlmssp_start(gensec_security); + NT_STATUS_NOT_OK_RETURN(nt_status); + + gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + + gensec_ntlmssp_state->role = NTLMSSP_CLIENT; + + gensec_ntlmssp_state->domain = lp_workgroup(gensec_security->lp_ctx); + + gensec_ntlmssp_state->unicode = lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "unicode", true); + + gensec_ntlmssp_state->use_nt_response = lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "send_nt_reponse", true); + + gensec_ntlmssp_state->allow_lm_key = (lp_client_lanman_auth(gensec_security->lp_ctx) + && (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "allow_lm_key", false) + || lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "lm_key", false))); + + gensec_ntlmssp_state->use_ntlmv2 = lp_client_ntlmv2_auth(gensec_security->lp_ctx); + + gensec_ntlmssp_state->expected_state = NTLMSSP_INITIAL; + + gensec_ntlmssp_state->neg_flags = + NTLMSSP_NEGOTIATE_NTLM | + NTLMSSP_REQUEST_TARGET; + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "128bit", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_128; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "56bit", false)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_56; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "lm_key", false)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_LM_KEY; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "keyexchange", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_KEY_EXCH; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "alwayssign", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_client", "ntlm2", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_NTLM2; + } else { + /* apparently we can't do ntlmv2 if we don't do ntlm2 */ + gensec_ntlmssp_state->use_ntlmv2 = false; + } + + if (gensec_security->want_features & GENSEC_FEATURE_SESSION_KEY) { + /* + * We need to set this to allow a later SetPassword + * via the SAMR pipe to succeed. Strange.... We could + * also add NTLMSSP_NEGOTIATE_SEAL here. JRA. + * + * Without this, Windows will not create the master key + * that it thinks is only used for NTLMSSP signing and + * sealing. (It is actually pulled out and used directly) + */ + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN; + } + if (gensec_security->want_features & GENSEC_FEATURE_SIGN) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN; + } + if (gensec_security->want_features & GENSEC_FEATURE_SEAL) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SEAL; + } + + gensec_security->private_data = gensec_ntlmssp_state; + + return NT_STATUS_OK; +} + diff --git a/source4/auth/ntlmssp/ntlmssp_parse.c b/source4/auth/ntlmssp/ntlmssp_parse.c new file mode 100644 index 0000000000..e1c1e7cbb3 --- /dev/null +++ b/source4/auth/ntlmssp/ntlmssp_parse.c @@ -0,0 +1,367 @@ +/* + Unix SMB/CIFS implementation. + simple kerberos5/SPNEGO routines + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2002 + Copyright (C) Andrew Bartlett 2002-2003 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "pstring.h" +#include "param/param.h" + +/* + this is a tiny msrpc packet generator. I am only using this to + avoid tying this code to a particular varient of our rpc code. This + generator is not general enough for all our rpc needs, its just + enough for the spnego/ntlmssp code + + format specifiers are: + + U = unicode string (input is unix string) + a = address (input is char *unix_string) + (1 byte type, 1 byte length, unicode/ASCII string, all inline) + A = ASCII string (input is unix string) + B = data blob (pointer + length) + b = data blob in header (pointer + length) + D + d = word (4 bytes) + C = constant ascii string + */ +bool msrpc_gen(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + DATA_BLOB *blob, + const char *format, ...) +{ + int i; + ssize_t n; + va_list ap; + char *s; + uint8_t *b; + int head_size=0, data_size=0; + int head_ofs, data_ofs; + int *intargs; + + DATA_BLOB *pointers; + + pointers = talloc_array(mem_ctx, DATA_BLOB, strlen(format)); + intargs = talloc_array(pointers, int, strlen(format)); + + /* first scan the format to work out the header and body size */ + va_start(ap, format); + for (i=0; format[i]; i++) { + switch (format[i]) { + case 'U': + s = va_arg(ap, char *); + head_size += 8; + n = push_ucs2_talloc(pointers, iconv_convenience, (void **)&pointers[i].data, s); + if (n == -1) { + return false; + } + pointers[i].length = n; + pointers[i].length -= 2; + data_size += pointers[i].length; + break; + case 'A': + s = va_arg(ap, char *); + head_size += 8; + n = push_ascii_talloc(pointers, iconv_convenience, (char **)&pointers[i].data, s); + if (n == -1) { + return false; + } + pointers[i].length = n; + pointers[i].length -= 1; + data_size += pointers[i].length; + break; + case 'a': + n = va_arg(ap, int); + intargs[i] = n; + s = va_arg(ap, char *); + n = push_ucs2_talloc(pointers, iconv_convenience, (void **)&pointers[i].data, s); + if (n == -1) { + return false; + } + pointers[i].length = n; + pointers[i].length -= 2; + data_size += pointers[i].length + 4; + break; + case 'B': + b = va_arg(ap, uint8_t *); + head_size += 8; + pointers[i].data = b; + pointers[i].length = va_arg(ap, int); + data_size += pointers[i].length; + break; + case 'b': + b = va_arg(ap, uint8_t *); + pointers[i].data = b; + pointers[i].length = va_arg(ap, int); + head_size += pointers[i].length; + break; + case 'd': + n = va_arg(ap, int); + intargs[i] = n; + head_size += 4; + break; + case 'C': + s = va_arg(ap, char *); + pointers[i].data = (uint8_t *)s; + pointers[i].length = strlen(s)+1; + head_size += pointers[i].length; + break; + } + } + va_end(ap); + + /* allocate the space, then scan the format again to fill in the values */ + *blob = data_blob_talloc(mem_ctx, NULL, head_size + data_size); + + head_ofs = 0; + data_ofs = head_size; + + va_start(ap, format); + for (i=0; format[i]; i++) { + switch (format[i]) { + case 'U': + case 'A': + case 'B': + n = pointers[i].length; + SSVAL(blob->data, head_ofs, n); head_ofs += 2; + SSVAL(blob->data, head_ofs, n); head_ofs += 2; + SIVAL(blob->data, head_ofs, data_ofs); head_ofs += 4; + if (pointers[i].data && n) /* don't follow null pointers... */ + memcpy(blob->data+data_ofs, pointers[i].data, n); + data_ofs += n; + break; + case 'a': + n = intargs[i]; + SSVAL(blob->data, data_ofs, n); data_ofs += 2; + + n = pointers[i].length; + SSVAL(blob->data, data_ofs, n); data_ofs += 2; + if (n >= 0) { + memcpy(blob->data+data_ofs, pointers[i].data, n); + } + data_ofs += n; + break; + case 'd': + n = intargs[i]; + SIVAL(blob->data, head_ofs, n); + head_ofs += 4; + break; + case 'b': + n = pointers[i].length; + memcpy(blob->data + head_ofs, pointers[i].data, n); + head_ofs += n; + break; + case 'C': + n = pointers[i].length; + memcpy(blob->data + head_ofs, pointers[i].data, n); + head_ofs += n; + break; + } + } + va_end(ap); + + talloc_free(pointers); + + return true; +} + + +/* a helpful macro to avoid running over the end of our blob */ +#define NEED_DATA(amount) \ +if ((head_ofs + amount) > blob->length) { \ + return false; \ +} + +/* + this is a tiny msrpc packet parser. This the the partner of msrpc_gen + + format specifiers are: + + U = unicode string (output is unix string) + A = ascii string + B = data blob + b = data blob in header + d = word (4 bytes) + C = constant ascii string + */ + +bool msrpc_parse(TALLOC_CTX *mem_ctx, + struct smb_iconv_convenience *iconv_convenience, + const DATA_BLOB *blob, + const char *format, ...) +{ + int i; + va_list ap; + const char **ps, *s; + DATA_BLOB *b; + size_t head_ofs = 0; + uint16_t len1, len2; + uint32_t ptr; + uint32_t *v; + size_t p_len = 1024; + char *p = talloc_array(mem_ctx, char, p_len); + bool ret = true; + + va_start(ap, format); + for (i=0; format[i]; i++) { + switch (format[i]) { + case 'U': + NEED_DATA(8); + len1 = SVAL(blob->data, head_ofs); head_ofs += 2; + len2 = SVAL(blob->data, head_ofs); head_ofs += 2; + ptr = IVAL(blob->data, head_ofs); head_ofs += 4; + + ps = (const char **)va_arg(ap, char **); + if (len1 == 0 && len2 == 0) { + *ps = ""; + } else { + /* make sure its in the right format - be strict */ + if ((len1 != len2) || (ptr + len1 < ptr) || (ptr + len1 < len1) || (ptr + len1 > blob->length)) { + ret = false; + goto cleanup; + } + if (len1 & 1) { + /* if odd length and unicode */ + ret = false; + goto cleanup; + } + if (blob->data + ptr < (uint8_t *)(uintptr_t)ptr || + blob->data + ptr < blob->data) { + ret = false; + goto cleanup; + } + + if (0 < len1) { + pull_string(iconv_convenience, p, blob->data + ptr, p_len, + len1, STR_UNICODE|STR_NOALIGN); + (*ps) = talloc_strdup(mem_ctx, p); + if (!(*ps)) { + ret = false; + goto cleanup; + } + } else { + (*ps) = ""; + } + } + break; + case 'A': + NEED_DATA(8); + len1 = SVAL(blob->data, head_ofs); head_ofs += 2; + len2 = SVAL(blob->data, head_ofs); head_ofs += 2; + ptr = IVAL(blob->data, head_ofs); head_ofs += 4; + + ps = (const char **)va_arg(ap, char **); + /* make sure its in the right format - be strict */ + if (len1 == 0 && len2 == 0) { + *ps = ""; + } else { + if ((len1 != len2) || (ptr + len1 < ptr) || (ptr + len1 < len1) || (ptr + len1 > blob->length)) { + ret = false; + goto cleanup; + } + + if (blob->data + ptr < (uint8_t *)(uintptr_t)ptr || + blob->data + ptr < blob->data) { + ret = false; + goto cleanup; + } + + if (0 < len1) { + pull_string(iconv_convenience, p, blob->data + ptr, p_len, + len1, STR_ASCII|STR_NOALIGN); + (*ps) = talloc_strdup(mem_ctx, p); + if (!(*ps)) { + ret = false; + goto cleanup; + } + } else { + (*ps) = ""; + } + } + break; + case 'B': + NEED_DATA(8); + len1 = SVAL(blob->data, head_ofs); head_ofs += 2; + len2 = SVAL(blob->data, head_ofs); head_ofs += 2; + ptr = IVAL(blob->data, head_ofs); head_ofs += 4; + + b = (DATA_BLOB *)va_arg(ap, void *); + if (len1 == 0 && len2 == 0) { + *b = data_blob_talloc(mem_ctx, NULL, 0); + } else { + /* make sure its in the right format - be strict */ + if ((len1 != len2) || (ptr + len1 < ptr) || (ptr + len1 < len1) || (ptr + len1 > blob->length)) { + ret = false; + goto cleanup; + } + + if (blob->data + ptr < (uint8_t *)(uintptr_t)ptr || + blob->data + ptr < blob->data) { + ret = false; + goto cleanup; + } + + *b = data_blob_talloc(mem_ctx, blob->data + ptr, len1); + } + break; + case 'b': + b = (DATA_BLOB *)va_arg(ap, void *); + len1 = va_arg(ap, uint_t); + /* make sure its in the right format - be strict */ + NEED_DATA(len1); + if (blob->data + head_ofs < (uint8_t *)head_ofs || + blob->data + head_ofs < blob->data) { + ret = false; + goto cleanup; + } + + *b = data_blob_talloc(mem_ctx, blob->data + head_ofs, len1); + head_ofs += len1; + break; + case 'd': + v = va_arg(ap, uint32_t *); + NEED_DATA(4); + *v = IVAL(blob->data, head_ofs); head_ofs += 4; + break; + case 'C': + s = va_arg(ap, char *); + + if (blob->data + head_ofs < (uint8_t *)head_ofs || + blob->data + head_ofs < blob->data) { + ret = false; + goto cleanup; + } + + head_ofs += pull_string(iconv_convenience, p, + blob->data+head_ofs, p_len, + blob->length - head_ofs, + STR_ASCII|STR_TERMINATE); + if (strcmp(s, p) != 0) { + ret = false; + goto cleanup; + } + break; + } + } + +cleanup: + va_end(ap); + talloc_free(p); + return ret; +} diff --git a/source4/auth/ntlmssp/ntlmssp_server.c b/source4/auth/ntlmssp/ntlmssp_server.c new file mode 100644 index 0000000000..838596ee98 --- /dev/null +++ b/source4/auth/ntlmssp/ntlmssp_server.c @@ -0,0 +1,821 @@ +/* + Unix SMB/Netbios implementation. + Version 3.0 + handle NLTMSSP, client server side parsing + + Copyright (C) Andrew Tridgell 2001 + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2005 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/ntlmssp/ntlmssp.h" +#include "auth/ntlmssp/msrpc_parse.h" +#include "lib/crypto/crypto.h" +#include "system/filesys.h" +#include "libcli/auth/libcli_auth.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "auth/auth.h" +#include "auth/ntlm/auth_proto.h" +#include "param/param.h" +#include "auth/session_proto.h" + +/** + * Set a username on an NTLMSSP context - ensures it is talloc()ed + * + */ + +static NTSTATUS ntlmssp_set_username(struct gensec_ntlmssp_state *gensec_ntlmssp_state, const char *user) +{ + if (!user) { + /* it should be at least "" */ + DEBUG(1, ("NTLMSSP failed to set username - cannot accept NULL username\n")); + return NT_STATUS_INVALID_PARAMETER; + } + gensec_ntlmssp_state->user = talloc_strdup(gensec_ntlmssp_state, user); + if (!gensec_ntlmssp_state->user) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +/** + * Set a domain on an NTLMSSP context - ensures it is talloc()ed + * + */ +static NTSTATUS ntlmssp_set_domain(struct gensec_ntlmssp_state *gensec_ntlmssp_state, const char *domain) +{ + gensec_ntlmssp_state->domain = talloc_strdup(gensec_ntlmssp_state, domain); + if (!gensec_ntlmssp_state->domain) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +/** + * Set a workstation on an NTLMSSP context - ensures it is talloc()ed + * + */ +static NTSTATUS ntlmssp_set_workstation(struct gensec_ntlmssp_state *gensec_ntlmssp_state, const char *workstation) +{ + gensec_ntlmssp_state->workstation = talloc_strdup(gensec_ntlmssp_state, workstation); + if (!gensec_ntlmssp_state->workstation) { + return NT_STATUS_NO_MEMORY; + } + return NT_STATUS_OK; +} + +/** + * Determine correct target name flags for reply, given server role + * and negotiated flags + * + * @param gensec_ntlmssp_state NTLMSSP State + * @param neg_flags The flags from the packet + * @param chal_flags The flags to be set in the reply packet + * @return The 'target name' string. + */ + +static const char *ntlmssp_target_name(struct gensec_ntlmssp_state *gensec_ntlmssp_state, + uint32_t neg_flags, uint32_t *chal_flags) +{ + if (neg_flags & NTLMSSP_REQUEST_TARGET) { + *chal_flags |= NTLMSSP_CHAL_TARGET_INFO; + *chal_flags |= NTLMSSP_REQUEST_TARGET; + if (gensec_ntlmssp_state->server_role == ROLE_STANDALONE) { + *chal_flags |= NTLMSSP_TARGET_TYPE_SERVER; + return gensec_ntlmssp_state->server_name; + } else { + *chal_flags |= NTLMSSP_TARGET_TYPE_DOMAIN; + return gensec_ntlmssp_state->domain; + }; + } else { + return ""; + } +} + + + +/** + * Next state function for the Negotiate packet + * + * @param gensec_security GENSEC state + * @param out_mem_ctx Memory context for *out + * @param in The request, as a DATA_BLOB. reply.data must be NULL + * @param out The reply, as an allocated DATA_BLOB, caller to free. + * @return Errors or MORE_PROCESSING_REQUIRED if (normal) a reply is required. + */ + +NTSTATUS ntlmssp_server_negotiate(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + DATA_BLOB struct_blob; + char dnsname[MAXHOSTNAMELEN], dnsdomname[MAXHOSTNAMELEN]; + const char *p; + uint32_t neg_flags = 0; + uint32_t ntlmssp_command, chal_flags; + const uint8_t *cryptkey; + const char *target_name; + + /* parse the NTLMSSP packet */ +#if 0 + file_save("ntlmssp_negotiate.dat", request.data, request.length); +#endif + + if (in.length) { + if ((in.length < 16) || !msrpc_parse(out_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + &in, "Cdd", + "NTLMSSP", + &ntlmssp_command, + &neg_flags)) { + DEBUG(1, ("ntlmssp_server_negotiate: failed to parse " + "NTLMSSP Negotiate of length %u:\n", + (unsigned int)in.length )); + dump_data(2, in.data, in.length); + return NT_STATUS_INVALID_PARAMETER; + } + debug_ntlmssp_flags(neg_flags); + } + + ntlmssp_handle_neg_flags(gensec_ntlmssp_state, neg_flags, gensec_ntlmssp_state->allow_lm_key); + + /* Ask our caller what challenge they would like in the packet */ + cryptkey = gensec_ntlmssp_state->get_challenge(gensec_ntlmssp_state); + if (!cryptkey) { + DEBUG(1, ("ntlmssp_server_negotiate: backend doesn't give a challenge\n")); + return NT_STATUS_INTERNAL_ERROR; + } + + /* Check if we may set the challenge */ + if (!gensec_ntlmssp_state->may_set_challenge(gensec_ntlmssp_state)) { + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_NTLM2; + } + + /* The flags we send back are not just the negotiated flags, + * they are also 'what is in this packet'. Therfore, we + * operate on 'chal_flags' from here on + */ + + chal_flags = gensec_ntlmssp_state->neg_flags; + + /* get the right name to fill in as 'target' */ + target_name = ntlmssp_target_name(gensec_ntlmssp_state, + neg_flags, &chal_flags); + if (target_name == NULL) + return NT_STATUS_INVALID_PARAMETER; + + gensec_ntlmssp_state->chal = data_blob_talloc(gensec_ntlmssp_state, cryptkey, 8); + gensec_ntlmssp_state->internal_chal = data_blob_talloc(gensec_ntlmssp_state, cryptkey, 8); + + dnsname[0] = '\0'; + if (gethostname(dnsname, sizeof(dnsname)) == -1) { + DEBUG(0,("gethostname failed\n")); + return NT_STATUS_UNSUCCESSFUL; + } + + /* This should be a 'netbios domain -> DNS domain' mapping */ + p = strchr(dnsname, '.'); + if (p != NULL) { + safe_strcpy(dnsdomname, p+1, sizeof(dnsdomname)); + strlower_m(dnsdomname); + } else { + dnsdomname[0] = '\0'; + } + + /* This creates the 'blob' of names that appears at the end of the packet */ + if (chal_flags & NTLMSSP_CHAL_TARGET_INFO) + { + const char *target_name_dns = ""; + if (chal_flags |= NTLMSSP_TARGET_TYPE_DOMAIN) { + target_name_dns = dnsdomname; + } else if (chal_flags |= NTLMSSP_TARGET_TYPE_SERVER) { + target_name_dns = dnsname; + } + + msrpc_gen(out_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + &struct_blob, "aaaaa", + NTLMSSP_NAME_TYPE_DOMAIN, target_name, + NTLMSSP_NAME_TYPE_SERVER, gensec_ntlmssp_state->server_name, + NTLMSSP_NAME_TYPE_DOMAIN_DNS, dnsdomname, + NTLMSSP_NAME_TYPE_SERVER_DNS, dnsname, + 0, ""); + } else { + struct_blob = data_blob(NULL, 0); + } + + { + /* Marshel the packet in the right format, be it unicode or ASCII */ + const char *gen_string; + if (gensec_ntlmssp_state->unicode) { + gen_string = "CdUdbddB"; + } else { + gen_string = "CdAdbddB"; + } + + msrpc_gen(out_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + out, gen_string, + "NTLMSSP", + NTLMSSP_CHALLENGE, + target_name, + chal_flags, + cryptkey, 8, + 0, 0, + struct_blob.data, struct_blob.length); + } + + gensec_ntlmssp_state->expected_state = NTLMSSP_AUTH; + + return NT_STATUS_MORE_PROCESSING_REQUIRED; +} + +/** + * Next state function for the Authenticate packet + * + * @param gensec_ntlmssp_state NTLMSSP State + * @param request The request, as a DATA_BLOB + * @return Errors or NT_STATUS_OK. + */ + +static NTSTATUS ntlmssp_server_preauth(struct gensec_ntlmssp_state *gensec_ntlmssp_state, + const DATA_BLOB request) +{ + uint32_t ntlmssp_command, auth_flags; + NTSTATUS nt_status; + + uint8_t session_nonce_hash[16]; + + const char *parse_string; + char *domain = NULL; + char *user = NULL; + char *workstation = NULL; + +#if 0 + file_save("ntlmssp_auth.dat", request.data, request.length); +#endif + + if (gensec_ntlmssp_state->unicode) { + parse_string = "CdBBUUUBd"; + } else { + parse_string = "CdBBAAABd"; + } + + /* zero these out */ + data_blob_free(&gensec_ntlmssp_state->lm_resp); + data_blob_free(&gensec_ntlmssp_state->nt_resp); + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + + gensec_ntlmssp_state->user = NULL; + gensec_ntlmssp_state->domain = NULL; + gensec_ntlmssp_state->workstation = NULL; + + /* now the NTLMSSP encoded auth hashes */ + if (!msrpc_parse(gensec_ntlmssp_state, + lp_iconv_convenience(gensec_ntlmssp_state->gensec_security->lp_ctx), + &request, parse_string, + "NTLMSSP", + &ntlmssp_command, + &gensec_ntlmssp_state->lm_resp, + &gensec_ntlmssp_state->nt_resp, + &domain, + &user, + &workstation, + &gensec_ntlmssp_state->encrypted_session_key, + &auth_flags)) { + DEBUG(10, ("ntlmssp_server_auth: failed to parse NTLMSSP (nonfatal):\n")); + dump_data(10, request.data, request.length); + + /* zero this out */ + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + auth_flags = 0; + + /* Try again with a shorter string (Win9X truncates this packet) */ + if (gensec_ntlmssp_state->unicode) { + parse_string = "CdBBUUU"; + } else { + parse_string = "CdBBAAA"; + } + + /* now the NTLMSSP encoded auth hashes */ + if (!msrpc_parse(gensec_ntlmssp_state, + lp_iconv_convenience(gensec_ntlmssp_state->gensec_security->lp_ctx), + &request, parse_string, + "NTLMSSP", + &ntlmssp_command, + &gensec_ntlmssp_state->lm_resp, + &gensec_ntlmssp_state->nt_resp, + &domain, + &user, + &workstation)) { + DEBUG(1, ("ntlmssp_server_auth: failed to parse NTLMSSP:\n")); + dump_data(2, request.data, request.length); + + return NT_STATUS_INVALID_PARAMETER; + } + } + + if (auth_flags) + ntlmssp_handle_neg_flags(gensec_ntlmssp_state, auth_flags, gensec_ntlmssp_state->allow_lm_key); + + if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_domain(gensec_ntlmssp_state, domain))) { + /* zero this out */ + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + return nt_status; + } + + if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_username(gensec_ntlmssp_state, user))) { + /* zero this out */ + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + return nt_status; + } + + if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_workstation(gensec_ntlmssp_state, workstation))) { + /* zero this out */ + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + return nt_status; + } + + DEBUG(3,("Got user=[%s] domain=[%s] workstation=[%s] len1=%lu len2=%lu\n", + gensec_ntlmssp_state->user, gensec_ntlmssp_state->domain, gensec_ntlmssp_state->workstation, (unsigned long)gensec_ntlmssp_state->lm_resp.length, (unsigned long)gensec_ntlmssp_state->nt_resp.length)); + +#if 0 + file_save("nthash1.dat", &gensec_ntlmssp_state->nt_resp.data, &gensec_ntlmssp_state->nt_resp.length); + file_save("lmhash1.dat", &gensec_ntlmssp_state->lm_resp.data, &gensec_ntlmssp_state->lm_resp.length); +#endif + + /* NTLM2 uses a 'challenge' that is made of up both the server challenge, and a + client challenge + + However, the NTLM2 flag may still be set for the real NTLMv2 logins, be careful. + */ + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) { + if (gensec_ntlmssp_state->nt_resp.length == 24 && gensec_ntlmssp_state->lm_resp.length == 24) { + struct MD5Context md5_session_nonce_ctx; + SMB_ASSERT(gensec_ntlmssp_state->internal_chal.data + && gensec_ntlmssp_state->internal_chal.length == 8); + + gensec_ntlmssp_state->doing_ntlm2 = true; + + memcpy(gensec_ntlmssp_state->crypt.ntlm2.session_nonce, gensec_ntlmssp_state->internal_chal.data, 8); + memcpy(&gensec_ntlmssp_state->crypt.ntlm2.session_nonce[8], gensec_ntlmssp_state->lm_resp.data, 8); + + MD5Init(&md5_session_nonce_ctx); + MD5Update(&md5_session_nonce_ctx, gensec_ntlmssp_state->crypt.ntlm2.session_nonce, 16); + MD5Final(session_nonce_hash, &md5_session_nonce_ctx); + + gensec_ntlmssp_state->chal = data_blob_talloc(gensec_ntlmssp_state, + session_nonce_hash, 8); + + /* LM response is no longer useful, zero it out */ + data_blob_free(&gensec_ntlmssp_state->lm_resp); + + /* We changed the effective challenge - set it */ + if (!NT_STATUS_IS_OK(nt_status = + gensec_ntlmssp_state->set_challenge(gensec_ntlmssp_state, + &gensec_ntlmssp_state->chal))) { + /* zero this out */ + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + return nt_status; + } + + /* LM Key is incompatible... */ + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY; + } + } + return NT_STATUS_OK; +} + +/** + * Next state function for the Authenticate packet + * (after authentication - figures out the session keys etc) + * + * @param gensec_ntlmssp_state NTLMSSP State + * @return Errors or NT_STATUS_OK. + */ + +static NTSTATUS ntlmssp_server_postauth(struct gensec_security *gensec_security, + DATA_BLOB *user_session_key, + DATA_BLOB *lm_session_key) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + NTSTATUS nt_status; + DATA_BLOB session_key = data_blob(NULL, 0); + + if (user_session_key) + dump_data_pw("USER session key:\n", user_session_key->data, user_session_key->length); + + if (lm_session_key) + dump_data_pw("LM first-8:\n", lm_session_key->data, lm_session_key->length); + + /* Handle the different session key derivation for NTLM2 */ + if (gensec_ntlmssp_state->doing_ntlm2) { + if (user_session_key && user_session_key->data && user_session_key->length == 16) { + session_key = data_blob_talloc(gensec_ntlmssp_state, NULL, 16); + hmac_md5(user_session_key->data, gensec_ntlmssp_state->crypt.ntlm2.session_nonce, + sizeof(gensec_ntlmssp_state->crypt.ntlm2.session_nonce), session_key.data); + DEBUG(10,("ntlmssp_server_auth: Created NTLM2 session key.\n")); + dump_data_pw("NTLM2 session key:\n", session_key.data, session_key.length); + + } else { + DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM2 session key.\n")); + session_key = data_blob(NULL, 0); + } + } else if ((gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) + /* Ensure we can never get here on NTLMv2 */ + && (gensec_ntlmssp_state->nt_resp.length == 0 || gensec_ntlmssp_state->nt_resp.length == 24)) { + + if (lm_session_key && lm_session_key->data && lm_session_key->length >= 8) { + if (gensec_ntlmssp_state->lm_resp.data && gensec_ntlmssp_state->lm_resp.length == 24) { + session_key = data_blob_talloc(gensec_ntlmssp_state, NULL, 16); + SMBsesskeygen_lm_sess_key(lm_session_key->data, gensec_ntlmssp_state->lm_resp.data, + session_key.data); + DEBUG(10,("ntlmssp_server_auth: Created NTLM session key.\n")); + dump_data_pw("LM session key:\n", session_key.data, session_key.length); + } else { + + /* When there is no LM response, just use zeros */ + static const uint8_t zeros[24]; + session_key = data_blob_talloc(gensec_ntlmssp_state, NULL, 16); + SMBsesskeygen_lm_sess_key(zeros, zeros, + session_key.data); + DEBUG(10,("ntlmssp_server_auth: Created NTLM session key.\n")); + dump_data_pw("LM session key:\n", session_key.data, session_key.length); + } + } else { + /* LM Key not selected */ + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY; + + DEBUG(10,("ntlmssp_server_auth: Failed to create NTLM session key.\n")); + session_key = data_blob(NULL, 0); + } + + } else if (user_session_key && user_session_key->data) { + session_key = *user_session_key; + DEBUG(10,("ntlmssp_server_auth: Using unmodified nt session key.\n")); + dump_data_pw("unmodified session key:\n", session_key.data, session_key.length); + + /* LM Key not selected */ + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY; + + } else if (lm_session_key && lm_session_key->data) { + /* Very weird to have LM key, but no user session key, but anyway.. */ + session_key = *lm_session_key; + DEBUG(10,("ntlmssp_server_auth: Using unmodified lm session key.\n")); + dump_data_pw("unmodified session key:\n", session_key.data, session_key.length); + + /* LM Key not selected */ + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY; + + } else { + DEBUG(10,("ntlmssp_server_auth: Failed to create unmodified session key.\n")); + session_key = data_blob(NULL, 0); + + /* LM Key not selected */ + gensec_ntlmssp_state->neg_flags &= ~NTLMSSP_NEGOTIATE_LM_KEY; + } + + /* With KEY_EXCH, the client supplies the proposed session key, + but encrypts it with the long-term key */ + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) { + if (!gensec_ntlmssp_state->encrypted_session_key.data + || gensec_ntlmssp_state->encrypted_session_key.length != 16) { + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + DEBUG(1, ("Client-supplied KEY_EXCH session key was of invalid length (%u)!\n", + (unsigned)gensec_ntlmssp_state->encrypted_session_key.length)); + return NT_STATUS_INVALID_PARAMETER; + } else if (!session_key.data || session_key.length != 16) { + DEBUG(5, ("server session key is invalid (len == %u), cannot do KEY_EXCH!\n", + (unsigned)session_key.length)); + gensec_ntlmssp_state->session_key = session_key; + } else { + dump_data_pw("KEY_EXCH session key (enc):\n", + gensec_ntlmssp_state->encrypted_session_key.data, + gensec_ntlmssp_state->encrypted_session_key.length); + arcfour_crypt(gensec_ntlmssp_state->encrypted_session_key.data, + session_key.data, + gensec_ntlmssp_state->encrypted_session_key.length); + gensec_ntlmssp_state->session_key = data_blob_talloc(gensec_ntlmssp_state, + gensec_ntlmssp_state->encrypted_session_key.data, + gensec_ntlmssp_state->encrypted_session_key.length); + dump_data_pw("KEY_EXCH session key:\n", gensec_ntlmssp_state->encrypted_session_key.data, + gensec_ntlmssp_state->encrypted_session_key.length); + } + } else { + gensec_ntlmssp_state->session_key = session_key; + } + + /* keep the session key around on the new context */ + talloc_steal(gensec_ntlmssp_state, session_key.data); + + if ((gensec_security->want_features & GENSEC_FEATURE_SIGN) + || (gensec_security->want_features & GENSEC_FEATURE_SEAL)) { + nt_status = ntlmssp_sign_init(gensec_ntlmssp_state); + } else { + nt_status = NT_STATUS_OK; + } + + data_blob_free(&gensec_ntlmssp_state->encrypted_session_key); + + /* allow arbitarily many authentications, but watch that this will cause a + memory leak, until the gensec_ntlmssp_state is shutdown + */ + + if (gensec_ntlmssp_state->server_multiple_authentications) { + gensec_ntlmssp_state->expected_state = NTLMSSP_AUTH; + } else { + gensec_ntlmssp_state->expected_state = NTLMSSP_DONE; + } + + return nt_status; +} + + +/** + * Next state function for the Authenticate packet + * + * @param gensec_security GENSEC state + * @param out_mem_ctx Memory context for *out + * @param in The request, as a DATA_BLOB. reply.data must be NULL + * @param out The reply, as an allocated DATA_BLOB, caller to free. + * @return Errors or NT_STATUS_OK if authentication sucessful + */ + +NTSTATUS ntlmssp_server_auth(struct gensec_security *gensec_security, + TALLOC_CTX *out_mem_ctx, + const DATA_BLOB in, DATA_BLOB *out) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + DATA_BLOB user_session_key = data_blob(NULL, 0); + DATA_BLOB lm_session_key = data_blob(NULL, 0); + NTSTATUS nt_status; + + TALLOC_CTX *mem_ctx = talloc_new(out_mem_ctx); + if (!mem_ctx) { + return NT_STATUS_NO_MEMORY; + } + + /* zero the outbound NTLMSSP packet */ + *out = data_blob_talloc(out_mem_ctx, NULL, 0); + + if (!NT_STATUS_IS_OK(nt_status = ntlmssp_server_preauth(gensec_ntlmssp_state, in))) { + talloc_free(mem_ctx); + return nt_status; + } + + /* + * Note we don't check here for NTLMv2 auth settings. If NTLMv2 auth + * is required (by "ntlm auth = no" and "lm auth = no" being set in the + * smb.conf file) and no NTLMv2 response was sent then the password check + * will fail here. JRA. + */ + + /* Finally, actually ask if the password is OK */ + + if (!NT_STATUS_IS_OK(nt_status = gensec_ntlmssp_state->check_password(gensec_ntlmssp_state, mem_ctx, + &user_session_key, &lm_session_key))) { + talloc_free(mem_ctx); + return nt_status; + } + + if (gensec_security->want_features + & (GENSEC_FEATURE_SIGN|GENSEC_FEATURE_SEAL|GENSEC_FEATURE_SESSION_KEY)) { + nt_status = ntlmssp_server_postauth(gensec_security, &user_session_key, &lm_session_key); + talloc_free(mem_ctx); + return nt_status; + } else { + gensec_ntlmssp_state->session_key = data_blob(NULL, 0); + talloc_free(mem_ctx); + return NT_STATUS_OK; + } +} + +/** + * Return the challenge as determined by the authentication subsystem + * @return an 8 byte random challenge + */ + +static const uint8_t *auth_ntlmssp_get_challenge(const struct gensec_ntlmssp_state *gensec_ntlmssp_state) +{ + NTSTATUS status; + const uint8_t *chal; + + status = auth_get_challenge(gensec_ntlmssp_state->auth_context, &chal); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(1, ("auth_ntlmssp_get_challenge: failed to get challenge: %s\n", + nt_errstr(status))); + return NULL; + } + + return chal; +} + +/** + * Some authentication methods 'fix' the challenge, so we may not be able to set it + * + * @return If the effective challenge used by the auth subsystem may be modified + */ +static bool auth_ntlmssp_may_set_challenge(const struct gensec_ntlmssp_state *gensec_ntlmssp_state) +{ + return auth_challenge_may_be_modified(gensec_ntlmssp_state->auth_context); +} + +/** + * NTLM2 authentication modifies the effective challenge, + * @param challenge The new challenge value + */ +static NTSTATUS auth_ntlmssp_set_challenge(struct gensec_ntlmssp_state *gensec_ntlmssp_state, DATA_BLOB *challenge) +{ + NTSTATUS nt_status; + struct auth_context *auth_context = gensec_ntlmssp_state->auth_context; + const uint8_t *chal; + + if (challenge->length != 8) { + return NT_STATUS_INVALID_PARAMETER; + } + + chal = challenge->data; + + nt_status = auth_context_set_challenge(auth_context, chal, "NTLMSSP callback (NTLM2)"); + + return nt_status; +} + +/** + * Check the password on an NTLMSSP login. + * + * Return the session keys used on the connection. + */ + +static NTSTATUS auth_ntlmssp_check_password(struct gensec_ntlmssp_state *gensec_ntlmssp_state, + TALLOC_CTX *mem_ctx, + DATA_BLOB *user_session_key, DATA_BLOB *lm_session_key) +{ + NTSTATUS nt_status; + struct auth_usersupplied_info *user_info = talloc(mem_ctx, struct auth_usersupplied_info); + if (!user_info) { + return NT_STATUS_NO_MEMORY; + } + + user_info->logon_parameters = MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT | MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT; + user_info->flags = 0; + user_info->mapped_state = false; + user_info->client.account_name = gensec_ntlmssp_state->user; + user_info->client.domain_name = gensec_ntlmssp_state->domain; + user_info->workstation_name = gensec_ntlmssp_state->workstation; + user_info->remote_host = gensec_get_peer_addr(gensec_ntlmssp_state->gensec_security); + + user_info->password_state = AUTH_PASSWORD_RESPONSE; + user_info->password.response.lanman = gensec_ntlmssp_state->lm_resp; + user_info->password.response.lanman.data = talloc_steal(user_info, gensec_ntlmssp_state->lm_resp.data); + user_info->password.response.nt = gensec_ntlmssp_state->nt_resp; + user_info->password.response.nt.data = talloc_steal(user_info, gensec_ntlmssp_state->nt_resp.data); + + nt_status = auth_check_password(gensec_ntlmssp_state->auth_context, mem_ctx, + user_info, &gensec_ntlmssp_state->server_info); + talloc_free(user_info); + NT_STATUS_NOT_OK_RETURN(nt_status); + + talloc_steal(gensec_ntlmssp_state, gensec_ntlmssp_state->server_info); + + if (gensec_ntlmssp_state->server_info->user_session_key.length) { + DEBUG(10, ("Got NT session key of length %u\n", + (unsigned)gensec_ntlmssp_state->server_info->user_session_key.length)); + if (!talloc_reference(mem_ctx, gensec_ntlmssp_state->server_info->user_session_key.data)) { + return NT_STATUS_NO_MEMORY; + } + + *user_session_key = gensec_ntlmssp_state->server_info->user_session_key; + } + if (gensec_ntlmssp_state->server_info->lm_session_key.length) { + DEBUG(10, ("Got LM session key of length %u\n", + (unsigned)gensec_ntlmssp_state->server_info->lm_session_key.length)); + if (!talloc_reference(mem_ctx, gensec_ntlmssp_state->server_info->lm_session_key.data)) { + return NT_STATUS_NO_MEMORY; + } + + *lm_session_key = gensec_ntlmssp_state->server_info->lm_session_key; + } + return nt_status; +} + +/** + * Return the credentials of a logged on user, including session keys + * etc. + * + * Only valid after a successful authentication + * + * May only be called once per authentication. + * + */ + +NTSTATUS gensec_ntlmssp_session_info(struct gensec_security *gensec_security, + struct auth_session_info **session_info) +{ + NTSTATUS nt_status; + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + + nt_status = auth_generate_session_info(gensec_ntlmssp_state, gensec_security->event_ctx, gensec_security->lp_ctx, gensec_ntlmssp_state->server_info, session_info); + NT_STATUS_NOT_OK_RETURN(nt_status); + + (*session_info)->session_key = data_blob_talloc(*session_info, + gensec_ntlmssp_state->session_key.data, + gensec_ntlmssp_state->session_key.length); + + return NT_STATUS_OK; +} + +/** + * Start NTLMSSP on the server side + * + */ +NTSTATUS gensec_ntlmssp_server_start(struct gensec_security *gensec_security) +{ + NTSTATUS nt_status; + struct gensec_ntlmssp_state *gensec_ntlmssp_state; + + nt_status = gensec_ntlmssp_start(gensec_security); + NT_STATUS_NOT_OK_RETURN(nt_status); + + gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + + gensec_ntlmssp_state->role = NTLMSSP_SERVER; + + gensec_ntlmssp_state->workstation = NULL; + gensec_ntlmssp_state->server_name = lp_netbios_name(gensec_security->lp_ctx); + + gensec_ntlmssp_state->domain = lp_workgroup(gensec_security->lp_ctx); + + gensec_ntlmssp_state->expected_state = NTLMSSP_NEGOTIATE; + + gensec_ntlmssp_state->allow_lm_key = (lp_lanman_auth(gensec_security->lp_ctx) + && lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_server", "allow_lm_key", false)); + + gensec_ntlmssp_state->server_multiple_authentications = false; + + gensec_ntlmssp_state->neg_flags = + NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_UNKNOWN_02000000; + + gensec_ntlmssp_state->lm_resp = data_blob(NULL, 0); + gensec_ntlmssp_state->nt_resp = data_blob(NULL, 0); + gensec_ntlmssp_state->encrypted_session_key = data_blob(NULL, 0); + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_server", "128bit", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_128; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_server", "56bit", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_56; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_server", "keyexchange", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_KEY_EXCH; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_server", "alwayssign", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; + } + + if (lp_parm_bool(gensec_security->lp_ctx, NULL, "ntlmssp_server", "ntlm2", true)) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_NTLM2; + } + + if (gensec_security->want_features & GENSEC_FEATURE_SIGN) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SIGN; + } + if (gensec_security->want_features & GENSEC_FEATURE_SEAL) { + gensec_ntlmssp_state->neg_flags |= NTLMSSP_NEGOTIATE_SEAL; + } + + nt_status = auth_context_create(gensec_ntlmssp_state, + gensec_security->event_ctx, + gensec_security->msg_ctx, + gensec_security->lp_ctx, + &gensec_ntlmssp_state->auth_context); + NT_STATUS_NOT_OK_RETURN(nt_status); + + gensec_ntlmssp_state->get_challenge = auth_ntlmssp_get_challenge; + gensec_ntlmssp_state->may_set_challenge = auth_ntlmssp_may_set_challenge; + gensec_ntlmssp_state->set_challenge = auth_ntlmssp_set_challenge; + gensec_ntlmssp_state->check_password = auth_ntlmssp_check_password; + gensec_ntlmssp_state->server_role = lp_server_role(gensec_security->lp_ctx); + + return NT_STATUS_OK; +} + diff --git a/source4/auth/ntlmssp/ntlmssp_sign.c b/source4/auth/ntlmssp/ntlmssp_sign.c new file mode 100644 index 0000000000..063b16f539 --- /dev/null +++ b/source4/auth/ntlmssp/ntlmssp_sign.c @@ -0,0 +1,548 @@ +/* + * Unix SMB/CIFS implementation. + * Version 3.0 + * NTLMSSP Signing routines + * Copyright (C) Luke Kenneth Casson Leighton 1996-2001 + * Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2005 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see <http://www.gnu.org/licenses/>. + */ + +#include "includes.h" +#include "auth/auth.h" +#include "auth/ntlmssp/ntlmssp.h" +#include "auth/ntlmssp/msrpc_parse.h" +#include "lib/crypto/crypto.h" +#include "auth/credentials/credentials.h" +#include "auth/gensec/gensec.h" +#include "param/param.h" + +#define CLI_SIGN "session key to client-to-server signing key magic constant" +#define CLI_SEAL "session key to client-to-server sealing key magic constant" +#define SRV_SIGN "session key to server-to-client signing key magic constant" +#define SRV_SEAL "session key to server-to-client sealing key magic constant" + +/** + * Some notes on the NTLM2 code: + * + * NTLM2 is a AEAD system. This means that the data encrypted is not + * all the data that is signed. In DCE-RPC case, the headers of the + * DCE-RPC packets are also signed. This prevents some of the + * fun-and-games one might have by changing them. + * + */ + +static void calc_ntlmv2_key(TALLOC_CTX *mem_ctx, + DATA_BLOB *subkey, + DATA_BLOB session_key, + const char *constant) +{ + struct MD5Context ctx3; + *subkey = data_blob_talloc(mem_ctx, NULL, 16); + MD5Init(&ctx3); + MD5Update(&ctx3, session_key.data, session_key.length); + MD5Update(&ctx3, (const uint8_t *)constant, strlen(constant)+1); + MD5Final(subkey->data, &ctx3); +} + +enum ntlmssp_direction { + NTLMSSP_SEND, + NTLMSSP_RECEIVE +}; + +static NTSTATUS ntlmssp_make_packet_signature(struct gensec_ntlmssp_state *gensec_ntlmssp_state, + TALLOC_CTX *sig_mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + enum ntlmssp_direction direction, + DATA_BLOB *sig, bool encrypt_sig) +{ + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) { + + HMACMD5Context ctx; + uint8_t digest[16]; + uint8_t seq_num[4]; + + *sig = data_blob_talloc(sig_mem_ctx, NULL, NTLMSSP_SIG_SIZE); + if (!sig->data) { + return NT_STATUS_NO_MEMORY; + } + + switch (direction) { + case NTLMSSP_SEND: + SIVAL(seq_num, 0, gensec_ntlmssp_state->crypt.ntlm2.send_seq_num); + gensec_ntlmssp_state->crypt.ntlm2.send_seq_num++; + hmac_md5_init_limK_to_64(gensec_ntlmssp_state->crypt.ntlm2.send_sign_key.data, + gensec_ntlmssp_state->crypt.ntlm2.send_sign_key.length, &ctx); + break; + case NTLMSSP_RECEIVE: + SIVAL(seq_num, 0, gensec_ntlmssp_state->crypt.ntlm2.recv_seq_num); + gensec_ntlmssp_state->crypt.ntlm2.recv_seq_num++; + hmac_md5_init_limK_to_64(gensec_ntlmssp_state->crypt.ntlm2.recv_sign_key.data, + gensec_ntlmssp_state->crypt.ntlm2.recv_sign_key.length, &ctx); + break; + } + hmac_md5_update(seq_num, sizeof(seq_num), &ctx); + hmac_md5_update(whole_pdu, pdu_length, &ctx); + hmac_md5_final(digest, &ctx); + + if (encrypt_sig && gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) { + switch (direction) { + case NTLMSSP_SEND: + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state, digest, 8); + break; + case NTLMSSP_RECEIVE: + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm2.recv_seal_arcfour_state, digest, 8); + break; + } + } + + SIVAL(sig->data, 0, NTLMSSP_SIGN_VERSION); + memcpy(sig->data + 4, digest, 8); + memcpy(sig->data + 12, seq_num, 4); + + DEBUG(10, ("NTLM2: created signature over %llu bytes of input:\n", (unsigned long long)pdu_length)); + dump_data(11, sig->data, sig->length); + + } else { + uint32_t crc; + crc = crc32_calc_buffer(data, length); + if (!msrpc_gen(sig_mem_ctx, + lp_iconv_convenience(gensec_ntlmssp_state->gensec_security->lp_ctx), + sig, "dddd", NTLMSSP_SIGN_VERSION, 0, crc, gensec_ntlmssp_state->crypt.ntlm.seq_num)) { + return NT_STATUS_NO_MEMORY; + } + gensec_ntlmssp_state->crypt.ntlm.seq_num++; + + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm.arcfour_state, sig->data+4, sig->length-4); + + DEBUG(10, ("NTLM1: created signature over %llu bytes of input:\n", (unsigned long long)length)); + dump_data(11, sig->data, sig->length); + } + return NT_STATUS_OK; +} + +/* TODO: make this non-public */ +NTSTATUS gensec_ntlmssp_sign_packet(struct gensec_security *gensec_security, + TALLOC_CTX *sig_mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + + return ntlmssp_make_packet_signature(gensec_ntlmssp_state, sig_mem_ctx, + data, length, + whole_pdu, pdu_length, + NTLMSSP_SEND, sig, true); +} + +/** + * Check the signature of an incoming packet + * + */ + +NTSTATUS gensec_ntlmssp_check_packet(struct gensec_security *gensec_security, + TALLOC_CTX *sig_mem_ctx, + const uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + + DATA_BLOB local_sig; + NTSTATUS nt_status; + + if (!gensec_ntlmssp_state->session_key.length) { + DEBUG(3, ("NO session key, cannot check packet signature\n")); + return NT_STATUS_NO_USER_SESSION_KEY; + } + + nt_status = ntlmssp_make_packet_signature(gensec_ntlmssp_state, sig_mem_ctx, + data, length, + whole_pdu, pdu_length, + NTLMSSP_RECEIVE, &local_sig, true); + + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(0, ("NTLMSSP packet check failed with %s\n", nt_errstr(nt_status))); + return nt_status; + } + + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) { + if (local_sig.length != sig->length || + memcmp(local_sig.data, + sig->data, sig->length) != 0) { + DEBUG(5, ("BAD SIG NTLM2: wanted signature over %llu bytes of input:\n", (unsigned long long)pdu_length)); + dump_data(5, local_sig.data, local_sig.length); + + DEBUG(5, ("BAD SIG: got signature over %llu bytes of input:\n", (unsigned long long)pdu_length)); + dump_data(5, sig->data, sig->length); + + DEBUG(1, ("NTLMSSP NTLM2 packet check failed due to invalid signature on %llu bytes of input!\n", (unsigned long long)pdu_length)); + return NT_STATUS_ACCESS_DENIED; + } + } else { + if (local_sig.length != sig->length || + memcmp(local_sig.data + 8, + sig->data + 8, sig->length - 8) != 0) { + DEBUG(5, ("BAD SIG NTLM1: wanted signature of %llu bytes of input:\n", (unsigned long long)length)); + dump_data(5, local_sig.data, local_sig.length); + + DEBUG(5, ("BAD SIG: got signature of %llu bytes of input:\n", (unsigned long long)length)); + dump_data(5, sig->data, sig->length); + + DEBUG(1, ("NTLMSSP NTLM1 packet check failed due to invalid signature on %llu bytes of input:\n", (unsigned long long)length)); + return NT_STATUS_ACCESS_DENIED; + } + } + dump_data_pw("checked ntlmssp signature\n", sig->data, sig->length); + + return NT_STATUS_OK; +} + + +/** + * Seal data with the NTLMSSP algorithm + * + */ + +NTSTATUS gensec_ntlmssp_seal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *sig_mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + DATA_BLOB *sig) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + NTSTATUS nt_status; + if (!gensec_ntlmssp_state->session_key.length) { + DEBUG(3, ("NO session key, cannot seal packet\n")); + return NT_STATUS_NO_USER_SESSION_KEY; + } + + DEBUG(10,("ntlmssp_seal_data: seal\n")); + dump_data_pw("ntlmssp clear data\n", data, length); + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) { + /* The order of these two operations matters - we must first seal the packet, + then seal the sequence number - this is becouse the send_seal_hash is not + constant, but is is rather updated with each iteration */ + nt_status = ntlmssp_make_packet_signature(gensec_ntlmssp_state, sig_mem_ctx, + data, length, + whole_pdu, pdu_length, + NTLMSSP_SEND, sig, false); + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state, data, length); + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCH) { + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state, sig->data+4, 8); + } + } else { + uint32_t crc; + crc = crc32_calc_buffer(data, length); + if (!msrpc_gen(sig_mem_ctx, + lp_iconv_convenience(gensec_security->lp_ctx), + sig, "dddd", NTLMSSP_SIGN_VERSION, 0, crc, gensec_ntlmssp_state->crypt.ntlm.seq_num)) { + return NT_STATUS_NO_MEMORY; + } + + /* The order of these two operations matters - we must + first seal the packet, then seal the sequence + number - this is becouse the ntlmssp_hash is not + constant, but is is rather updated with each + iteration */ + + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm.arcfour_state, data, length); + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm.arcfour_state, sig->data+4, sig->length-4); + /* increment counter on send */ + gensec_ntlmssp_state->crypt.ntlm.seq_num++; + nt_status = NT_STATUS_OK; + } + dump_data_pw("ntlmssp signature\n", sig->data, sig->length); + dump_data_pw("ntlmssp sealed data\n", data, length); + + + return nt_status; +} + +/** + * Unseal data with the NTLMSSP algorithm + * + */ + +/* + wrappers for the ntlmssp_*() functions +*/ +NTSTATUS gensec_ntlmssp_unseal_packet(struct gensec_security *gensec_security, + TALLOC_CTX *sig_mem_ctx, + uint8_t *data, size_t length, + const uint8_t *whole_pdu, size_t pdu_length, + const DATA_BLOB *sig) +{ + struct gensec_ntlmssp_state *gensec_ntlmssp_state = (struct gensec_ntlmssp_state *)gensec_security->private_data; + if (!gensec_ntlmssp_state->session_key.length) { + DEBUG(3, ("NO session key, cannot unseal packet\n")); + return NT_STATUS_NO_USER_SESSION_KEY; + } + + dump_data_pw("ntlmssp sealed data\n", data, length); + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) { + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm2.recv_seal_arcfour_state, data, length); + } else { + arcfour_crypt_sbox(gensec_ntlmssp_state->crypt.ntlm.arcfour_state, data, length); + } + dump_data_pw("ntlmssp clear data\n", data, length); + return gensec_ntlmssp_check_packet(gensec_security, sig_mem_ctx, data, length, whole_pdu, pdu_length, sig); +} + +/** + Initialise the state for NTLMSSP signing. +*/ +/* TODO: make this non-public */ +NTSTATUS ntlmssp_sign_init(struct gensec_ntlmssp_state *gensec_ntlmssp_state) +{ + TALLOC_CTX *mem_ctx = talloc_new(gensec_ntlmssp_state); + + if (!mem_ctx) { + return NT_STATUS_NO_MEMORY; + } + + DEBUG(3, ("NTLMSSP Sign/Seal - Initialising with flags:\n")); + debug_ntlmssp_flags(gensec_ntlmssp_state->neg_flags); + + if (gensec_ntlmssp_state->session_key.length < 8) { + talloc_free(mem_ctx); + DEBUG(3, ("NO session key, cannot intialise signing\n")); + return NT_STATUS_NO_USER_SESSION_KEY; + } + + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2) + { + DATA_BLOB weak_session_key = gensec_ntlmssp_state->session_key; + const char *send_sign_const; + const char *send_seal_const; + const char *recv_sign_const; + const char *recv_seal_const; + + DATA_BLOB send_seal_key; + DATA_BLOB recv_seal_key; + + switch (gensec_ntlmssp_state->role) { + case NTLMSSP_CLIENT: + send_sign_const = CLI_SIGN; + send_seal_const = CLI_SEAL; + recv_sign_const = SRV_SIGN; + recv_seal_const = SRV_SEAL; + break; + case NTLMSSP_SERVER: + send_sign_const = SRV_SIGN; + send_seal_const = SRV_SEAL; + recv_sign_const = CLI_SIGN; + recv_seal_const = CLI_SEAL; + break; + default: + talloc_free(mem_ctx); + return NT_STATUS_INTERNAL_ERROR; + } + + gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state = talloc(gensec_ntlmssp_state, struct arcfour_state); + NT_STATUS_HAVE_NO_MEMORY(gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state); + gensec_ntlmssp_state->crypt.ntlm2.recv_seal_arcfour_state = talloc(gensec_ntlmssp_state, struct arcfour_state); + NT_STATUS_HAVE_NO_MEMORY(gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state); + + /** + Weaken NTLMSSP keys to cope with down-level + clients, servers and export restrictions. + + We probably should have some parameters to control + this, once we get NTLM2 working. + */ + + /* Key weakening was not performed on the master key + * for NTLM2 (in ntlmssp_weaken_keys()), but must be + * done on the encryption subkeys only. That is why + * we don't have this code for the ntlmv1 case. + */ + + if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_128) { + + } else if (gensec_ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_56) { + weak_session_key.length = 7; + } else { /* forty bits */ + weak_session_key.length = 5; + } + dump_data_pw("NTLMSSP weakend master key:\n", + weak_session_key.data, + weak_session_key.length); + + /* SEND: sign key */ + calc_ntlmv2_key(gensec_ntlmssp_state, + &gensec_ntlmssp_state->crypt.ntlm2.send_sign_key, + gensec_ntlmssp_state->session_key, send_sign_const); + dump_data_pw("NTLMSSP send sign key:\n", + gensec_ntlmssp_state->crypt.ntlm2.send_sign_key.data, + gensec_ntlmssp_state->crypt.ntlm2.send_sign_key.length); + + /* SEND: seal ARCFOUR pad */ + calc_ntlmv2_key(mem_ctx, + &send_seal_key, + weak_session_key, send_seal_const); + dump_data_pw("NTLMSSP send seal key:\n", + send_seal_key.data, + send_seal_key.length); + arcfour_init(gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state, + &send_seal_key); + dump_data_pw("NTLMSSP send sesl hash:\n", + gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state->sbox, + sizeof(gensec_ntlmssp_state->crypt.ntlm2.send_seal_arcfour_state->sbox)); + + /* RECV: sign key */ + calc_ntlmv2_key(gensec_ntlmssp_state, + &gensec_ntlmssp_state->crypt.ntlm2.recv_sign_key, + gensec_ntlmssp_state->session_key, recv_sign_const); + dump_data_pw("NTLMSSP recv sign key:\n", + gensec_ntlmssp_state->crypt.ntlm2.recv_sign_key.data, + gensec_ntlmssp_state->crypt.ntlm2.recv_sign_key.length); + + /* RECV: seal ARCFOUR pad */ + calc_ntlmv2_key(mem_ctx, + &recv_seal_key, + weak_session_key, recv_seal_const); + dump_data_pw("NTLMSSP recv seal key:\n", + recv_seal_key.data, + recv_seal_key.length); + arcfour_init(gensec_ntlmssp_state->crypt.ntlm2.recv_seal_arcfour_state, + &recv_seal_key); + dump_data_pw("NTLMSSP receive seal hash:\n", + gensec_ntlmssp_state->crypt.ntlm2.recv_seal_arcfour_state->sbox, + sizeof(gensec_ntlmssp_state->crypt.ntlm2.recv_seal_arcfour_state->sbox)); + + gensec_ntlmssp_state->crypt.ntlm2.send_seq_num = 0; + gensec_ntlmssp_state->crypt.ntlm2.recv_seq_num = 0; + + } else { + DATA_BLOB weak_session_key = ntlmssp_weakend_key(gensec_ntlmssp_state, mem_ctx); + DEBUG(5, ("NTLMSSP Sign/Seal - using NTLM1\n")); + + gensec_ntlmssp_state->crypt.ntlm.arcfour_state = talloc(gensec_ntlmssp_state, struct arcfour_state); + NT_STATUS_HAVE_NO_MEMORY(gensec_ntlmssp_state->crypt.ntlm.arcfour_state); + + arcfour_init(gensec_ntlmssp_state->crypt.ntlm.arcfour_state, + &weak_session_key); + dump_data_pw("NTLMSSP hash:\n", gensec_ntlmssp_state->crypt.ntlm.arcfour_state->sbox, + sizeof(gensec_ntlmssp_state->crypt.ntlm.arcfour_state->sbox)); + + gensec_ntlmssp_state->crypt.ntlm.seq_num = 0; + } + + talloc_free(mem_ctx); + return NT_STATUS_OK; +} + +size_t gensec_ntlmssp_sig_size(struct gensec_security *gensec_security, size_t data_size) +{ + return NTLMSSP_SIG_SIZE; +} + +NTSTATUS gensec_ntlmssp_wrap(struct gensec_security *gensec_security, + TALLOC_CTX *sig_mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + DATA_BLOB sig; + NTSTATUS nt_status; + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + + *out = data_blob_talloc(sig_mem_ctx, NULL, in->length + NTLMSSP_SIG_SIZE); + if (!out->data) { + return NT_STATUS_NO_MEMORY; + } + memcpy(out->data + NTLMSSP_SIG_SIZE, in->data, in->length); + + nt_status = gensec_ntlmssp_seal_packet(gensec_security, sig_mem_ctx, + out->data + NTLMSSP_SIG_SIZE, + out->length - NTLMSSP_SIG_SIZE, + out->data + NTLMSSP_SIG_SIZE, + out->length - NTLMSSP_SIG_SIZE, + &sig); + + if (NT_STATUS_IS_OK(nt_status)) { + memcpy(out->data, sig.data, NTLMSSP_SIG_SIZE); + } + return nt_status; + + } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + + *out = data_blob_talloc(sig_mem_ctx, NULL, in->length + NTLMSSP_SIG_SIZE); + if (!out->data) { + return NT_STATUS_NO_MEMORY; + } + memcpy(out->data + NTLMSSP_SIG_SIZE, in->data, in->length); + + nt_status = gensec_ntlmssp_sign_packet(gensec_security, sig_mem_ctx, + out->data + NTLMSSP_SIG_SIZE, + out->length - NTLMSSP_SIG_SIZE, + out->data + NTLMSSP_SIG_SIZE, + out->length - NTLMSSP_SIG_SIZE, + &sig); + + if (NT_STATUS_IS_OK(nt_status)) { + memcpy(out->data, sig.data, NTLMSSP_SIG_SIZE); + } + return nt_status; + + } else { + *out = *in; + return NT_STATUS_OK; + } +} + + +NTSTATUS gensec_ntlmssp_unwrap(struct gensec_security *gensec_security, + TALLOC_CTX *sig_mem_ctx, + const DATA_BLOB *in, + DATA_BLOB *out) +{ + DATA_BLOB sig; + + if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) { + if (in->length < NTLMSSP_SIG_SIZE) { + return NT_STATUS_INVALID_PARAMETER; + } + sig.data = in->data; + sig.length = NTLMSSP_SIG_SIZE; + + *out = data_blob_talloc(sig_mem_ctx, in->data + NTLMSSP_SIG_SIZE, in->length - NTLMSSP_SIG_SIZE); + + return gensec_ntlmssp_unseal_packet(gensec_security, sig_mem_ctx, + out->data, out->length, + out->data, out->length, + &sig); + + } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) { + if (in->length < NTLMSSP_SIG_SIZE) { + return NT_STATUS_INVALID_PARAMETER; + } + sig.data = in->data; + sig.length = NTLMSSP_SIG_SIZE; + + *out = data_blob_talloc(sig_mem_ctx, in->data + NTLMSSP_SIG_SIZE, in->length - NTLMSSP_SIG_SIZE); + + return gensec_ntlmssp_check_packet(gensec_security, sig_mem_ctx, + out->data, out->length, + out->data, out->length, + &sig); + } else { + *out = *in; + return NT_STATUS_OK; + } +} + diff --git a/source4/auth/sam.c b/source4/auth/sam.c new file mode 100644 index 0000000000..a2090afcdc --- /dev/null +++ b/source4/auth/sam.c @@ -0,0 +1,470 @@ +/* + Unix SMB/CIFS implementation. + Password and authentication handling + Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2004 + Copyright (C) Gerald Carter 2003 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "system/time.h" +#include "auth/auth.h" +#include <ldb.h> +#include "util/util_ldb.h" +#include "dsdb/samdb/samdb.h" +#include "libcli/security/security.h" +#include "libcli/ldap/ldap.h" +#include "librpc/gen_ndr/ndr_netlogon.h" +#include "param/param.h" + +const char *user_attrs[] = { + /* required for the krb5 kdc */ + "objectClass", + "sAMAccountName", + "userPrincipalName", + "servicePrincipalName", + "msDS-KeyVersionNumber", + "supplementalCredentials", + + /* passwords */ + "dBCSPwd", + "unicodePwd", + + "userAccountControl", + + "pwdLastSet", + "accountExpires", + "logonHours", + "objectSid", + + /* check 'allowed workstations' */ + "userWorkstations", + + /* required for server_info, not access control: */ + "displayName", + "scriptPath", + "profilePath", + "homeDirectory", + "homeDrive", + "lastLogon", + "lastLogoff", + "accountExpires", + "badPwdCount", + "logonCount", + "primaryGroupID", + NULL, +}; + +const char *domain_ref_attrs[] = {"nETBIOSName", "nCName", + "dnsRoot", "objectClass", NULL}; + +/**************************************************************************** + Check if a user is allowed to logon at this time. Note this is the + servers local time, as logon hours are just specified as a weekly + bitmask. +****************************************************************************/ + +static bool logon_hours_ok(struct ldb_message *msg, const char *name_for_logs) +{ + /* In logon hours first bit is Sunday from 12AM to 1AM */ + const struct ldb_val *hours; + struct tm *utctime; + time_t lasttime; + const char *asct; + uint8_t bitmask, bitpos; + + hours = ldb_msg_find_ldb_val(msg, "logonHours"); + if (!hours) { + DEBUG(5,("logon_hours_ok: No hours restrictions for user %s\n", name_for_logs)); + return true; + } + + if (hours->length != 168/8) { + DEBUG(5,("logon_hours_ok: malformed logon hours restrictions for user %s\n", name_for_logs)); + return true; + } + + lasttime = time(NULL); + utctime = gmtime(&lasttime); + if (!utctime) { + DEBUG(1, ("logon_hours_ok: failed to get gmtime. Failing logon for user %s\n", + name_for_logs)); + return false; + } + + /* find the corresponding byte and bit */ + bitpos = (utctime->tm_wday * 24 + utctime->tm_hour) % 168; + bitmask = 1 << (bitpos % 8); + + if (! (hours->data[bitpos/8] & bitmask)) { + struct tm *t = localtime(&lasttime); + if (!t) { + asct = "INVALID TIME"; + } else { + asct = asctime(t); + if (!asct) { + asct = "INVALID TIME"; + } + } + + DEBUG(1, ("logon_hours_ok: Account for user %s not allowed to " + "logon at this time (%s).\n", + name_for_logs, asct )); + return false; + } + + asct = asctime(utctime); + DEBUG(5,("logon_hours_ok: user %s allowed to logon at this time (%s)\n", + name_for_logs, asct ? asct : "UNKNOWN TIME" )); + + return true; +} + +/**************************************************************************** + Do a specific test for a SAM_ACCOUNT being vaild for this connection + (ie not disabled, expired and the like). +****************************************************************************/ +_PUBLIC_ NTSTATUS authsam_account_ok(TALLOC_CTX *mem_ctx, + struct ldb_context *sam_ctx, + uint32_t logon_parameters, + struct ldb_message *msg, + struct ldb_message *msg_domain_ref, + const char *logon_workstation, + const char *name_for_logs) +{ + uint16_t acct_flags; + const char *workstation_list; + NTTIME acct_expiry; + NTTIME must_change_time; + + struct ldb_dn *domain_dn = samdb_result_dn(sam_ctx, mem_ctx, msg_domain_ref, "nCName", ldb_dn_new(mem_ctx, sam_ctx, NULL)); + + NTTIME now; + DEBUG(4,("authsam_account_ok: Checking SMB password for user %s\n", name_for_logs)); + + acct_flags = samdb_result_acct_flags(sam_ctx, mem_ctx, msg, domain_dn); + + acct_expiry = samdb_result_account_expires(msg); + + /* Check for when we must change this password, taking the + * userAccountControl flags into account */ + must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, + domain_dn, msg); + + workstation_list = samdb_result_string(msg, "userWorkstations", NULL); + + /* Quit if the account was disabled. */ + if (acct_flags & ACB_DISABLED) { + DEBUG(1,("authsam_account_ok: Account for user '%s' was disabled.\n", name_for_logs)); + return NT_STATUS_ACCOUNT_DISABLED; + } + + /* Quit if the account was locked out. */ + if (acct_flags & ACB_AUTOLOCK) { + DEBUG(1,("authsam_account_ok: Account for user %s was locked out.\n", name_for_logs)); + return NT_STATUS_ACCOUNT_LOCKED_OUT; + } + + /* Test account expire time */ + unix_to_nt_time(&now, time(NULL)); + if (now > acct_expiry) { + DEBUG(1,("authsam_account_ok: Account for user '%s' has expired.\n", name_for_logs)); + DEBUG(3,("authsam_account_ok: Account expired at '%s'.\n", + nt_time_string(mem_ctx, acct_expiry))); + return NT_STATUS_ACCOUNT_EXPIRED; + } + + /* check for immediate expiry "must change at next logon" */ + if (must_change_time == 0) { + DEBUG(1,("sam_account_ok: Account for user '%s' password must change!.\n", + name_for_logs)); + return NT_STATUS_PASSWORD_MUST_CHANGE; + } + + /* check for expired password */ + if (must_change_time < now) { + DEBUG(1,("sam_account_ok: Account for user '%s' password expired!.\n", + name_for_logs)); + DEBUG(1,("sam_account_ok: Password expired at '%s' unix time.\n", + nt_time_string(mem_ctx, must_change_time))); + return NT_STATUS_PASSWORD_EXPIRED; + } + + /* Test workstation. Workstation list is comma separated. */ + if (logon_workstation && workstation_list && *workstation_list) { + bool invalid_ws = true; + int i; + const char **workstations = str_list_make(mem_ctx, workstation_list, ","); + + for (i = 0; workstations && workstations[i]; i++) { + DEBUG(10,("sam_account_ok: checking for workstation match '%s' and '%s'\n", + workstations[i], logon_workstation)); + + if (strequal(workstations[i], logon_workstation)) { + invalid_ws = false; + break; + } + } + + talloc_free(workstations); + + if (invalid_ws) { + return NT_STATUS_INVALID_WORKSTATION; + } + } + + if (!logon_hours_ok(msg, name_for_logs)) { + return NT_STATUS_INVALID_LOGON_HOURS; + } + + if (acct_flags & ACB_DOMTRUST) { + DEBUG(2,("sam_account_ok: Domain trust account %s denied by server\n", name_for_logs)); + return NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT; + } + + if (!(logon_parameters & MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT)) { + if (acct_flags & ACB_SVRTRUST) { + DEBUG(2,("sam_account_ok: Server trust account %s denied by server\n", name_for_logs)); + return NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT; + } + } + if (!(logon_parameters & MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT)) { + if (acct_flags & ACB_WSTRUST) { + DEBUG(4,("sam_account_ok: Wksta trust account %s denied by server\n", name_for_logs)); + return NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT; + } + } + + return NT_STATUS_OK; +} + +_PUBLIC_ NTSTATUS authsam_make_server_info(TALLOC_CTX *mem_ctx, struct ldb_context *sam_ctx, + const char *netbios_name, + struct ldb_message *msg, + struct ldb_message *msg_domain_ref, + DATA_BLOB user_sess_key, DATA_BLOB lm_sess_key, + struct auth_serversupplied_info **_server_info) +{ + struct auth_serversupplied_info *server_info; + struct ldb_message **group_msgs; + int group_ret; + const char *group_attrs[3] = { "sAMAccountType", "objectSid", NULL }; + /* find list of sids */ + struct dom_sid **groupSIDs = NULL; + struct dom_sid *account_sid; + struct dom_sid *primary_group_sid; + struct ldb_dn *domain_dn; + const char *str; + struct ldb_dn *ncname; + int i; + uint_t rid; + TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); + + group_ret = gendb_search(sam_ctx, + tmp_ctx, NULL, &group_msgs, group_attrs, + "(&(member=%s)(sAMAccountType=*))", + ldb_dn_get_linearized(msg->dn)); + if (group_ret == -1) { + talloc_free(tmp_ctx); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + server_info = talloc(mem_ctx, struct auth_serversupplied_info); + NT_STATUS_HAVE_NO_MEMORY(server_info); + + if (group_ret > 0) { + groupSIDs = talloc_array(server_info, struct dom_sid *, group_ret); + NT_STATUS_HAVE_NO_MEMORY(groupSIDs); + } + + /* Need to unroll some nested groups, but not aliases */ + for (i = 0; i < group_ret; i++) { + groupSIDs[i] = samdb_result_dom_sid(groupSIDs, + group_msgs[i], "objectSid"); + NT_STATUS_HAVE_NO_MEMORY(groupSIDs[i]); + } + + talloc_free(tmp_ctx); + + account_sid = samdb_result_dom_sid(server_info, msg, "objectSid"); + NT_STATUS_HAVE_NO_MEMORY(account_sid); + + primary_group_sid = dom_sid_dup(server_info, account_sid); + NT_STATUS_HAVE_NO_MEMORY(primary_group_sid); + + rid = samdb_result_uint(msg, "primaryGroupID", ~0); + if (rid == ~0) { + if (group_ret > 0) { + primary_group_sid = groupSIDs[0]; + } else { + primary_group_sid = NULL; + } + } else { + primary_group_sid->sub_auths[primary_group_sid->num_auths-1] = rid; + } + + server_info->account_sid = account_sid; + server_info->primary_group_sid = primary_group_sid; + + server_info->n_domain_groups = group_ret; + server_info->domain_groups = groupSIDs; + + server_info->account_name = talloc_steal(server_info, samdb_result_string(msg, "sAMAccountName", NULL)); + + server_info->domain_name = talloc_steal(server_info, samdb_result_string(msg_domain_ref, "nETBIOSName", NULL)); + + str = samdb_result_string(msg, "displayName", ""); + server_info->full_name = talloc_strdup(server_info, str); + NT_STATUS_HAVE_NO_MEMORY(server_info->full_name); + + str = samdb_result_string(msg, "scriptPath", ""); + server_info->logon_script = talloc_strdup(server_info, str); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_script); + + str = samdb_result_string(msg, "profilePath", ""); + server_info->profile_path = talloc_strdup(server_info, str); + NT_STATUS_HAVE_NO_MEMORY(server_info->profile_path); + + str = samdb_result_string(msg, "homeDirectory", ""); + server_info->home_directory = talloc_strdup(server_info, str); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_directory); + + str = samdb_result_string(msg, "homeDrive", ""); + server_info->home_drive = talloc_strdup(server_info, str); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_drive); + + server_info->logon_server = talloc_strdup(server_info, netbios_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_server); + + server_info->last_logon = samdb_result_nttime(msg, "lastLogon", 0); + server_info->last_logoff = samdb_result_nttime(msg, "lastLogoff", 0); + server_info->acct_expiry = samdb_result_account_expires(msg); + server_info->last_password_change = samdb_result_nttime(msg, "pwdLastSet", 0); + + ncname = samdb_result_dn(sam_ctx, mem_ctx, msg_domain_ref, "nCName", NULL); + if (!ncname) { + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + server_info->allow_password_change + = samdb_result_allow_password_change(sam_ctx, mem_ctx, + ncname, msg, "pwdLastSet"); + server_info->force_password_change + = samdb_result_force_password_change(sam_ctx, mem_ctx, + ncname, msg); + + server_info->logon_count = samdb_result_uint(msg, "logonCount", 0); + server_info->bad_password_count = samdb_result_uint(msg, "badPwdCount", 0); + + domain_dn = samdb_result_dn(sam_ctx, mem_ctx, msg_domain_ref, "nCName", NULL); + + server_info->acct_flags = samdb_result_acct_flags(sam_ctx, mem_ctx, + msg, domain_dn); + + server_info->user_session_key = user_sess_key; + server_info->lm_session_key = lm_sess_key; + + server_info->authenticated = true; + + *_server_info = server_info; + + return NT_STATUS_OK; +} + +NTSTATUS sam_get_results_principal(struct ldb_context *sam_ctx, + TALLOC_CTX *mem_ctx, const char *principal, + struct ldb_message ***msgs, + struct ldb_message ***msgs_domain_ref) +{ + struct ldb_dn *user_dn, *domain_dn; + NTSTATUS nt_status; + TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); + int ret; + struct ldb_dn *partitions_basedn = samdb_partitions_dn(sam_ctx, mem_ctx); + + if (!tmp_ctx) { + return NT_STATUS_NO_MEMORY; + } + + nt_status = crack_user_principal_name(sam_ctx, tmp_ctx, principal, &user_dn, &domain_dn); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(tmp_ctx); + return nt_status; + } + + /* grab domain info from the reference */ + ret = gendb_search(sam_ctx, tmp_ctx, partitions_basedn, msgs_domain_ref, domain_ref_attrs, + "(ncName=%s)", ldb_dn_get_linearized(domain_dn)); + + if (ret != 1) { + talloc_free(tmp_ctx); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + /* pull the user attributes */ + ret = gendb_search_dn(sam_ctx, tmp_ctx, user_dn, msgs, user_attrs); + if (ret != 1) { + talloc_free(tmp_ctx); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + talloc_steal(mem_ctx, *msgs); + talloc_steal(mem_ctx, *msgs_domain_ref); + talloc_free(tmp_ctx); + + return NT_STATUS_OK; +} + +/* Used in the gensec_gssapi and gensec_krb5 server-side code, where the PAC isn't available */ +NTSTATUS sam_get_server_info_principal(TALLOC_CTX *mem_ctx, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *principal, + struct auth_serversupplied_info **server_info) +{ + NTSTATUS nt_status; + DATA_BLOB user_sess_key = data_blob(NULL, 0); + DATA_BLOB lm_sess_key = data_blob(NULL, 0); + + struct ldb_message **msgs; + struct ldb_message **msgs_domain_ref; + struct ldb_context *sam_ctx; + + TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx); + if (!tmp_ctx) { + return NT_STATUS_NO_MEMORY; + } + + sam_ctx = samdb_connect(tmp_ctx, event_ctx, lp_ctx, system_session(tmp_ctx, lp_ctx)); + if (sam_ctx == NULL) { + talloc_free(tmp_ctx); + return NT_STATUS_INVALID_SYSTEM_SERVICE; + } + + nt_status = sam_get_results_principal(sam_ctx, tmp_ctx, principal, + &msgs, &msgs_domain_ref); + if (!NT_STATUS_IS_OK(nt_status)) { + return nt_status; + } + + nt_status = authsam_make_server_info(tmp_ctx, sam_ctx, lp_netbios_name(lp_ctx), + msgs[0], msgs_domain_ref[0], + user_sess_key, lm_sess_key, + server_info); + if (NT_STATUS_IS_OK(nt_status)) { + talloc_steal(mem_ctx, *server_info); + } + talloc_free(tmp_ctx); + return nt_status; +} diff --git a/source4/auth/session.c b/source4/auth/session.c new file mode 100644 index 0000000000..d75f1793e1 --- /dev/null +++ b/source4/auth/session.c @@ -0,0 +1,343 @@ +/* + Unix SMB/CIFS implementation. + Authentication utility functions + Copyright (C) Andrew Tridgell 1992-1998 + Copyright (C) Andrew Bartlett 2001 + Copyright (C) Jeremy Allison 2000-2001 + Copyright (C) Rafal Szczesniak 2002 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "auth/auth.h" +#include "libcli/security/security.h" +#include "libcli/auth/libcli_auth.h" +#include "dsdb/samdb/samdb.h" +#include "auth/credentials/credentials.h" +#include "param/param.h" +#include "auth/session_proto.h" + +_PUBLIC_ struct auth_session_info *anonymous_session(TALLOC_CTX *mem_ctx, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx) +{ + NTSTATUS nt_status; + struct auth_session_info *session_info = NULL; + nt_status = auth_anonymous_session_info(mem_ctx, event_ctx, lp_ctx, &session_info); + if (!NT_STATUS_IS_OK(nt_status)) { + return NULL; + } + return session_info; +} + +_PUBLIC_ NTSTATUS auth_anonymous_session_info(TALLOC_CTX *parent_ctx, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct auth_session_info **_session_info) +{ + NTSTATUS nt_status; + struct auth_serversupplied_info *server_info = NULL; + struct auth_session_info *session_info = NULL; + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + + nt_status = auth_anonymous_server_info(mem_ctx, + lp_netbios_name(lp_ctx), + &server_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + /* references the server_info into the session_info */ + nt_status = auth_generate_session_info(parent_ctx, event_ctx, lp_ctx, server_info, &session_info); + talloc_free(mem_ctx); + + NT_STATUS_NOT_OK_RETURN(nt_status); + + session_info->credentials = cli_credentials_init(session_info); + if (!session_info->credentials) { + return NT_STATUS_NO_MEMORY; + } + + cli_credentials_set_conf(session_info->credentials, lp_ctx); + cli_credentials_set_anonymous(session_info->credentials); + + *_session_info = session_info; + + return NT_STATUS_OK; +} + +_PUBLIC_ NTSTATUS auth_anonymous_server_info(TALLOC_CTX *mem_ctx, + const char *netbios_name, + struct auth_serversupplied_info **_server_info) +{ + struct auth_serversupplied_info *server_info; + server_info = talloc(mem_ctx, struct auth_serversupplied_info); + NT_STATUS_HAVE_NO_MEMORY(server_info); + + server_info->account_sid = dom_sid_parse_talloc(server_info, SID_NT_ANONYMOUS); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_sid); + + /* is this correct? */ + server_info->primary_group_sid = dom_sid_parse_talloc(server_info, SID_BUILTIN_GUESTS); + NT_STATUS_HAVE_NO_MEMORY(server_info->primary_group_sid); + + server_info->n_domain_groups = 0; + server_info->domain_groups = NULL; + + /* annoying, but the Anonymous really does have a session key... */ + server_info->user_session_key = data_blob_talloc(server_info, NULL, 16); + NT_STATUS_HAVE_NO_MEMORY(server_info->user_session_key.data); + + server_info->lm_session_key = data_blob_talloc(server_info, NULL, 16); + NT_STATUS_HAVE_NO_MEMORY(server_info->lm_session_key.data); + + /* and it is all zeros! */ + data_blob_clear(&server_info->user_session_key); + data_blob_clear(&server_info->lm_session_key); + + server_info->account_name = talloc_strdup(server_info, "ANONYMOUS LOGON"); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_name); + + server_info->domain_name = talloc_strdup(server_info, "NT AUTHORITY"); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_name); + + server_info->full_name = talloc_strdup(server_info, "Anonymous Logon"); + NT_STATUS_HAVE_NO_MEMORY(server_info->full_name); + + server_info->logon_script = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_script); + + server_info->profile_path = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->profile_path); + + server_info->home_directory = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_directory); + + server_info->home_drive = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_drive); + + server_info->logon_server = talloc_strdup(server_info, netbios_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_server); + + server_info->last_logon = 0; + server_info->last_logoff = 0; + server_info->acct_expiry = 0; + server_info->last_password_change = 0; + server_info->allow_password_change = 0; + server_info->force_password_change = 0; + + server_info->logon_count = 0; + server_info->bad_password_count = 0; + + server_info->acct_flags = ACB_NORMAL; + + server_info->authenticated = false; + + *_server_info = server_info; + + return NT_STATUS_OK; +} + +_PUBLIC_ NTSTATUS auth_generate_session_info(TALLOC_CTX *mem_ctx, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct auth_serversupplied_info *server_info, + struct auth_session_info **_session_info) +{ + struct auth_session_info *session_info; + NTSTATUS nt_status; + + session_info = talloc(mem_ctx, struct auth_session_info); + NT_STATUS_HAVE_NO_MEMORY(session_info); + + session_info->server_info = talloc_reference(session_info, server_info); + + /* unless set otherwise, the session key is the user session + * key from the auth subsystem */ + session_info->session_key = server_info->user_session_key; + + nt_status = security_token_create(session_info, + event_ctx, + lp_ctx, + server_info->account_sid, + server_info->primary_group_sid, + server_info->n_domain_groups, + server_info->domain_groups, + server_info->authenticated, + &session_info->security_token); + NT_STATUS_NOT_OK_RETURN(nt_status); + + session_info->credentials = NULL; + + *_session_info = session_info; + return NT_STATUS_OK; +} + +/** + * prints a struct auth_session_info security token to debug output. + */ +void auth_session_info_debug(int dbg_lev, + const struct auth_session_info *session_info) +{ + if (!session_info) { + DEBUG(dbg_lev, ("Session Info: (NULL)\n")); + return; + } + + security_token_debug(dbg_lev, session_info->security_token); +} + +/** + * Make a server_info struct from the info3 returned by a domain logon + */ +_PUBLIC_ NTSTATUS make_server_info_netlogon_validation(TALLOC_CTX *mem_ctx, + const char *account_name, + uint16_t validation_level, + union netr_Validation *validation, + struct auth_serversupplied_info **_server_info) +{ + struct auth_serversupplied_info *server_info; + struct netr_SamBaseInfo *base = NULL; + int i; + + switch (validation_level) { + case 2: + if (!validation || !validation->sam2) { + return NT_STATUS_INVALID_PARAMETER; + } + base = &validation->sam2->base; + break; + case 3: + if (!validation || !validation->sam3) { + return NT_STATUS_INVALID_PARAMETER; + } + base = &validation->sam3->base; + break; + case 6: + if (!validation || !validation->sam6) { + return NT_STATUS_INVALID_PARAMETER; + } + base = &validation->sam6->base; + break; + default: + return NT_STATUS_INVALID_LEVEL; + } + + server_info = talloc(mem_ctx, struct auth_serversupplied_info); + NT_STATUS_HAVE_NO_MEMORY(server_info); + + /* + Here is where we should check the list of + trusted domains, and verify that the SID + matches. + */ + server_info->account_sid = dom_sid_add_rid(server_info, base->domain_sid, base->rid); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_sid); + + + server_info->primary_group_sid = dom_sid_add_rid(server_info, base->domain_sid, base->primary_gid); + NT_STATUS_HAVE_NO_MEMORY(server_info->primary_group_sid); + + server_info->n_domain_groups = base->groups.count; + if (base->groups.count) { + server_info->domain_groups = talloc_array(server_info, struct dom_sid*, base->groups.count); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_groups); + } else { + server_info->domain_groups = NULL; + } + + for (i = 0; i < base->groups.count; i++) { + server_info->domain_groups[i] = dom_sid_add_rid(server_info, base->domain_sid, base->groups.rids[i].rid); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_groups[i]); + } + + /* Copy 'other' sids. We need to do sid filtering here to + prevent possible elevation of privileges. See: + + http://www.microsoft.com/windows2000/techinfo/administration/security/sidfilter.asp + */ + + if (validation_level == 3) { + struct dom_sid **dgrps = server_info->domain_groups; + size_t sidcount = server_info->n_domain_groups + validation->sam3->sidcount; + size_t n_dgrps = server_info->n_domain_groups; + + if (validation->sam3->sidcount > 0) { + dgrps = talloc_realloc(server_info, dgrps, struct dom_sid*, sidcount); + NT_STATUS_HAVE_NO_MEMORY(dgrps); + + for (i = 0; i < validation->sam3->sidcount; i++) { + dgrps[n_dgrps + i] = talloc_reference(dgrps, validation->sam3->sids[i].sid); + } + } + + server_info->n_domain_groups = sidcount; + server_info->domain_groups = dgrps; + + /* Where are the 'global' sids?... */ + } + + if (base->account_name.string) { + server_info->account_name = talloc_reference(server_info, base->account_name.string); + } else { + server_info->account_name = talloc_strdup(server_info, account_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_name); + } + + server_info->domain_name = talloc_reference(server_info, base->domain.string); + server_info->full_name = talloc_reference(server_info, base->full_name.string); + server_info->logon_script = talloc_reference(server_info, base->logon_script.string); + server_info->profile_path = talloc_reference(server_info, base->profile_path.string); + server_info->home_directory = talloc_reference(server_info, base->home_directory.string); + server_info->home_drive = talloc_reference(server_info, base->home_drive.string); + server_info->logon_server = talloc_reference(server_info, base->logon_server.string); + server_info->last_logon = base->last_logon; + server_info->last_logoff = base->last_logoff; + server_info->acct_expiry = base->acct_expiry; + server_info->last_password_change = base->last_password_change; + server_info->allow_password_change = base->allow_password_change; + server_info->force_password_change = base->force_password_change; + server_info->logon_count = base->logon_count; + server_info->bad_password_count = base->bad_password_count; + server_info->acct_flags = base->acct_flags; + + server_info->authenticated = true; + + /* ensure we are never given NULL session keys */ + + if (all_zero(base->key.key, sizeof(base->key.key))) { + server_info->user_session_key = data_blob(NULL, 0); + } else { + server_info->user_session_key = data_blob_talloc(server_info, base->key.key, sizeof(base->key.key)); + NT_STATUS_HAVE_NO_MEMORY(server_info->user_session_key.data); + } + + if (all_zero(base->LMSessKey.key, sizeof(base->LMSessKey.key))) { + server_info->lm_session_key = data_blob(NULL, 0); + } else { + server_info->lm_session_key = data_blob_talloc(server_info, base->LMSessKey.key, sizeof(base->LMSessKey.key)); + NT_STATUS_HAVE_NO_MEMORY(server_info->lm_session_key.data); + } + + ZERO_STRUCT(server_info->pac_srv_sig); + ZERO_STRUCT(server_info->pac_kdc_sig); + + *_server_info = server_info; + return NT_STATUS_OK; +} + + diff --git a/source4/auth/session.h b/source4/auth/session.h new file mode 100644 index 0000000000..e0805e1584 --- /dev/null +++ b/source4/auth/session.h @@ -0,0 +1,70 @@ +/* + Unix SMB/CIFS implementation. + Process and provide the logged on user's authorization token + Copyright (C) Andrew Bartlett 2001 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef _SAMBA_AUTH_SESSION_H +#define _SAMBA_AUTH_SESSION_H + +struct auth_session_info { + struct security_token *security_token; + struct auth_serversupplied_info *server_info; + DATA_BLOB session_key; + struct cli_credentials *credentials; +}; + +#include "librpc/gen_ndr/netlogon.h" +#include "lib/events/events.h" + +/* Create a security token for a session SYSTEM (the most + * trusted/prvilaged account), including the local machine account as + * the off-host credentials */ +struct auth_session_info *system_session(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx) ; + +/* + * Create a system session, but with anonymous credentials (so we do + * not need to open secrets.ldb) + */ +struct auth_session_info *system_session_anon(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx); + + +NTSTATUS auth_anonymous_server_info(TALLOC_CTX *mem_ctx, + const char *netbios_name, + struct auth_serversupplied_info **_server_info) ; +NTSTATUS auth_generate_session_info(TALLOC_CTX *mem_ctx, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx, + struct auth_serversupplied_info *server_info, + struct auth_session_info **_session_info) ; + +NTSTATUS make_server_info_netlogon_validation(TALLOC_CTX *mem_ctx, + const char *account_name, + uint16_t validation_level, + union netr_Validation *validation, + struct auth_serversupplied_info **_server_info); +NTSTATUS auth_anonymous_session_info(TALLOC_CTX *parent_ctx, + struct event_context *ev_ctx, + struct loadparm_context *lp_ctx, + struct auth_session_info **_session_info); + +struct auth_session_info *anonymous_session(TALLOC_CTX *mem_ctx, + struct event_context *event_ctx, + struct loadparm_context *lp_ctx); + + +#endif /* _SAMBA_AUTH_SESSION_H */ diff --git a/source4/auth/system_session.c b/source4/auth/system_session.c new file mode 100644 index 0000000000..1d227fe468 --- /dev/null +++ b/source4/auth/system_session.c @@ -0,0 +1,304 @@ +/* + Unix SMB/CIFS implementation. + Authentication utility functions + Copyright (C) Andrew Tridgell 1992-1998 + Copyright (C) Andrew Bartlett 2001 + Copyright (C) Jeremy Allison 2000-2001 + Copyright (C) Rafal Szczesniak 2002 + Copyright (C) Stefan Metzmacher 2005 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "includes.h" +#include "libcli/security/security.h" +#include "libcli/auth/libcli_auth.h" +#include "auth/credentials/credentials.h" +#include "param/param.h" +#include "auth/auth.h" /* for auth_serversupplied_info */ +#include "auth/session.h" +#include "auth/system_session_proto.h" + +/** + * Create the SID list for this user. + * + * @note Specialised version for system sessions that doesn't use the SAM. + */ +static NTSTATUS create_token(TALLOC_CTX *mem_ctx, + struct dom_sid *user_sid, + struct dom_sid *group_sid, + int n_groupSIDs, + struct dom_sid **groupSIDs, + bool is_authenticated, + struct security_token **token) +{ + struct security_token *ptoken; + int i; + + ptoken = security_token_initialise(mem_ctx); + NT_STATUS_HAVE_NO_MEMORY(ptoken); + + ptoken->sids = talloc_array(ptoken, struct dom_sid *, n_groupSIDs + 5); + NT_STATUS_HAVE_NO_MEMORY(ptoken->sids); + + ptoken->user_sid = talloc_reference(ptoken, user_sid); + ptoken->group_sid = talloc_reference(ptoken, group_sid); + ptoken->privilege_mask = 0; + + ptoken->sids[0] = ptoken->user_sid; + ptoken->sids[1] = ptoken->group_sid; + + /* + * Finally add the "standard" SIDs. + * The only difference between guest and "anonymous" + * is the addition of Authenticated_Users. + */ + ptoken->sids[2] = dom_sid_parse_talloc(ptoken->sids, SID_WORLD); + NT_STATUS_HAVE_NO_MEMORY(ptoken->sids[2]); + ptoken->sids[3] = dom_sid_parse_talloc(ptoken->sids, SID_NT_NETWORK); + NT_STATUS_HAVE_NO_MEMORY(ptoken->sids[3]); + ptoken->num_sids = 4; + + if (is_authenticated) { + ptoken->sids[4] = dom_sid_parse_talloc(ptoken->sids, SID_NT_AUTHENTICATED_USERS); + NT_STATUS_HAVE_NO_MEMORY(ptoken->sids[4]); + ptoken->num_sids++; + } + + for (i = 0; i < n_groupSIDs; i++) { + size_t check_sid_idx; + for (check_sid_idx = 1; + check_sid_idx < ptoken->num_sids; + check_sid_idx++) { + if (dom_sid_equal(ptoken->sids[check_sid_idx], groupSIDs[i])) { + break; + } + } + + if (check_sid_idx == ptoken->num_sids) { + ptoken->sids[ptoken->num_sids++] = talloc_reference(ptoken->sids, groupSIDs[i]); + } + } + + *token = ptoken; + + /* Shortcuts to prevent recursion and avoid lookups */ + if (ptoken->user_sid == NULL) { + ptoken->privilege_mask = 0; + return NT_STATUS_OK; + } + + if (security_token_is_system(ptoken)) { + ptoken->privilege_mask = ~0; + return NT_STATUS_OK; + } + + if (security_token_is_anonymous(ptoken)) { + ptoken->privilege_mask = 0; + return NT_STATUS_OK; + } + + DEBUG(0, ("Created token was not system or anonymous token!")); + *token = NULL; + return NT_STATUS_INTERNAL_ERROR; +} + +static NTSTATUS generate_session_info(TALLOC_CTX *mem_ctx, + struct auth_serversupplied_info *server_info, + struct auth_session_info **_session_info) +{ + struct auth_session_info *session_info; + NTSTATUS nt_status; + + session_info = talloc(mem_ctx, struct auth_session_info); + NT_STATUS_HAVE_NO_MEMORY(session_info); + + session_info->server_info = talloc_reference(session_info, server_info); + + /* unless set otherwise, the session key is the user session + * key from the auth subsystem */ + session_info->session_key = server_info->user_session_key; + + nt_status = create_token(session_info, + server_info->account_sid, + server_info->primary_group_sid, + server_info->n_domain_groups, + server_info->domain_groups, + server_info->authenticated, + &session_info->security_token); + NT_STATUS_NOT_OK_RETURN(nt_status); + + session_info->credentials = NULL; + + *_session_info = session_info; + return NT_STATUS_OK; +} + + + +/* Create a security token for a session SYSTEM (the most + * trusted/prvilaged account), including the local machine account as + * the off-host credentials + */ +_PUBLIC_ struct auth_session_info *system_session(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx) +{ + NTSTATUS nt_status; + struct auth_session_info *session_info = NULL; + nt_status = auth_system_session_info(mem_ctx, + lp_ctx, + &session_info); + if (!NT_STATUS_IS_OK(nt_status)) { + return NULL; + } + return session_info; +} + +static NTSTATUS _auth_system_session_info(TALLOC_CTX *parent_ctx, + struct loadparm_context *lp_ctx, + bool anonymous_credentials, + struct auth_session_info **_session_info) +{ + NTSTATUS nt_status; + struct auth_serversupplied_info *server_info = NULL; + struct auth_session_info *session_info = NULL; + TALLOC_CTX *mem_ctx = talloc_new(parent_ctx); + + nt_status = auth_system_server_info(mem_ctx, lp_netbios_name(lp_ctx), + &server_info); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return nt_status; + } + + /* references the server_info into the session_info */ + nt_status = generate_session_info(parent_ctx, server_info, &session_info); + talloc_free(mem_ctx); + + NT_STATUS_NOT_OK_RETURN(nt_status); + + session_info->credentials = cli_credentials_init(session_info); + if (!session_info->credentials) { + return NT_STATUS_NO_MEMORY; + } + + cli_credentials_set_conf(session_info->credentials, lp_ctx); + + if (anonymous_credentials) { + cli_credentials_set_anonymous(session_info->credentials); + } else { + cli_credentials_set_machine_account_pending(session_info->credentials, lp_ctx); + } + *_session_info = session_info; + + return NT_STATUS_OK; +} + +/* + Create a system session, but with anonymous credentials (so we do not need to open secrets.ldb) +*/ +_PUBLIC_ struct auth_session_info *system_session_anon(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx) +{ + NTSTATUS nt_status; + struct auth_session_info *session_info = NULL; + nt_status = _auth_system_session_info(mem_ctx, lp_ctx, false, &session_info); + if (!NT_STATUS_IS_OK(nt_status)) { + return NULL; + } + return session_info; +} + + + +_PUBLIC_ NTSTATUS auth_system_session_info(TALLOC_CTX *parent_ctx, + struct loadparm_context *lp_ctx, + struct auth_session_info **_session_info) +{ + return _auth_system_session_info(parent_ctx, + lp_ctx, + lp_parm_bool(lp_ctx, NULL, "system", "anonymous", false), + _session_info); +} + +NTSTATUS auth_system_server_info(TALLOC_CTX *mem_ctx, const char *netbios_name, + struct auth_serversupplied_info **_server_info) +{ + struct auth_serversupplied_info *server_info; + server_info = talloc(mem_ctx, struct auth_serversupplied_info); + NT_STATUS_HAVE_NO_MEMORY(server_info); + + server_info->account_sid = dom_sid_parse_talloc(server_info, SID_NT_SYSTEM); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_sid); + + /* is this correct? */ + server_info->primary_group_sid = dom_sid_parse_talloc(server_info, SID_BUILTIN_ADMINISTRATORS); + NT_STATUS_HAVE_NO_MEMORY(server_info->primary_group_sid); + + server_info->n_domain_groups = 0; + server_info->domain_groups = NULL; + + /* annoying, but the Anonymous really does have a session key, + and it is all zeros! */ + server_info->user_session_key = data_blob_talloc(server_info, NULL, 16); + NT_STATUS_HAVE_NO_MEMORY(server_info->user_session_key.data); + + server_info->lm_session_key = data_blob_talloc(server_info, NULL, 16); + NT_STATUS_HAVE_NO_MEMORY(server_info->lm_session_key.data); + + data_blob_clear(&server_info->user_session_key); + data_blob_clear(&server_info->lm_session_key); + + server_info->account_name = talloc_strdup(server_info, "SYSTEM"); + NT_STATUS_HAVE_NO_MEMORY(server_info->account_name); + + server_info->domain_name = talloc_strdup(server_info, "NT AUTHORITY"); + NT_STATUS_HAVE_NO_MEMORY(server_info->domain_name); + + server_info->full_name = talloc_strdup(server_info, "System"); + NT_STATUS_HAVE_NO_MEMORY(server_info->full_name); + + server_info->logon_script = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_script); + + server_info->profile_path = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->profile_path); + + server_info->home_directory = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_directory); + + server_info->home_drive = talloc_strdup(server_info, ""); + NT_STATUS_HAVE_NO_MEMORY(server_info->home_drive); + + server_info->logon_server = talloc_strdup(server_info, netbios_name); + NT_STATUS_HAVE_NO_MEMORY(server_info->logon_server); + + server_info->last_logon = 0; + server_info->last_logoff = 0; + server_info->acct_expiry = 0; + server_info->last_password_change = 0; + server_info->allow_password_change = 0; + server_info->force_password_change = 0; + + server_info->logon_count = 0; + server_info->bad_password_count = 0; + + server_info->acct_flags = ACB_NORMAL; + + server_info->authenticated = true; + + *_server_info = server_info; + + return NT_STATUS_OK; +} + + diff --git a/source4/auth/tests/bindings.py b/source4/auth/tests/bindings.py new file mode 100644 index 0000000000..b7a5994675 --- /dev/null +++ b/source4/auth/tests/bindings.py @@ -0,0 +1,34 @@ +#!/usr/bin/python + +# Unix SMB/CIFS implementation. +# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. +# + +"""Tests for the Auth Python bindings. + +Note that this just tests the bindings work. It does not intend to test +the functionality, that's already done in other tests. +""" + +import unittest +from samba import auth + +class AuthTests(unittest.TestCase): + def test_system_session(self): + auth.system_session() + + def test_system_session_anon(self): + auth.system_session_anon() |