s3-build: only include memcache.h where needed.
[nivanova/samba-autobuild/.git] / source3 / lib / access.c
index 224ede5968e7e50d438d323dadd1e6136575f7ce..b674144150a348a3445796ab029c8f6bf3652aa3 100644 (file)
-/* 
-This module is an adaption of code from the tcpd-1.4 package written
-by Wietse Venema, Eindhoven University of Technology, The Netherlands.
+/*
+   This module is an adaption of code from the tcpd-1.4 package written
+   by Wietse Venema, Eindhoven University of Technology, The Netherlands.
 
-The code is used here with permission.
+   The code is used here with permission.
 
-The code has been considerably changed from the original. Bug reports
-should be sent to Andrew.Tridgell@anu.edu.au
+   The code has been considerably changed from the original. Bug reports
+   should be sent to samba@samba.org
+
+   Updated for IPv6 by Jeremy Allison (C) 2007.
 */
 
 #include "includes.h"
+#include "memcache.h"
 
-#define ALLOW_PURE_ADDRESSES
+#define NAME_INDEX 0
+#define ADDR_INDEX 1
 
-extern int DEBUGLEVEL;
+/* masked_match - match address against netnumber/netmask */
+static bool masked_match(const char *tok, const char *slash, const char *s)
+{
+       struct sockaddr_storage ss_mask;
+       struct sockaddr_storage ss_tok;
+       struct sockaddr_storage ss_host;
+       char *tok_copy = NULL;
 
-#ifndef        INADDR_NONE
-#define        INADDR_NONE     ((unsigned long)~0)
-#endif
+       if (!interpret_string_addr(&ss_host, s, 0)) {
+               return false;
+       }
 
+       if (*tok == '[') {
+               /* IPv6 address - remove braces. */
+               tok_copy = SMB_STRDUP(tok+1);
+               if (!tok_copy) {
+                       return false;
+               }
+               /* Remove the terminating ']' */
+               tok_copy[PTR_DIFF(slash,tok)-1] = '\0';
+       } else {
+               tok_copy = SMB_STRDUP(tok);
+               if (!tok_copy) {
+                       return false;
+               }
+               /* Remove the terminating '/' */
+               tok_copy[PTR_DIFF(slash,tok)] = '\0';
+       }
 
-#define FROM_ADDRLEN  (4*3+3+1)
-#define Good True
-#define Bad False
+       if (!interpret_string_addr(&ss_tok, tok_copy, 0)) {
+               SAFE_FREE(tok_copy);
+               return false;
+       }
 
-#define CLIENT_MATCH client_match
+       SAFE_FREE(tok_copy);
+
+        if (strlen(slash + 1) > 2) {
+               if (!interpret_string_addr(&ss_mask, slash+1, 0)) {
+                       return false;
+               }
+        } else {
+               char *endp = NULL;
+               unsigned long val = strtoul(slash+1, &endp, 0);
+               if (slash+1 == endp || (endp && *endp != '\0')) {
+                       return false;
+               }
+               if (!make_netmask(&ss_mask, &ss_tok, val)) {
+                       return false;
+               }
+        }
+
+       return same_net((struct sockaddr *)(void *)&ss_host,
+                       (struct sockaddr *)(void *)&ss_tok,
+                       (struct sockaddr *)(void *)&ss_mask);
+}
 
-/* Delimiters for lists of daemons or clients. */
+/* string_match - match string s against token tok */
+static bool string_match(const char *tok,const char *s)
+{
+       size_t     tok_len;
+       size_t     str_len;
+       const char   *cut;
+
+       /* Return true if a token has the magic value "ALL". Return
+        * true if the token is "FAIL". If the token starts with a "."
+        * (domain name), return true if it matches the last fields of
+        * the string. If the token has the magic value "LOCAL",
+        * return true if the string does not contain a "."
+        * character. If the token ends on a "." (network number),
+        * return true if it matches the first fields of the
+        * string. If the token begins with a "@" (netgroup name),
+        * return true if the string is a (host) member of the
+        * netgroup. Return true if the token fully matches the
+        * string. If the token is a netnumber/netmask pair, return
+        * true if the address is a member of the specified subnet.
+        */
+
+       if (tok[0] == '.') {                    /* domain: match last fields */
+               if ((str_len = strlen(s)) > (tok_len = strlen(tok))
+                   && strequal(tok, s + str_len - tok_len)) {
+                       return true;
+               }
+       } else if (tok[0] == '@') { /* netgroup: look it up */
+#ifdef HAVE_NETGROUP
+               DATA_BLOB tmp;
+               char *mydomain = NULL;
+               char *hostname = NULL;
+               bool netgroup_ok = false;
+
+               if (memcache_lookup(
+                           NULL, SINGLETON_CACHE,
+                           data_blob_string_const_null("yp_default_domain"),
+                           &tmp)) {
+
+                       SMB_ASSERT(tmp.length > 0);
+                       mydomain = (tmp.data[0] == '\0')
+                               ? NULL : (char *)tmp.data;
+               }
+               else {
+                       yp_get_default_domain(&mydomain);
+
+                       memcache_add(
+                               NULL, SINGLETON_CACHE,
+                               data_blob_string_const_null("yp_default_domain"),
+                               data_blob_string_const_null(mydomain?mydomain:""));
+               }
+
+               if (!mydomain) {
+                       DEBUG(0,("Unable to get default yp domain. "
+                               "Try without it.\n"));
+               }
+               if (!(hostname = SMB_STRDUP(s))) {
+                       DEBUG(1,("out of memory for strdup!\n"));
+                       return false;
+               }
+
+               netgroup_ok = innetgr(tok + 1, hostname, (char *) 0, mydomain);
+
+               DEBUG(5,("looking for %s of domain %s in netgroup %s gave %s\n",
+                        hostname,
+                        mydomain?mydomain:"(ANY)",
+                        tok+1,
+                        BOOLSTR(netgroup_ok)));
+
+               SAFE_FREE(hostname);
+
+               if (netgroup_ok)
+                       return true;
+#else
+               DEBUG(0,("access: netgroup support is not configured\n"));
+               return false;
+#endif
+       } else if (strequal(tok, "ALL")) {      /* all: match any */
+               return true;
+       } else if (strequal(tok, "FAIL")) {     /* fail: match any */
+               return true;
+       } else if (strequal(tok, "LOCAL")) {    /* local: no dots */
+               if (strchr_m(s, '.') == 0 && !strequal(s, "unknown")) {
+                       return true;
+               }
+       } else if (strequal(tok, s)) {   /* match host name or address */
+               return true;
+       } else if (tok[(tok_len = strlen(tok)) - 1] == '.') {   /* network */
+               if (strncmp(tok, s, tok_len) == 0) {
+                       return true;
+               }
+       } else if ((cut = strchr_m(tok, '/')) != 0) {   /* netnumber/netmask */
+               if ((isdigit(s[0]) && strchr_m(tok, '.') != NULL) ||
+                       (tok[0] == '[' && cut > tok && cut[-1] == ']') ||
+                       ((isxdigit(s[0]) || s[0] == ':') &&
+                               strchr_m(tok, ':') != NULL)) {
+                       /* IPv4/netmask or
+                        * [IPv6:addr]/netmask or IPv6:addr/netmask */
+                       return masked_match(tok, cut, s);
+               }
+       } else if (strchr_m(tok, '*') != 0 || strchr_m(tok, '?')) {
+               return unix_wild_match(tok, s);
+       }
+       return false;
+}
 
-static char sep[] = ", \t";
+/* client_match - match host name and address against token */
+bool client_match(const char *tok, const void *item)
+{
+       const char **client = (const char **)item;
 
-/* Constants to be used in assignments only, not in comparisons... */
+       /*
+        * Try to match the address first. If that fails, try to match the host
+        * name if available.
+        */
 
-#define        YES             1
-#define        NO              0
-#define        FAIL            (-1)
+       if (string_match(tok, client[ADDR_INDEX])) {
+               return true;
+       }
 
-/* Forward declarations. */
-static int list_match(char *list,char *item, int (*match_fn)());
-static int client_match(char *tok,char *item);
-static int string_match(char *tok,char *s);
-static int masked_match(char *tok, char *slash, char *s);
-static int matchname(char *remotehost,struct in_addr  addr);
+       if (strnequal(client[ADDR_INDEX],"::ffff:",7) &&
+                       !strnequal(tok, "::ffff:",7)) {
+               /* client[ADDR_INDEX] is an IPv4 mapped to IPv6, but
+                * the list item is not. Try and match the IPv4 part of
+                * address only. This will happen a lot on IPv6 enabled
+                * systems with IPv4 allow/deny lists in smb.conf.
+                * Bug #5311. JRA.
+                */
+               if (string_match(tok, (client[ADDR_INDEX])+7)) {
+                       return true;
+               }
+       }
 
-/* Size of logical line buffer. */
-#define        BUFLEN 2048
+       if (client[NAME_INDEX][0] != 0) {
+               if (string_match(tok, client[NAME_INDEX])) {
+                       return true;
+               }
+       }
 
+       return false;
+}
 
-/* return true if access should be allowed to a service*/
-BOOL check_access(int snum)
+/* list_match - match an item against a list of tokens with exceptions */
+bool list_match(const char **list,const void *item,
+               bool (*match_fn)(const char *, const void *))
 {
-  extern int Client;
-  extern struct from_host Client_info;
-  char *denyl,*allowl;
-  BOOL ret = False;
-
-  denyl = lp_hostsdeny(snum);
-  if (denyl) denyl = strdup(denyl);
-
-  allowl = lp_hostsallow(snum);
-  if (allowl) allowl = strdup(allowl);
-
-
-  fromhost(Client,&Client_info);
-
-  if ((!denyl || *denyl==0) && (!allowl || *allowl==0))
-    ret = True;
-
-  if (!ret)
-    {
-      if (!fromhost(Client,&Client_info))
-       DEBUG(0,("ERROR: Can't get from_host info\n"));
-      else
-       {
-         if (allow_access(denyl,allowl,&Client_info))
-           {
-             if (snum >= 0)
-               DEBUG(2,("Allowed connection from %s (%s) to %s\n",
-                        Client_info.name,Client_info.addr,
-                        lp_servicename(snum)));
-             ret = True;
-           }
-         else
-           if (snum >= 0)
-             DEBUG(0,("Denied connection from %s (%s) to %s\n",
-                      Client_info.name,Client_info.addr,
-                      lp_servicename(snum)));
+       bool match = false;
+
+       if (!list) {
+               return false;
        }
-    }
 
-  if (denyl) free(denyl);
-  if (allowl) free(allowl);
-  return(ret);
-}
+       /*
+        * Process tokens one at a time. We have exhausted all possible matches
+        * when we reach an "EXCEPT" token or the end of the list. If we do find
+        * a match, look for an "EXCEPT" list and recurse to determine whether
+        * the match is affected by any exceptions.
+        */
+
+       for (; *list ; list++) {
+               if (strequal(*list, "EXCEPT")) {
+                       /* EXCEPT: give up */
+                       break;
+               }
+               if ((match = (*match_fn) (*list, item))) {
+                       /* true or FAIL */
+                       break;
+               }
+       }
+       /* Process exceptions to true or FAIL matches. */
+
+       if (match != false) {
+               while (*list  && !strequal(*list, "EXCEPT")) {
+                       list++;
+               }
+
+               for (; *list; list++) {
+                       if ((*match_fn) (*list, item)) {
+                               /* Exception Found */
+                               return false;
+                       }
+               }
+       }
 
+       return match;
+}
 
 /* return true if access should be allowed */
-BOOL allow_access(char *deny_list,char *allow_list,struct from_host *client)
+static bool allow_access_internal(const char **deny_list,
+                               const char **allow_list,
+                               const char *cname,
+                               const char *caddr)
 {
-  /* if theres no deny list and no allow list then allow access */
-  if ((!deny_list || *deny_list == 0) && (!allow_list || *allow_list == 0))
-    return(True);  
-
-  /* if there is an allow list but no deny list then allow only hosts
-     on the allow list */
-  if (!deny_list || *deny_list == 0)
-    return(list_match(allow_list,(char *)client,CLIENT_MATCH));
-
-  /* if theres a deny list but no allow list then allow
-     all hosts not on the deny list */
-  if (!allow_list || *allow_list == 0)
-    return(!list_match(deny_list,(char *)client,CLIENT_MATCH));
-
-  /* if there are both type of list then allow all hosts on the allow list */
-  if (list_match(allow_list,(char *)client,CLIENT_MATCH))
-    return (True);
-
-  /* if there are both type of list and it's not on the allow then
-     allow it if its not on the deny */
-  if (list_match(deny_list,(char *)client,CLIENT_MATCH))
-    return (False);
-
-  return (True);
-}
+       const char *client[2];
+
+       client[NAME_INDEX] = cname;
+       client[ADDR_INDEX] = caddr;
+
+       /* if it is loopback then always allow unless specifically denied */
+       if (strcmp(caddr, "127.0.0.1") == 0 || strcmp(caddr, "::1") == 0) {
+               /*
+                * If 127.0.0.1 matches both allow and deny then allow.
+                * Patch from Steve Langasek vorlon@netexpress.net.
+                */
+               if (deny_list &&
+                       list_match(deny_list,client,client_match) &&
+                               (!allow_list ||
+                               !list_match(allow_list,client, client_match))) {
+                       return false;
+               }
+               return true;
+       }
 
-/* list_match - match an item against a list of tokens with exceptions */
-/* (All modifications are marked with the initials "jkf") */
-static int list_match(char *list,char *item, int (*match_fn)())
-{
-    char   *tok;
-    char   *listcopy;          /* jkf */
-    int     match = NO;
-
-    /*
-     * jkf@soton.ac.uk -- 31 August 1994 -- Stop list_match()
-     * overwriting the list given as its first parameter.
-     */
-
-    /* jkf -- can get called recursively with NULL list */
-    listcopy = (list == 0) ? (char *)0 : strdup(list);
-
-    /*
-     * Process tokens one at a time. We have exhausted all possible matches
-     * when we reach an "EXCEPT" token or the end of the list. If we do find
-     * a match, look for an "EXCEPT" list and recurse to determine whether
-     * the match is affected by any exceptions.
-     */
-
-    for (tok = strtok(listcopy, sep); tok ; tok = strtok(NULL, sep)) {
-       if (strcasecmp(tok, "EXCEPT") == 0)     /* EXCEPT: give up */
-           break;
-       if ((match = (*match_fn) (tok, item)))  /* YES or FAIL */
-           break;
-    }
-    /* Process exceptions to YES or FAIL matches. */
-
-    if (match != NO) {
-       while ((tok = strtok((char *) 0, sep)) && strcasecmp(tok, "EXCEPT"))
-            /* VOID */ ;
-       if (tok == 0 || list_match((char *) 0, item, match_fn) == NO) {
-           if (listcopy != 0) free(listcopy); /* jkf */
-           return (match);
+       /* if theres no deny list and no allow list then allow access */
+       if ((!deny_list || *deny_list == 0) &&
+           (!allow_list || *allow_list == 0)) {
+               return true;
        }
-    }
 
-    if (listcopy != 0) free(listcopy); /* jkf */
-    return (NO);
-}
+       /* if there is an allow list but no deny list then allow only hosts
+          on the allow list */
+       if (!deny_list || *deny_list == 0) {
+               return(list_match(allow_list,client,client_match));
+       }
 
+       /* if theres a deny list but no allow list then allow
+          all hosts not on the deny list */
+       if (!allow_list || *allow_list == 0) {
+               return(!list_match(deny_list,client,client_match));
+       }
 
-/* client_match - match host name and address against token */
-static int client_match(char *tok,char *item)
-{
-    struct from_host *client = (struct from_host *) item;
-    int     match;
-
-    /*
-     * Try to match the address first. If that fails, try to match the host
-     * name if available.
-     */
-
-    if ((match = string_match(tok, client->addr)) == 0)
-       if (client->name[0] != 0)
-           match = string_match(tok, client->name);
-    return (match);
-}
+       /* if there are both types of list then allow all hosts on the
+           allow list */
+       if (list_match(allow_list,(const char *)client,client_match)) {
+               return true;
+       }
 
-/* string_match - match string against token */
-static int string_match(char *tok,char *s)
-{
-    int     tok_len;
-    int     str_len;
-    char   *cut;
-
-    /*
-     * Return YES if a token has the magic value "ALL". Return FAIL if the
-     * token is "FAIL". If the token starts with a "." (domain name), return
-     * YES if it matches the last fields of the string. If the token has the
-     * magic value "LOCAL", return YES if the string does not contain a "."
-     * character. If the token ends on a "." (network number), return YES if
-     * it matches the first fields of the string. If the token begins with a
-     * "@" (netgroup name), return YES if the string is a (host) member of
-     * the netgroup. Return YES if the token fully matches the string. If the
-     * token is a netnumber/netmask pair, return YES if the address is a
-     * member of the specified subnet.
-     */
-
-    if (tok[0] == '.') {                       /* domain: match last fields */
-       if ((str_len = strlen(s)) > (tok_len = strlen(tok))
-           && strcasecmp(tok, s + str_len - tok_len) == 0)
-           return (YES);
-    } else if (tok[0] == '@') {                        /* netgroup: look it up */
-#ifdef NETGROUP
-      static char *mydomain = NULL;
-      char *hostname = NULL;
-      BOOL netgroup_ok = False;
-
-      if (!mydomain) yp_get_default_domain(&mydomain);
-
-      if (!(hostname = strdup(s))) {
-       DEBUG(1,("out of memory for strdup!\n"));
-       return NO;
-      }
-
-      netgroup_ok = innetgr(tok + 1, hostname, (char *) 0, mydomain);
-
-      DEBUG(5,("looking for %s of domain %s in netgroup %s gave %s\n", 
-              hostname,
-              mydomain, 
-              tok+1,
-              BOOLSTR(netgroup_ok)));
-
-#ifdef NETGROUP_INSECURE
-      /* if you really want netgroups that match non qualified names
-        then define NETGROUP_INSECURE. It can, however, be a big
-        security hole */
-      {
-       char        *clnt_domain;
-       if (!netgroup_ok && (clnt_domain=strchr(hostname,'.'))) {
-         *clnt_domain++ = '\0';
-         netgroup_ok = innetgr(tok + 1, hostname, (char *) 0, mydomain);
+       /* if there are both types of list and it's not on the allow then
+          allow it if its not on the deny */
+       if (list_match(deny_list,(const char *)client,client_match)) {
+               return false;
        }
-      }
-#endif
 
-      free(hostname);
-      
-      if (netgroup_ok) return(YES);
-#else
-      DEBUG(0,("access: netgroup support is not configured"));
-      return (NO);
-#endif
-    } else if (strcasecmp(tok, "ALL") == 0) {  /* all: match any */
-       return (YES);
-    } else if (strcasecmp(tok, "FAIL") == 0) { /* fail: match any */
-       return (FAIL);
-    } else if (strcasecmp(tok, "LOCAL") == 0) {        /* local: no dots */
-       if (strchr(s, '.') == 0 && strcasecmp(s, "unknown") != 0)
-           return (YES);
-    } else if (!strcasecmp(tok, s)) {  /* match host name or address */
-       return (YES);
-    } else if (tok[(tok_len = strlen(tok)) - 1] == '.') {      /* network */
-       if (strncmp(tok, s, tok_len) == 0)
-           return (YES);
-    } else if ((cut = strchr(tok, '/')) != 0) {        /* netnumber/netmask */
-       if (isdigit(s[0]) && masked_match(tok, cut, s))
-           return (YES);
-    }
-    return (NO);
+       return true;
 }
 
-/* masked_match - match address against netnumber/netmask */
-static int masked_match(char *tok, char *slash, char *s)
+/* return true if access should be allowed */
+bool allow_access(const char **deny_list,
+               const char **allow_list,
+               const char *cname,
+               const char *caddr)
 {
-    unsigned long net;
-    unsigned long mask;
-    unsigned long addr;
-
-    if ((addr = interpret_addr(s)) == INADDR_NONE)
-       return (NO);
-    *slash = 0;
-    net = interpret_addr(tok);
-    *slash = '/';
-    if (net == INADDR_NONE || (mask = interpret_addr(slash + 1)) == INADDR_NONE) {
-       DEBUG(0,("access: bad net/mask access control: %s", tok));
-       return (NO);
-    }
-    return ((addr & mask) == net);
-}
+       bool ret;
+       char *nc_cname = smb_xstrdup(cname);
+       char *nc_caddr = smb_xstrdup(caddr);
 
+       ret = allow_access_internal(deny_list, allow_list, nc_cname, nc_caddr);
 
-/* fromhost - find out what is at the other end of a socket */
-BOOL fromhost(int sock,struct from_host *f)
-{
-    static struct sockaddr sa;
-    struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
-    struct hostent *hp;
-    int     length = sizeof(sa);
-    static char addr_buf[FROM_ADDRLEN];
-    static char name_buf[MAXHOSTNAMELEN];
-    BOOL   takeAddressAsHostname = False;
-
-    if (getpeername(sock, &sa, &length) < 0) 
-      {
-       DEBUG(0,("getpeername failed\n"));
-       return(False);
-      }
-
-    f->sin = sockin;
-    f->addr = strcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));
-
-    /* Look up the remote host name. */
-    if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
-                           sizeof(sockin->sin_addr),
-                           AF_INET)) == 0) {
-      DEBUG(1,("Gethostbyaddr failed for %s\n",addr_buf));
-#ifdef ALLOW_PURE_ADDRESSES
-      takeAddressAsHostname = True;
-#else
-      return(False);
-#endif
-    }
-
-    /* Save the host name. A later gethostbyxxx() call may clobber it. */
-    f->name = StrnCpy(name_buf,
-                      takeAddressAsHostname? f->addr : hp->h_name,
-                      sizeof(name_buf) - 1);
-
-    /*
-     * Verify that the host name does not belong to someone else. If host
-     * name verification fails, pretend that the host name lookup failed.
-     */
-    if (!takeAddressAsHostname && !matchname(f->name, sockin->sin_addr))
-      {
-       DEBUG(0,("Matchname failed\n"));
-       return(False);
-      }
-
-    return(True);      
-}
+       DEBUG(ret ? 3 : 0,
+             ("%s connection from %s (%s)\n",
+              ret ? "Allowed" : "Denied", nc_cname, nc_caddr));
 
-/* matchname - determine if host name matches IP address */
-static int matchname(char *remotehost,struct in_addr  addr)
-{
-  struct hostent *hp;
-  int     i;
-  
-  if ((hp = Get_Hostbyname(remotehost)) == 0) {
-    DEBUG(0,("Get_Hostbyname(%s): lookup failure", remotehost));
-    return (Bad);
-  } 
-
-    /*
-     * Make sure that gethostbyname() returns the "correct" host name.
-     * Unfortunately, gethostbyname("localhost") sometimes yields
-     * "localhost.domain". Since the latter host name comes from the
-     * local DNS, we just have to trust it (all bets are off if the local
-     * DNS is perverted). We always check the address list, though.
-     */
-  
-  if (strcasecmp(remotehost, hp->h_name)
-      && strcasecmp(remotehost, "localhost")) {
-    DEBUG(0,("host name/name mismatch: %s != %s",
-         remotehost, hp->h_name));
-    return (Bad);
-  }
-       
-  /* Look up the host address in the address list we just got. */
-  for (i = 0; hp->h_addr_list[i]; i++) {
-    if (memcmp(hp->h_addr_list[i], (caddr_t) & addr, sizeof(addr)) == 0)
-      return (Good);
-  }
-
-  /*
-   * The host name does not map to the original host address. Perhaps
-   * someone has compromised a name server. More likely someone botched
-   * it, but that could be dangerous, too.
-   */
-  
-  DEBUG(0,("host name/address mismatch: %s != %s",
-       inet_ntoa(addr), hp->h_name));
-  return (Bad);
+       SAFE_FREE(nc_cname);
+       SAFE_FREE(nc_caddr);
+       return ret;
 }
-
-