libclamav/phishcheck.c
bd912dd8
 /*
  *  Detect phishing, based on URL spoofing detection.
  *
2023340a
  *  Copyright (C) 2007-2008 Sourcefire, Inc.
  *
  *  Authors: Török Edvin
bd912dd8
  *
  *  This program is free software; you can redistribute it and/or modify
2023340a
  *  it under the terms of the GNU General Public License version 2 as
38a00199
  *  published by the Free Software Foundation.
bd912dd8
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  *  MA 02110-1301, USA.
  */
 
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
 #ifdef CL_THREAD_SAFE
 #ifndef _REENTRANT
 #define _REENTRANT
 #endif
 #endif
 
 #include <stdio.h>
 #include <string.h>
 #include <ctype.h>
 
43ecd9a1
 #include "clamav.h"
2e11bcdf
 #include "cltypes.h"
bd912dd8
 #include "others.h"
 #include "htmlnorm.h"
 #include "phishcheck.h"
 #include "phish_domaincheck_db.h"
43ecd9a1
 #include "phish_whitelist.h"
b611b5ff
 #include "regex_list.h"
bd912dd8
 #include "iana_tld.h"
2e11bcdf
 #include "iana_cctld.h"
d66b8812
 #include "scanners.h"
4e46d65d
 #include "sha256.h"
b43205cb
 #include <assert.h>
43ecd9a1
 
b94e66c4
 #include "mpool.h"
 
bd912dd8
 #define DOMAIN_REAL 1
 #define DOMAIN_DISPLAY 0
 
 #define PHISHY_USERNAME_IN_URL 1
 #define PHISHY_NUMERIC_IP      2
43ecd9a1
 #define REAL_IS_MAILTO	       4
bd912dd8
 /* this is just a flag, so that the displayed url will be parsed as mailto too, for example
  * <a href='mailto:somebody@yahoo.com'>to:somebody@yahoo.com</a>*/
5c23fc2f
 #define DOMAIN_LISTED		 8
 #define PHISHY_CLOAKED_NULL	16
bd912dd8
 
6f60f808
 
bd912dd8
 /*
5c23fc2f
 * Phishing design documentation,
bd912dd8
 (initially written at http://wiki.clamav.net/index.php/phishing_design as discussed with aCaB)
 
813864ce
 TODO: update this doc whenever behaviour changes
bd912dd8
 
 phishingCheck() determines if @displayedLink is  a legit representation of @realLink.
 
 Steps:
 
813864ce
 1. if _realLink_ == _displayLink_ => CLEAN
bd912dd8
 
 2. url cleanup (normalization)
 - whitespace elimination
813864ce
  strip all spaces, and leading and trailing garbage.
  When matching we have to keep in account whether we stripped any spaces or not.
  See str_fixup_spaces.
bd912dd8
 - html entity conversion
813864ce
 - handle hex-encoded characters
bd912dd8
 - convert hostname to lowercase
 - normalize \ to /
 
 3. Matched the urls against a _whitelist_:
 a _realLink_, _displayedLink_ pair is matched against the _whitelist_.
 the _whitelist_ is a list of pairs of realLink, displayedLink. Any of the elements of those pairs can be a _regex_.
  if url *is found* in _whitelist_ --> *CLEAN*
 
813864ce
 4. URL is looked up in the _domainlist_
bd912dd8
 The _domainlist_ is a list of pairs of realLink, displayedLink (any of which can be regex).
 This is the list of domains we do phishing detection for (such as ebay,paypal,chase,....)
 We can't decide to stop processing here or not, so we just set a flag.
 
 Note(*!*): the flags are modified by the the domainlist checker. If domain is found, then the flags associated with it filter the default compile-time flags.
 
 5. _Hostname_ is extracted from the _displayed URL_.
 It is checked against the _whitelist_, and _domainlist_.
 
 6. Now we know if we want to stop processing.
 If we are only scanning domains in the _domainlist_ (default behaviour), and the url/domain
 isn't found in it, we return (and mark url as not_list/clean).
 If we scan all domains, then the domainlist isn't even checked.
 
 7. URL cloak check.
 check for %00, and hex-encoded IPs in URL.
 
 8. Skip empty displayedURLs
 
 9. SSL mismatch detection.
 Checks if realLink is http, but displayedLink is https or viceversa.
 (by default the SSL detection is done for hrefs only, not for imgs)
 
 10. Hostname of real URL is extracted.
 
 12. Numeric IP detection.
 If url is a numeric IP, then -> phish.
 Maybe we should do DNS lookup?
 
 13. isURL(displayedLink).
 Checks if displayedLink is really a url.
 if not -> clean
 
 14. Hostnames of real, displayedLink are compared. If equal -> clean
 
 15. Extract domain names, and compare. If equal -> clean
 
 16. Do DNS lookups/reverse lookups. Disabled now (too much load/too many lookups). *
 
 For the Whitelist(.wdb)/Domainlist(.pdb) format see regex_list.c (search for Flags)
  *
  */
ec481027
 
 /* Constant strings and tables */ 
bd912dd8
 static char empty_string[]="";
19b3e182
 
ec481027
 static const char dotnet[] = ".net";
 static const char adonet[] = "ado.net";
 static const char aspnet[] = "asp.net";
97ba1aed
 /* ; is replaced by ' ' so omit it here*/
 static const char lt[]="&lt";
 static const char gt[]="&gt";
fc83da82
 static const char src_text[] = "src";
 static const char href_text[] = "href";
43ecd9a1
 static const char mailto[] = "mailto:";
2e11bcdf
 static const char mailto_proto[] = "mailto://";
f2b71eb9
 static const char https[]="https:";
 static const char http[]="http:";
 static const char ftp[] = "ftp:";
43ecd9a1
 
fc83da82
 static const size_t href_text_len = sizeof(href_text);
 static const size_t src_text_len = sizeof(src_text);
ec481027
 static const size_t dotnet_len = sizeof(dotnet)-1;
 static const size_t adonet_len = sizeof(adonet)-1;
 static const size_t aspnet_len = sizeof(aspnet)-1;
 static const size_t lt_len = sizeof(lt)-1;
 static const size_t gt_len = sizeof(gt)-1;
43ecd9a1
 static const size_t mailto_len = sizeof(mailto)-1;
2e11bcdf
 static const size_t mailto_proto_len = sizeof(mailto_proto)-1;
43ecd9a1
 static const size_t https_len  = sizeof(https)-1;
2e11bcdf
 static const size_t http_len  = sizeof(http)-1;
 static const size_t ftp_len  = sizeof(ftp)-1;
ec481027
 
 /* for urls, including mailto: urls, and (broken) http:www... style urls*/
 /* refer to: http://www.w3.org/Addressing/URL/5_URI_BNF.html
  * Modifications: don't allow empty domains/subdomains, such as www..com <- that is no url
  * So the 'safe' char class has been split up
  * */
 /* character classes */
 #define URI_digit	"0-9"
 #define URI_IP_digits "["URI_digit"]{1,3}"
f12c2e68
 #define URI_path_start "[/?:]?"
 #define URI_numeric_path URI_IP_digits"(\\."URI_IP_digits"){3}"URI_path_start
2e11bcdf
 #define URI_numeric_URI "(http|https|ftp:(//)?)?"URI_numeric_path
f12c2e68
 #define URI_numeric_fragmentaddress URI_numeric_URI
ec481027
 
 
 /*Warning: take care when modifying this regex, it has been tweaked, and tuned, just don't break it please.
  * there is fragmentaddress1, and 2  to work around the ISO limitation of 509 bytes max length for string constants*/
 static const char numeric_url_regex[] = "^ *"URI_numeric_fragmentaddress" *$";
 
 /* generated by contrib/phishing/generate_tables.c */
 static const short int hextable[256] = {
813864ce
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
ec481027
        0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
 };
 
 /* Prototypes*/
43ecd9a1
 static void string_init_c(struct string* dest,char* data);
75fe1251
 static int string_assign_concatenated(struct string* dest, const char* prefix, const char* begin, const char* end);
43ecd9a1
 static void string_assign_null(struct string* dest);
 static char *rfind(char *start, char c, size_t len);
 static char hex2int(const unsigned char* src);
fc83da82
 static enum phish_status phishingCheck(const struct cl_engine* engine,struct url_check* urls);
 static const char* phishing_ret_toString(enum phish_status rc);
bd912dd8
 
fc83da82
 static void url_check_init(struct url_check* urls)
bd912dd8
 {
7da9bd64
 	string_init_c(&urls->realLink, NULL);
 	string_init_c(&urls->displayLink, NULL);
 	string_init_c(&urls->pre_fixup.pre_displayLink, NULL);
bd912dd8
 }
 
 /* string reference counting implementation,
  * so that: we don't have to keep in mind who allocated what, and when needs to be freed,
34c9315f
  * and thus we won't leak memory*/
bd912dd8
 
fc83da82
 static void string_free(struct string* str)
bd912dd8
 {
5c23fc2f
 	for(;;){
bd912dd8
 		str->refcount--;
 		if(!str->refcount) {
 			if(str->ref)/* don't free, this is a portion of another string */
 				str=str->ref;/* try to free that one*/
 			else {
15b08fbb
 				if(str->data)
 					free(str->data);
bd912dd8
 				break;
 			}
 		}
 		else break;
5c23fc2f
 	}
bd912dd8
 }
 
43ecd9a1
 /* always use the string_assign when assigning to a string, this makes sure the old one's reference count is incremented*/
fc83da82
 static void string_assign(struct string* dest,struct string* src)
bd912dd8
 {
 	string_free(dest);
 	src->refcount++;
 	dest->data=src->data;
 	dest->refcount=1;
 	dest->ref=src;
 }
 
 /* data will be freed when string freed */
fc83da82
 /* it doesn't free old string, use only for initialization
bd912dd8
  * Doesn't allow NULL pointers, they are replaced by pointer to empty string
  * */
43ecd9a1
 static void string_init_c(struct string* dest,char* data)
bd912dd8
 {
7da9bd64
 	dest->refcount = data ? 1 : 0;
bd912dd8
 	dest->data = data ? data : empty_string;
 	dest->ref = NULL;
 }
 
75fe1251
 /* assigns to @dest the string made from concatenating @prefix with the string between @begin and @end */
 static int string_assign_concatenated(struct string* dest, const char* prefix, const char* begin, const char* end)
 {
 	const size_t prefix_len = strlen(prefix);
 	char* ret = cli_malloc(prefix_len + end - begin + 1);
 	if(!ret)
 		return CL_EMEM;
 	strncpy(ret, prefix, prefix_len);
 	strncpy(ret+prefix_len, begin, end-begin);
 	ret[prefix_len+end-begin]='\0';
 	string_free(dest);
 	string_init_c(dest, ret);
 	return CL_SUCCESS;
 }
 
bd912dd8
 /* make a copy of the string between start -> end*/
fc83da82
 static int string_assign_dup(struct string* dest,const char* start,const char* end)
bd912dd8
 {
75fe1251
 	char* ret  = cli_malloc(end-start+1);
15b08fbb
 	if(!ret)
 		return CL_EMEM;
bd912dd8
 	strncpy(ret,start,end-start);
 	ret[end-start]='\0';
 
 	string_free(dest);
75fe1251
 	string_init_c(dest, ret);
15b08fbb
 	return CL_SUCCESS;
bd912dd8
 }
 
43ecd9a1
 static void string_assign_null(struct string* dest)
bd912dd8
 {
7da9bd64
 	if(dest) {
 		string_free(dest);
 		dest->data=empty_string;
 		dest->refcount=-1;/* don't free it! */
 		dest->ref=NULL;
 	}
bd912dd8
 }
 
 /* this string uses portion of another string*/
fc83da82
 static void string_assign_ref(struct string* dest,struct string* ref,char* data)
bd912dd8
 {
 	string_free(dest);
 	ref->refcount++;
 	dest->data=data;
 	dest->refcount=1;
 	dest->ref=ref;
 }
 
fc83da82
 static void free_if_needed(struct url_check* url)
bd912dd8
 {
 	string_free(&url->realLink);
 	string_free(&url->displayLink);
7da9bd64
 	string_free(&url->pre_fixup.pre_displayLink);
bd912dd8
 }
 
ec481027
 static int build_regex(regex_t* preg,const char* regex,int nosub)
bd912dd8
 {
 	int rc;
4c748c36
 	cli_dbgmsg("Phishcheck: Compiling regex: %s\n",regex);
53ff1b04
 	rc = cli_regcomp(preg,regex,REG_EXTENDED|REG_ICASE|(nosub ? REG_NOSUB :0));
bd912dd8
 	if(rc) {
813864ce
 
22e811e4
 #ifdef	C_WINDOWS
43ecd9a1
 		cli_errmsg("Phishcheck: Error in compiling regex, disabling phishing checks\n");
22e811e4
 #else
53ff1b04
 		size_t buflen =	cli_regerror(rc,preg,NULL,0);
22e811e4
 		char *errbuf = cli_malloc(buflen);
813864ce
 
22e811e4
 		if(errbuf) {
53ff1b04
 			cli_regerror(rc,preg,errbuf,buflen);
43ecd9a1
 			cli_errmsg("Phishcheck: Error in compiling regex:%s\nDisabling phishing checks\n",errbuf);
22e811e4
 			free(errbuf);
 		} else
43ecd9a1
 			cli_errmsg("Phishcheck: Error in compiling regex, disabling phishing checks. Additionally an Out-of-memory error was encountered while generating a detailed error message\n");
22e811e4
 #endif
bd912dd8
 		return 1;
 	}
15b08fbb
 	return CL_SUCCESS;
bd912dd8
 }
 
 /* allocates memory */
08402afa
 static int get_host(const char* URL,int isReal,int* phishy,const char **hstart, const char **hend)
bd912dd8
 {
15b08fbb
 	int rc,ismailto = 0;
bd912dd8
 	const char* start;
 	const char* end=NULL;
 	if(!URL) {
b5341ac0
 		*hstart=*hend=NULL;
9db68157
 		return 0;
bd912dd8
 	}
 	start = strstr(URL,"://");
 	if(!start) {
43ecd9a1
 		if(!strncmp(URL,mailto,mailto_len)) {
 			start = URL + mailto_len;
bd912dd8
 			ismailto = 1;
 		}
 		else if (!isReal && *phishy&REAL_IS_MAILTO) {
 			/* it is not required to use mailto: in the displayed url, they might use to:, or whatever */
 			end = URL+strlen(URL)+1;
 			start = URL + strcspn(URL,": ")+1;
5c23fc2f
 			if (start==end)
bd912dd8
 				start = URL;
 			ismailto = 1;
 		}
 		else {
 			start=URL;/*URL without protocol*/
 			if(isReal)
4c748c36
 				cli_dbgmsg("Phishcheck: Real URL without protocol: %s\n",URL);
bd912dd8
 			else ismailto=2;/*no-protocol, might be mailto, @ is no problem*/
 		}
 	}
5c23fc2f
 	else
 		start += 3;	/* :// */
 
 	if(!ismailto || !isReal) {
43ecd9a1
 		const char *realhost,*tld;
5c23fc2f
 
bd912dd8
 		do {
5c23fc2f
 			end  = start + strcspn(start,":/?");
bd912dd8
 			realhost = strchr(start,'@');
5c23fc2f
 
43ecd9a1
 			if(realhost == NULL || (start!=end && realhost>end)) {
 				/*don't check beyond end of hostname*/ 
5c23fc2f
 				break;
bd912dd8
 			}
43ecd9a1
 
 			tld = strrchr(realhost,'.');
b3b6f0e4
 			rc = tld ? !!in_tld_set(tld,strlen(tld)) : 0;
43ecd9a1
 			if(rc < 0)
 				return rc;
 			if(rc)
 				*phishy |= PHISHY_USERNAME_IN_URL;/* if the url contains a username that is there just to fool people,
81040d73
 			     					     like http://banksite@example.com/ */
43ecd9a1
 			start = realhost+1;/*skip the username*/
bd912dd8
 		} while(realhost);/*skip over multiple @ characters, text following last @ character is the real host*/
 	}
43ecd9a1
 	else if (ismailto && isReal)
bd912dd8
 		*phishy |= REAL_IS_MAILTO;
 
 	if(!end) {
43ecd9a1
 		end  = start + strcspn(start,":/?");/*especially important for mailto:somebody@yahoo.com?subject=...*/
5c23fc2f
 		if(!end)
bd912dd8
 			end  = start + strlen(start);
 	}
b5341ac0
 	*hstart = start;
 	*hend = end;
9db68157
 	return 0;
bd912dd8
 }
 
 
 /*
  * memrchr isn't standard, so I use this
  */
5c23fc2f
 static char *
e2f30fd2
 rfind(char *start, char c, size_t len)
bd912dd8
 {
e2f30fd2
 	char *p;
5c23fc2f
 
 	if(start == NULL)
 		return NULL;
 
 	for(p = start + len; (p >= start) && (*p != c); p--)
 		;
 	return (p < start) ? NULL : p;
bd912dd8
 }
 
08402afa
 static void get_domain(struct string* dest,struct string* host)
bd912dd8
 {
 	char* domain;
 	char* tld = strrchr(host->data,'.');
 	if(!tld) {
43ecd9a1
 		cli_dbgmsg("Phishcheck: Encountered a host without a tld? (%s)\n",host->data);
bd912dd8
 		string_assign(dest,host);
 		return;
 	}
2e11bcdf
 	if(in_cctld_set(tld+1, strlen(tld+1))) {
43ecd9a1
 		const char* countrycode = tld+1;
bd912dd8
 		tld = rfind(host->data,'.',tld-host->data-1);
 		if(!tld) {
43ecd9a1
 			cli_dbgmsg("Phishcheck: Weird, a name with only 2 levels (%s)\n",
1d65e9a3
 				host->data);
bd912dd8
 			string_assign(dest,host);
 			return;
 		}
2e11bcdf
 		if(!in_tld_set(tld+1, countrycode-tld-2)) {
bd912dd8
 			string_assign_ref(dest,host,tld+1);
 			return;/*it was a name like: subdomain.domain.uk, return domain.uk*/
 		}
 	}
 	/*we need to strip one more level, this is the actual domain*/
 	domain = rfind(host->data,'.',tld-host->data-1);
 	if(!domain) {
 		string_assign(dest,host);
 		return;/* it was like sourceforge.net?*/
 	}
 	string_assign_ref(dest,host,domain+1);
 }
 
fc83da82
 static int isNumeric(const char* host)
bd912dd8
 {
 	int len = strlen(host);
 	int a,b,c,d,n=0;
 	/* 1.2.3.4 -> 7*/
 	/* 127.127.127.127 -> 15*/
 	if(len<7 || len>15)
5c23fc2f
 		return 0;
bd912dd8
 	sscanf(host,"%d.%d.%d.%d%n",&a,&b,&c,&d,&n);
 	if(n==len)
 		if(a>=0 && a<=256 && b>=0 && b<=256 && c>=0 && c<=256 && d>=0 && d<=256)
 			return 1;
 	return 0;
 }
 
fc83da82
 static int isSSL(const char* URL)
bd912dd8
 {
43ecd9a1
 	return URL ? !strncmp(https,URL,https_len) : 0;
bd912dd8
 }
 
5c23fc2f
 /* deletes @what from the string @begin.
bd912dd8
  * @what_len: length of @what, excluding the terminating \0 */
5c23fc2f
 static void
 str_hex_to_char(char **begin, const char **end)
bd912dd8
 {
4e46d65d
 	char *firsthex, *sbegin_;
5c23fc2f
 	char *sbegin = *begin;
 	const char *str_end = *end;
 
47a6df99
 	if(str_end <= &sbegin[1])
5c23fc2f
 		return;
 
bd912dd8
 	/* convert leading %xx*/
 	if (sbegin[0] == '%') {
 		sbegin[2] = hex2int((unsigned char*)sbegin+1);
 		sbegin += 2;
 	}
 	*begin = sbegin++;
4e46d65d
 	do {
 	    sbegin_ = sbegin;
 	    firsthex = NULL;
 	    while(sbegin+3 <= str_end) {
 		if (sbegin+3<=str_end && sbegin[0]=='%') {
 		    const char* src = sbegin+3;
 		    if (isxdigit(sbegin[1]) && isxdigit(sbegin[2])) {
bd912dd8
 			*sbegin = hex2int((unsigned char*)sbegin+1);
4e46d65d
 			if (*sbegin == '%' && !firsthex)
 			    firsthex = sbegin;
bd912dd8
 			/* move string */
 			memmove(sbegin+1,src,str_end-src+1);
 			str_end -= 2;
4e46d65d
 		    }
bd912dd8
 		}
 		sbegin++;
4e46d65d
 	    }
 	    sbegin = sbegin_;
 	} while (firsthex);
bd912dd8
 	*end = str_end;
 }
5c23fc2f
 
 /*
  * deletes @what from the string @begin.
  * @what_len: length of @what, excluding the terminating \0
  */
 static void
 str_strip(char **begin, const char **end, const char *what, size_t what_len)
bd912dd8
 {
5c23fc2f
 	char *sbegin = *begin;
 	const char *str_end = *end;
 	const char *str_end_what;
bd912dd8
 	size_t cmp_len = what_len;
5c23fc2f
 
15b08fbb
 	if(begin == NULL || str_end <= sbegin)
5c23fc2f
 		return;
 
 	/*if(str_end < (sbegin + what_len))
 		return;*/
 	if(strlen(sbegin) < what_len)
bd912dd8
 		return;
5c23fc2f
 
bd912dd8
 	/* strip leading @what */
 	while(cmp_len && !strncmp(sbegin,what,cmp_len)) {
 		sbegin += what_len;
5c23fc2f
 
bd912dd8
 		if(cmp_len > what_len)
 			cmp_len -= what_len;
5c23fc2f
 		else
 			cmp_len = 0;
bd912dd8
 	}
5c23fc2f
 
bd912dd8
 	/* strip trailing @what */
23865d0f
 	if(what_len <= (size_t)(str_end - sbegin)) {
f15a8c49
 		str_end_what = str_end - what_len + 1;
5c23fc2f
 		while((str_end_what > sbegin) &&
 		      (strncmp(str_end_what, what, what_len) == 0)) {
 			str_end -= what_len;
 			str_end_what -= what_len;
 		}
bd912dd8
 	}
5c23fc2f
 
bd912dd8
 	*begin = sbegin++;
f15a8c49
 	while(sbegin+what_len <= str_end) {
 		while(sbegin+what_len<=str_end && !strncmp(sbegin,what,what_len)) {
bd912dd8
 			const char* src = sbegin+what_len;
 			/* move string */
 			memmove(sbegin,src,str_end-src+1);
 			str_end -= what_len;
 		}
 		sbegin++;
 	}
 	*end = str_end;
 }
 
 
43ecd9a1
 /* replace every occurrence of @c in @str with @r*/
 static void str_replace(char* str,const char* end,char c,char r)
bd912dd8
 {
7c6c3e13
 	for(;str<=end;str++) {
bd912dd8
 		if(*str==c)
 			*str=r;
 	}
 }
43ecd9a1
 static void str_make_lowercase(char* str,size_t len)
bd912dd8
 {
 	for(;len;str++,len--) {
 		*str = tolower(*str);
 	}
 }
 
 #define fix32(x) ((x)<32 ? 32 : (x))
43ecd9a1
 static void clear_msb(char* begin)
bd912dd8
 {
 	for(;*begin;begin++)
5c23fc2f
 		*begin = fix32((*begin)&0x7f);
bd912dd8
 }
 
 /*
  * Particularly yahoo puts links like this in mails:
81040d73
  * http:/ /www.example.com
bd912dd8
  * So first step: delete space between / /
  *
  * Next there could be possible links like this:
  * <a href="phishlink">w  w w . e b a y . c o m</a>
  * Here we need to strip spaces to get this picked up.
  *
  * Next there are links like:
  * <a href="www.yahoo.com">Check out yahoo.com</a>
  * Here we add a ., so we get: check.out.yahoo.com (it won't trigger)
  *
6a929d83
  * Old Rule for adding .: if substring from right contains dot, then add dot,
5c23fc2f
  *	otherwise strip space
6a929d83
  * New Rule: strip all spaces
  *  strip leading and trailing garbage
bd912dd8
  *
  */
43ecd9a1
 static void
5c23fc2f
 str_fixup_spaces(char **begin, const char **end)
bd912dd8
 {
6a929d83
 	char* sbegin = *begin;
 	const char* send = *end;
 	if(!sbegin || !send || send < sbegin)
5c23fc2f
 		return;
6a929d83
 	/* strip spaces */
 	str_strip(&sbegin, &send, " ",1);
 	/* strip leading/trailing garbage */
35609fe5
 	while(!isalnum(sbegin[0]&0xff) && sbegin <= send) sbegin++;
 	while(!isalnum(send[0]&0xff) && send >= sbegin) send--;
f12c2e68
 
 	/* keep terminating slash character*/
 	if(send[1] == '/') send++;
6a929d83
 	*begin = sbegin;
 	*end = send;
bd912dd8
 }
 
 /* allocates memory */
fc83da82
 static int
b5341ac0
 cleanupURL(struct string *URL,struct string *pre_URL, int isReal)
bd912dd8
 {
5c23fc2f
 	char *begin = URL->data;
 	const char *end;
bd912dd8
 	size_t len;
813864ce
 
bd912dd8
 	clear_msb(begin);
5c23fc2f
 	/*if(begin == NULL)
bd912dd8
 		return;*/
 	/*TODO: handle hex-encoded IPs*/
5c23fc2f
 	while(isspace(*begin))
 		begin++;
 
 	len = strlen(begin);
 	if(len == 0) {
 		string_assign_null(URL);
b5341ac0
 		string_assign_null(pre_URL);
9db68157
 		return 0;
5c23fc2f
 	}
 
 	end = begin + len - 1;
 	/*cli_dbgmsg("%d %d\n", end-begin, len);*/
 	if(begin >= end) {
bd912dd8
 		string_assign_null(URL);
b5341ac0
 		string_assign_null(pre_URL);
9db68157
 		return 0;
bd912dd8
 	}
5c23fc2f
 	while(isspace(*end))
bd912dd8
 		end--;
 	/* From mailscanner, my comments enclosed in {} */
b5341ac0
 	if(!strncmp(begin,dotnet,dotnet_len) || !strncmp(begin,adonet,adonet_len) || !strncmp(begin,aspnet,aspnet_len)) {
bd912dd8
 		string_assign_null(URL);
b5341ac0
 		string_assign_null(pre_URL);
 	}
bd912dd8
 	else {
 		size_t host_len;
 		char* host_begin;
15b08fbb
 		int rc;
 
bd912dd8
 		str_replace(begin,end,'\\','/');
f12c2e68
 		/* find beginning of hostname, because:
 		 * - we want to keep only protocol, host, and 
 		 *  strip path & query parameter(s) 
 		 * - we want to make hostname lowercase*/
 		host_begin = strchr(begin,':');
 		while(host_begin && (host_begin < end) && (host_begin[1] == '/'))  host_begin++;
 		if(!host_begin) host_begin=begin;
 		else host_begin++;
 		host_len = strcspn(host_begin,":/?");
 	        if(host_begin + host_len > end + 1) {
 			/* prevent hostname extending beyond end, it can happen
 			 * if we have spaces at the end, we don't want those part of 
 			 * the hostname */
 			host_len = end - host_begin + 1;
 		} else {
 			/* cut the URL after the hostname */
 			/* @end points to last character we want to be part of the URL */
 			end = host_begin + host_len - 1;
 		}
2e11bcdf
 		host_begin[host_len] = '\0';
f12c2e68
 		/* convert hostname to lowercase, but only hostname! */
 		str_make_lowercase(host_begin, host_len);
7c6c3e13
 		/* some broken MUAs put > in the href, and then
 		 * we get a false positive, so remove them */
97ba1aed
 		str_replace(begin,end,'<',' ');
 		str_replace(begin,end,'>',' ');
 		str_replace(begin,end,'\"',' ');
 		str_replace(begin,end,';',' ');
bd912dd8
 		str_strip(&begin,&end,lt,lt_len);
 		str_strip(&begin,&end,gt,gt_len);
 		/* convert %xx to real value */
 		str_hex_to_char(&begin,&end);
37dd9c04
 		if(isReal) {
 			/* htmlnorm converts \n to space, so we have to strip spaces */
 			str_strip(&begin, &end, " ", 1);
 		}
 		else {
 			/* trim space */
 			while((begin <= end) && (begin[0]==' '))  begin++;
 			while((begin <= end) && (end[0]==' ')) end--;
 		}
b5341ac0
 		if (( rc = string_assign_dup(isReal ? URL : pre_URL,begin,end+1) )) {
 			string_assign_null(URL);
15b08fbb
 			return rc;
b5341ac0
 		}
 		if(!isReal) {
 			str_fixup_spaces(&begin,&end);
75fe1251
 			if (( rc = string_assign_dup(URL, begin, end+1) )) {
b5341ac0
 				return rc;
 			}
 		}
bd912dd8
 	}
9db68157
 	return 0;
bd912dd8
 }
 
3da4dd4c
 /* -------end runtime disable---------*/
08402afa
 int phishingScan(cli_ctx* ctx,tag_arguments_t* hrefs)
bd912dd8
 {
75fe1251
 	/* TODO: get_host and then apply regex, etc. */
bd912dd8
 	int i;
ec481027
 	struct phishcheck* pchk = (struct phishcheck*) ctx->engine->phishcheck;
462e8e5e
 	/* check for status of whitelist fatal error, etc. */
ec481027
 	if(!pchk || pchk->is_disabled)
 		return CL_CLEAN;
bd912dd8
 
89c76290
 	if(!ctx->found_possibly_unwanted)
 		*ctx->virname=NULL;
b43205cb
 #if 0
2e11bcdf
 	FILE *f = fopen("/home/edwin/quarantine/urls","r");
 	if(!f)
 		abort();
 	while(!feof(f)) {
 		struct url_check urls;
 		char line1[4096];
 		char line2[4096];
 		char line3[4096];
 
 		fgets(line1, sizeof(line1), f);
 		fgets(line2, sizeof(line2), f);
 		fgets(line3, sizeof(line3), f);
 		if(strcmp(line3, "\n") != 0) {
 			strcpy(line1, line2);
 			strcpy(line2, line3);
 			fgets(line3, sizeof(line3), f);
 			while(strcmp(line3, "\n") != 0) {
 				fgets(line3, sizeof(line3),f);
 			}
 		}
 		urls.flags = CL_PHISH_ALL_CHECKS;
 		urls.link_type = 0;
 		string_init_c(&urls.realLink, line1);
 		string_init_c(&urls.displayLink, line2);
 		string_init_c(&urls.pre_fixup.pre_displayLink, NULL);
 		urls.realLink.refcount=-1;
 		urls.displayLink.refcount=-1;
 		int rc = phishingCheck(ctx->engine, &urls);
 	}
 	fclose(f);
 	return 0;
b43205cb
 #endif
f2b71eb9
 	for(i=0;i<hrefs->count;i++) {
bd912dd8
 			struct url_check urls;
 			enum phish_status rc;
 			urls.flags	 = strncmp((char*)hrefs->tag[i],href_text,href_text_len)? (CL_PHISH_ALL_CHECKS&~CHECK_SSL): CL_PHISH_ALL_CHECKS;
c7090d88
 			urls.link_type   = 0;
 			if(!strncmp((char*)hrefs->tag[i],src_text,src_text_len)) {
 				if (!(urls.flags&CHECK_IMG_URL))
bd912dd8
 				continue;
813864ce
 				urls.link_type |= LINKTYPE_IMAGE;
c7090d88
 			}
ff9845c0
 			urls.always_check_flags = 0;
19b3e182
 			if (ctx->options & CL_SCAN_PHISHING_BLOCKSSL) {
 				urls.always_check_flags |= CHECK_SSL;
 			}
 			if (ctx->options & CL_SCAN_PHISHING_BLOCKCLOAK) {
 				urls.always_check_flags |= CHECK_CLOAKING;
 			}
bd912dd8
 			string_init_c(&urls.realLink,(char*)hrefs->value[i]);
b9b47784
 			string_init_c(&urls.displayLink, (char*)hrefs->contents[i]);
7da9bd64
 			string_init_c(&urls.pre_fixup.pre_displayLink, NULL);
 
bd912dd8
 			urls.realLink.refcount=-1;
 			urls.displayLink.refcount=-1;/*don't free these, caller will free*/
 			if(strcmp((char*)hrefs->tag[i],"href")) {
 				char *url;
 				url = urls.realLink.data;
 				urls.realLink.data = urls.displayLink.data;
 				urls.displayLink.data = url;
 			}
 
3da4dd4c
 			rc = phishingCheck(ctx->engine,&urls);
ec481027
 			if(pchk->is_disabled)
 				return CL_CLEAN;
bd912dd8
 			free_if_needed(&urls);
4c748c36
 			cli_dbgmsg("Phishcheck: Phishing scan result: %s\n",phishing_ret_toString(rc));
bd912dd8
 			switch(rc)/*TODO: support flags from ctx->options,*/
7f0d1148
 			{
 				case CL_PHISH_CLEAN:
 					continue;
 				case CL_PHISH_NUMERIC_IP:
 					*ctx->virname="Phishing.Heuristics.Email.Cloaked.NumericIP";
 					break;
 				case CL_PHISH_CLOAKED_NULL:
81040d73
 					*ctx->virname="Phishing.Heuristics.Email.Cloaked.Null";/*fakesite%01%00@fake.example.com*/
7f0d1148
 					break;
 				case CL_PHISH_SSL_SPOOF:
 					*ctx->virname="Phishing.Heuristics.Email.SSL-Spoof";
 					break;
 				case CL_PHISH_CLOAKED_UIU:
81040d73
 					*ctx->virname="Phishing.Heuristics.Email.Cloaked.Username";/*http://banksite@fake.example.com*/
7f0d1148
 					break;
1126559f
 				case CL_PHISH_HASH0:
a9c304e3
 					*ctx->virname="Safebrowsing.Suspected-malware_safebrowsing.clamav.net";
12d07440
 					break;
1126559f
 				case CL_PHISH_HASH1:
b611b5ff
 					*ctx->virname="Phishing.URL.Blacklisted";
 					break;
12d07440
 				case CL_PHISH_HASH2:
a9c304e3
 					*ctx->virname="Safebrowsing.Suspected-phishing_safebrowsing.clamav.net";
12d07440
 					break;
7f0d1148
 				case CL_PHISH_NOMATCH:
 				default:
 					*ctx->virname="Phishing.Heuristics.Email.SpoofedDomain";
 					break;
 			}
 			return cli_found_possibly_unwanted(ctx);
f2b71eb9
 	}
43ecd9a1
 	return CL_CLEAN;
bd912dd8
 }
 
43ecd9a1
 static char hex2int(const unsigned char* src)
3da4dd4c
 {
19b3e182
 	return (src[0] == '0' && src[1] == '0') ? 
 		0x1 :/* don't convert %00 to \0, use 0x1
  		      * this value is also used by cloak check*/
 		hextable[src[0]]<<4 | hextable[src[1]];
3da4dd4c
 }
 
ec481027
 static void free_regex(regex_t* p)
3da4dd4c
 {
 	if(p) {
53ff1b04
 		cli_regfree(p);
3da4dd4c
 	}
 }
 
ec481027
 int phishing_init(struct cl_engine* engine)
3da4dd4c
 {
ec481027
 	struct phishcheck* pchk;
 	if(!engine->phishcheck) {
47d40feb
 		pchk = engine->phishcheck = mpool_malloc(engine->mempool, sizeof(struct phishcheck));
ec481027
 		if(!pchk)
 			return CL_EMEM;
81040d73
 		pchk->is_disabled=1;
ec481027
 	}
 	else {
 		pchk = engine->phishcheck;
15b08fbb
 		if(!pchk)
 			return CL_ENULLARG;
ec481027
 		if(!pchk->is_disabled) {
 			/* already initialized */
 			return CL_SUCCESS;
 		}
 	}
 
3da4dd4c
 	cli_dbgmsg("Initializing phishcheck module\n");
ec481027
 
 	if(build_regex(&pchk->preg_numeric,numeric_url_regex,1)) {
47d40feb
 		mpool_free(engine->mempool, pchk);
ec481027
 		engine->phishcheck = NULL;
 		return CL_EFORMAT;
 	}
 	pchk->is_disabled = 0;
3da4dd4c
 	cli_dbgmsg("Phishcheck module initialized\n");
ec481027
 	return CL_SUCCESS;
3da4dd4c
 }
 
 void phishing_done(struct cl_engine* engine)
 {
ec481027
 	struct phishcheck* pchk = engine->phishcheck;
3da4dd4c
 	cli_dbgmsg("Cleaning up phishcheck\n");
ec481027
 	if(pchk && !pchk->is_disabled) {
 		free_regex(&pchk->preg_numeric);
6c659919
 	}
3da4dd4c
 	whitelist_done(engine);
 	domainlist_done(engine);
ec481027
 	if(pchk) {
 		cli_dbgmsg("Freeing phishcheck struct\n");
47d40feb
 		mpool_free(engine->mempool, pchk);
813864ce
 	}
3da4dd4c
 	cli_dbgmsg("Phishcheck cleaned up\n");
 }
 
2e11bcdf
 
 /*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz*/
 static const uint8_t URI_alpha[256] = {
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
         0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
 };
 
 /*!"$%&'()*,-0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz*/
 static const uint8_t URI_xalpha_nodot[256] = {
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
         0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
 };
 
dfc0c031
 /*!"#$%&'()*+,-0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz*/
2e11bcdf
 static const uint8_t URI_xpalpha_nodot[256] = {
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
dfc0c031
         0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
2e11bcdf
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
         0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
 };
 
 static inline int validate_uri_xalphas_nodot(const char *start, const char *end)
 {
b9b47784
 	const unsigned char *p;
 	for(p=(const unsigned char*)start;p < (const unsigned char*)end; p++) {
2e11bcdf
 		if(!URI_xalpha_nodot[*p])
 			return 0;
 	}
 	return 1;
 }
 
 static inline int validate_uri_xpalphas_nodot(const char *start, const char *end)
 {
b9b47784
 	const unsigned char *p;
 	for(p=(const unsigned char*)start;p < (const unsigned char*)end; p++) {
2e11bcdf
 		if(!URI_xpalpha_nodot[*p])
 			return 0;
 	}
 	/* must have at least on char */
 	return p > (const unsigned char*)start;
 }
 
 
 static inline int validate_uri_ialpha(const char *start, const char *end)
 {
b9b47784
 	const unsigned char *p = (const unsigned char*) start;
2e11bcdf
 	if(start >= end || !URI_alpha[*p])
 		return 0;
 	return validate_uri_xalphas_nodot(start + 1, end);
 }
 
bd912dd8
 /*
  * Only those URLs are identified as URLs for which phishing detection can be performed.
  */
7e32c99e
 static int isURL(char* URL, int accept_anyproto)
bd912dd8
 {
7e32c99e
 	char *last_tld_end = NULL, *q;
 	const char *start = NULL, *p, *end;
2e11bcdf
 	if(!URL)
 		return 0;
 
dc36f0d7
 	while (*URL == ' ') URL++;
2e11bcdf
 	switch (URL[0]) {
 		case 'h':
 			if (strncmp(URL, https, https_len) == 0)
f2b71eb9
 				start = URL + https_len - 1;
2e11bcdf
 			else if (strncmp(URL, http, http_len) == 0)
f2b71eb9
 				start = URL + http_len - 1;
2e11bcdf
 			break;
 		case 'f':
 		       if (strncmp(URL, ftp, ftp_len) == 0)
f2b71eb9
 			       start = URL + ftp_len - 1;
2e11bcdf
 		       break;
 		case 'm':
 		       if (strncmp(URL, mailto_proto, mailto_proto_len) == 0)
f2b71eb9
 			       start = URL + mailto_proto_len - 1;
2e11bcdf
 		       break;
 	}
f2b71eb9
 	if(start && start[1] == '/' && start[2] == '/') {
2e11bcdf
 		/* has a valid protocol, it is a URL */
 		return 1;
 	}
f2b71eb9
 	start = accept_anyproto ?  strchr(URL, ':') : start;
2e11bcdf
 	if(start) {
 		/* validate URI scheme */
 		if(validate_uri_ialpha(URL, start)) {
f2b71eb9
 			/* skip :// */
 			if (start[1] == '/') {
 			    start += 2;
 			    if (*start == '/')
2e11bcdf
 				start++;
f2b71eb9
 			} else
 			    start++;
2e11bcdf
 		}
 		else
 			start = URL; /* scheme invalid */
 	} else
 		start = URL;
 	p = start;
d6d8d450
 	end = strchr(p, '/');
 	if (!end)
 		end = p + strlen(p);
2e11bcdf
 	do {
 		q = strchr(p, '.');
d6d8d450
 		if (q > end)
 			break;
2e11bcdf
 		if(q) {
 			if(!validate_uri_xpalphas_nodot(p, q))
 				return 0;
7e32c99e
 			if (accept_anyproto && in_tld_set(p, q-p))
 			    last_tld_end = q;
2e11bcdf
 			p = q+1;
 		}
 	} while(q);
 	if (p == start) /* must have at least one dot in the URL */
 		return 0;
d6d8d450
 	if (end < p)
 		end = p;
 	while (*end == ' ' && end > p) --end;
7e32c99e
 
 	if (in_tld_set(p, end - p))
 	    return 1;
 	if (!accept_anyproto)
 	    return 0;
 	if (last_tld_end) {
 	    *last_tld_end = '\0';
 	    return 1;
 	}
 	return 0;
bd912dd8
 }
 
830c1eae
 /*
  * Check if this is a real URL, which basically means to check if it has a known URL scheme (http,https,ftp).
  * This prevents false positives with outbind:// and blocked:: links.
  */
2e11bcdf
 #if 0
830c1eae
 static int isRealURL(const struct phishcheck* pchk,const char* URL)
 {
 	return URL ? !cli_regexec(&pchk->preg_realurl,URL,0,NULL,0) : 0;
 }
2e11bcdf
 #endif
830c1eae
 
fc83da82
 static int isNumericURL(const struct phishcheck* pchk,const char* URL)
bd912dd8
 {
53ff1b04
 	return URL ? !cli_regexec(&pchk->preg_numeric,URL,0,NULL,0) : 0;
bd912dd8
 }
 
 /* Cleans up @urls
  * If URLs are identical after cleanup it will return CL_PHISH_CLEANUP_OK.
  * */
fc83da82
 static enum phish_status cleanupURLs(struct url_check* urls)
bd912dd8
 {
 	if(urls->flags&CLEANUP_URL) {
b5341ac0
 		cleanupURL(&urls->realLink,NULL,1);
 		cleanupURL(&urls->displayLink,&urls->pre_fixup.pre_displayLink,0);
bd912dd8
 		if(!urls->displayLink.data || !urls->realLink.data)
 			return CL_PHISH_NODECISION;
 		if(!strcmp(urls->realLink.data,urls->displayLink.data))
813864ce
 			return CL_PHISH_CLEAN;
bd912dd8
 	}
 	return CL_PHISH_NODECISION;
 }
 
08402afa
 static int url_get_host(struct url_check* url,struct url_check* host_url,int isReal,int* phishy)
bd912dd8
 {
b5341ac0
 	const char *start, *end;
bd912dd8
 	struct string* host = isReal ? &host_url->realLink : &host_url->displayLink;
b5341ac0
 	const char* URL = isReal ? url->realLink.data : url->displayLink.data;
 	int rc;
08402afa
 	if ((rc = get_host(URL, isReal, phishy, &start, &end))) {
b5341ac0
 		return rc;
 	}
 	if(!start || !end) {
 		string_assign_null(host);
 	}
75fe1251
 	else if(( rc = string_assign_concatenated(host, ".", start, end) )) {
813864ce
 		return rc;
b5341ac0
 	}
813864ce
 
ecd2643b
 	cli_dbgmsg("Phishcheck:host:%s\n", host->data);
813864ce
 
f12c2e68
 	if(!host->data || (isReal && (host->data[0]=='\0' || strstr(host->data,".."))) || *phishy&REAL_IS_MAILTO || strchr(host->data,' ')) {
813864ce
 		/* no host,
 		 * link without domain, such as: href="/isapi.dll?...
 		 * mailto:
 		 * spaces in hostname
f12c2e68
 		 * double dots
813864ce
 		 */
f12c2e68
 		cli_dbgmsg("Phishcheck:skipping invalid host\n");
813864ce
 		return CL_PHISH_CLEAN;
bd912dd8
 	}
 	if(isNumeric(host->data)) {
 		*phishy |= PHISHY_NUMERIC_IP;
 	}
813864ce
 	if(!isReal) {
 		url->pre_fixup.host_start = start - URL;
 		url->pre_fixup.host_end = end - URL;
7e32c99e
 		url->pre_fixup.pre_displayLink.data[url->pre_fixup.host_end] = '\0';
813864ce
 	}
bd912dd8
 	return CL_PHISH_NODECISION;
 }
5c23fc2f
 
08402afa
 static void url_get_domain(struct url_check* url,struct url_check* domains)
5c23fc2f
 {
08402afa
 	get_domain(&domains->realLink, &url->realLink);
 	get_domain(&domains->displayLink, &url->displayLink);
ec481027
 	domains->flags = url->flags;
bd912dd8
 }
 
fc83da82
 static enum phish_status phishy_map(int phishy,enum phish_status fallback)
bd912dd8
 {
 	if(phishy&PHISHY_USERNAME_IN_URL)
 		return CL_PHISH_CLOAKED_UIU;
 	else if(phishy&PHISHY_NUMERIC_IP)
 		return CL_PHISH_NUMERIC_IP;
 	else
 		return fallback;
 }
 
fc83da82
 static int whitelist_check(const struct cl_engine* engine,struct url_check* urls,int hostOnly)
bd912dd8
 {
3da4dd4c
 	return whitelist_match(engine,urls->realLink.data,urls->displayLink.data,hostOnly);
bd912dd8
 }
 
a3d029b9
 static int hash_match(const struct regex_matcher *rlist, const char *host, size_t hlen, const char *path, size_t plen, int *prefix_matched)
b611b5ff
 {
1126559f
 	const char *virname;
b43205cb
 #if 0
 	char s[1024];
 	strncpy(s, host, hlen);
 	strncpy(s+hlen, path, plen);
 	s[hlen+plen] = '\0';
 	cli_dbgmsg("hash lookup for: %s\n",s);
 #endif
4e46d65d
 	if(rlist->sha256_hashes.bm_patterns) {
e828353b
 	    const char hexchars[] = "0123456789ABCDEF";
 	    unsigned char h[65];
4e46d65d
 	    unsigned char sha256_dig[32];
e828353b
 	    unsigned i;
4e46d65d
 	    SHA256_CTX sha256;
 
 	    sha256_init(&sha256);
 	    sha256_update(&sha256, host, hlen);
 	    sha256_update(&sha256, path, plen);
 	    sha256_final(&sha256, sha256_dig);
e828353b
 	    for(i=0;i<32;i++) {
 		h[2*i] = hexchars[sha256_dig[i]>>4];
 		h[2*i+1] = hexchars[sha256_dig[i]&0xf];
 	    }
 	    h[64]='\0';
d38d251d
 	    cli_dbgmsg("Looking up hash %s for %s(%u)%s(%u)\n", h, host, (unsigned)hlen, path, (unsigned)plen);
a3d029b9
 	    if (prefix_matched) {
33872a43
 		if (cli_bm_scanbuff(sha256_dig, 4, &virname, &rlist->hostkey_prefix,0,-1) == CL_VIRUS) {
d38d251d
 		    cli_dbgmsg("prefix matched\n");
a3d029b9
 		    *prefix_matched = 1;
 		} else
 		    return CL_SUCCESS;
 	    }
33872a43
 	    if (cli_bm_scanbuff(sha256_dig, 32, &virname, &rlist->sha256_hashes,0,-1) == CL_VIRUS) {
467bb4e0
 		cli_dbgmsg("This hash matched: %s\n", h);
4e46d65d
 		switch(*virname) {
816d66a8
 		    case 'W':
 			cli_dbgmsg("Hash is whitelisted, skipping\n");
 			break;
4e46d65d
 		    case '1':
 			return CL_PHISH_HASH1;
 		    case '2':
 			return CL_PHISH_HASH2;
 		    default:
 			return CL_PHISH_HASH0;
b43205cb
 		}
4e46d65d
 	    }
b43205cb
 	}
 	return CL_SUCCESS;
 }
b611b5ff
 
b43205cb
 #define URL_MAX_LEN 1024
 #define COMPONENTS 4
a1c9ad2c
 int cli_url_canon(const char *inurl, size_t len, char *urlbuff, size_t dest_len, char **host, size_t *hostlen, const char **path, size_t *pathlen)
b43205cb
 {
4e46d65d
 	char *url, *p, *last;
 	char *host_begin, *path_begin;
b43205cb
 	const char *urlend = urlbuff + len;
 	size_t host_len, path_len;
 
4e46d65d
 	dest_len -= 3;
 	strncpy(urlbuff, inurl, dest_len);
 	urlbuff[dest_len] = urlbuff[dest_len+1] = urlbuff[dest_len+2] = '\0';
b43205cb
 	url = urlbuff;
4e46d65d
 
b02aff65
 	/* canonicalize only real URLs, with a protocol */
4e46d65d
 	host_begin = strchr(url, ':');
 	if(!host_begin)
b43205cb
 		return CL_PHISH_CLEAN;
 	++host_begin;
4e46d65d
 
b02aff65
 	/* ignore username in URL */
4e46d65d
 	p = strchr(host_begin, '@');
 	if (p)
 	    host_begin = p+1;
 	url = host_begin;
b02aff65
 	/* repeatedly % unescape characters */
4e46d65d
 	str_hex_to_char(&url, &urlend);
 	host_begin = url;
 	len = urlend - url;
b02aff65
 	/* skip to beginning of hostname */
b43205cb
 	while((host_begin < urlend) && *host_begin == '/') ++host_begin;
 	while(*host_begin == '.' && host_begin < urlend) ++host_begin;
dfc0c031
 
4e46d65d
 	last = strchr(host_begin, '/');
 	p = host_begin;
 	while (p < urlend) {
 	    if (p+2 < urlend && *p == '/' && p[1] == '.' ) {
 		if (p[2] == '/') {
b02aff65
 		    /* remove /./ */
4e46d65d
 		    if (p + 3 < urlend)
 			memmove(p+1, p+3, urlend - p - 3);
 		    urlend -= 2;
 		}
 		else if (p[2] == '.' && (p[3] == '/' || p[3] == '\0') && last) {
b02aff65
 		    /* remove /component/../ */
4e46d65d
 		    if (p+4 < urlend)
 			memmove(last+1, p+4, urlend - p - 4);
 		    urlend -= 3 + (p - last);
 		}
 	    }
 	    if (*p == '/')
 		last = p;
 	    p++;
 	}
 	p = &url[urlend - url];
 	*p = '\0';
 
 	p = host_begin;
bdd4b77c
 	while (p < urlend && p+2 < url + dest_len && urlend < urlbuff+dest_len) {
4e46d65d
 	    unsigned char c = *p;
 	    if (c <= 32 || c >= 127 || c == '%' || c == '#') {
b02aff65
 		/* convert non-ascii characters back to % escaped */
47a6df99
 		const char hexchars[] = "0123456789ABCDEF";
4e46d65d
 		memmove(p+3, p+1, urlend - p - 1);
 		*p++ = '%';
 		*p++ = hexchars[c>>4];
 		*p = hexchars[c&0xf];
 		urlend += 2;
 	    }
 	    p++;
 	}
 	*p = '\0';
 	urlend = p;
 	len = urlend - url;
b02aff65
 	/* determine end of hostname */
b43205cb
 	host_len = strcspn(host_begin, ":/?");
 	path_begin = host_begin + host_len;
f2b71eb9
 	if(host_len <= len) {
b02aff65
 		/* url without path, use a single / */
b43205cb
 		memmove(path_begin + 2, path_begin + 1, len - host_len);
 		*path_begin++ = '/';
 		*path_begin++ = '\0';
 	} else path_begin = url+len;
 	if(url + len >= path_begin) {
 		path_len = url + len - path_begin + 1;
4e46d65d
 		p = strchr(path_begin, '#');
 		if (p) {
b02aff65
 		    /* ignore anchor */
4e46d65d
 		    *p = '\0';
 		    path_len = p - path_begin;
 		}
a1c9ad2c
 		*path = path_begin;
4e46d65d
 	} else {
b43205cb
 		path_len = 0;
a1c9ad2c
 		*path = "";
4e46d65d
 	}
b02aff65
 	/* lowercase entire URL */
b43205cb
 	str_make_lowercase(host_begin, host_len);
4e46d65d
 	*host = host_begin;
 	*hostlen = host_len;
 	*pathlen = path_len;
 	return CL_PHISH_NODECISION;
 }
 
 static int url_hash_match(const struct regex_matcher *rlist, const char *inurl, size_t len)
 {
 	size_t j, k, ji, ki;
a1c9ad2c
 	char *host_begin;
 	const char *path_begin;
4e46d65d
 	const char *component;
 	size_t path_len;
 	size_t host_len;
 	char *p;
a3d029b9
 	int rc, prefix_matched=0;
4e46d65d
 	const char *lp[COMPONENTS+1];
 	size_t pp[COMPONENTS+2];
 	char urlbuff[URL_MAX_LEN+3];/* htmlnorm truncates at 1024 bytes + terminating null + slash + host end null */
a3d029b9
 	unsigned count;
4e46d65d
 
 	if(!rlist || !rlist->sha256_hashes.bm_patterns) {
b02aff65
 		/* no hashes loaded -> don't waste time canonicalizing and
 		 * looking up */
4e46d65d
 		return CL_SUCCESS;
 	}
 	if(!inurl)
 		return CL_EMEM;
b611b5ff
 
4e46d65d
 	rc = cli_url_canon(inurl, len, urlbuff, sizeof(urlbuff), &host_begin, &host_len, &path_begin, &path_len);
 	if (rc == CL_PHISH_CLEAN)
 	    return rc;
b02aff65
 
 	/* get last 5 components of hostname */
b43205cb
 	j=COMPONENTS;
 	component = strrchr(host_begin, '.');
 	while(component && j > 0) {
 		do {
 			--component;
 		} while(*component != '.' && component > host_begin);
 		if(*component != '.')
 			component = NULL;
 		if(component)
 			lp[j--] = component + 1;
 	}
 	lp[j] = host_begin;
 
b02aff65
 	/* get first 5 components of path */
b43205cb
 	pp[0] = path_len;
dfc0c031
 	if(path_len) {
 		pp[1] = strcspn(path_begin, "?");
 		if(pp[1] != pp[0]) k = 2;
 		else k = 1;
 		pp[k++] = 0;
 		while(k < COMPONENTS+2) {
7959343d
 			p = strchr(path_begin + pp[k-1] + 1, '/');
dfc0c031
 			if(p && p > path_begin) {
 				pp[k++] = p - path_begin;
 			} else
 				break;
 		}
 	} else
 		k = 1;
a3d029b9
 	count = 0;
 	for(ki=k;ki > 0;) {
 	    --ki;
 	    for(ji=COMPONENTS+1;ji > j;) {
 		/* lookup last 2 and 3 components of host, as hostkey prefix,
 		 * if not matched, shortcircuit lookups */
 		int need_prefixmatch = (count<2 && !prefix_matched) &&
 				       rlist->hostkey_prefix.bm_patterns;
 		--ji;
 		assert(pp[ki] <= path_len);
b02aff65
 		/* lookup prefix/suffix hashes of URL */
a3d029b9
 		rc = hash_match(rlist, lp[ji], host_begin + host_len - lp[ji] + 1, path_begin, pp[ki], 
 				need_prefixmatch ? &prefix_matched : NULL);
 		if(rc) {
 		    return rc;
 		}
 		count++;
 		if (count == 2 && !prefix_matched && rlist->hostkey_prefix.bm_patterns) {
b02aff65
 		    /* if hostkey is not matched, don't bother calculating
 		     * hashes for other parts of the URL, they are not in the DB
 		     */
a3d029b9
 		    cli_dbgmsg("hostkey prefix not matched, short-circuiting lookups\n");
 		    return CL_SUCCESS;
b43205cb
 		}
a3d029b9
 	    }
b611b5ff
 	}
 	return CL_SUCCESS;
 }
 
bd912dd8
 /* urls can't contain null pointer, caller must ensure this */
fc83da82
 static enum phish_status phishingCheck(const struct cl_engine* engine,struct url_check* urls)
bd912dd8
 {
 	struct url_check host_url;
813864ce
 	int rc = CL_PHISH_NODECISION;
816d66a8
 	int phishy=0;
ec481027
 	const struct phishcheck* pchk = (const struct phishcheck*) engine->phishcheck;
21d213d7
 
f2b71eb9
 	if(!urls->realLink.data)
bd912dd8
 		return CL_PHISH_CLEAN;
21d213d7
 
43ecd9a1
 	cli_dbgmsg("Phishcheck:Checking url %s->%s\n", urls->realLink.data,
21d213d7
 		urls->displayLink.data);
bd912dd8
 
 	if(!strcmp(urls->realLink.data,urls->displayLink.data))
 		return CL_PHISH_CLEAN;/* displayed and real URL are identical -> clean */
 
08402afa
 	if(!isURL(urls->realLink.data, 0)) {
b43205cb
 		cli_dbgmsg("Real 'url' is not url:%s\n",urls->realLink.data);
 		return CL_PHISH_CLEAN;
 	}
 
1126559f
 	if(( rc = url_hash_match(engine->domainlist_matcher, urls->realLink.data, strlen(urls->realLink.data)) )) {
6f60f808
 	    if (rc == CL_PHISH_CLEAN) {
a3d029b9
 		cli_dbgmsg("not analyzing, not a real url: %s\n", urls->realLink.data);
6f60f808
 		return CL_PHISH_CLEAN;
 	    } else {
b43205cb
 		cli_dbgmsg("Hash matched for: %s\n", urls->realLink.data);
816d66a8
 		return rc;
6f60f808
 	    }
b43205cb
 	}
 
816d66a8
 	if (urls->displayLink.data[0] == '\0') {
 	    return CL_PHISH_CLEAN;
 	}
 
bd912dd8
 	if((rc = cleanupURLs(urls))) {
813864ce
 		/* it can only return an error, or say its clean;
 		 * it is not allowed to decide it is phishing */
 		return rc < 0 ? rc : CL_PHISH_CLEAN;
bd912dd8
 	}
 
75fe1251
 	cli_dbgmsg("Phishcheck:URL after cleanup: %s->%s\n", urls->realLink.data,
 		urls->displayLink.data);
f12c2e68
 
08402afa
 	if((!isURL(urls->displayLink.data, 1) ) &&
830c1eae
 			( (phishy&PHISHY_NUMERIC_IP && !isNumericURL(pchk, urls->displayLink.data)) ||
 			  !(phishy&PHISHY_NUMERIC_IP))) {
 		cli_dbgmsg("Displayed 'url' is not url:%s\n",urls->displayLink.data);
816d66a8
 		return CL_PHISH_CLEAN;
830c1eae
 	}
 
59838e6c
 	if(whitelist_check(engine, urls, 0))
 		return CL_PHISH_CLEAN;/* if url is whitelisted don't perform further checks */
bd912dd8
 
 	url_check_init(&host_url);
 
08402afa
 	if((rc = url_get_host(urls, &host_url, DOMAIN_DISPLAY, &phishy))) {
bd912dd8
 		free_if_needed(&host_url);
813864ce
 		return rc < 0 ? rc : CL_PHISH_CLEAN;
bd912dd8
 	}
 
08402afa
 	if (domainlist_match(engine, host_url.displayLink.data,host_url.realLink.data,&urls->pre_fixup,1)) {
ff9845c0
 		phishy |= DOMAIN_LISTED;
 	} else {
 		urls->flags &= urls->always_check_flags;
 		/* don't return, we may need to check for ssl/cloaking */
19b3e182
 	}
 
c7090d88
 	/* link type filtering must occur after last domainlist_match */
1eed6af5
 	if(urls->link_type & LINKTYPE_IMAGE && !(urls->flags&CHECK_IMG_URL)) {
 		free_if_needed(&host_url);
813864ce
 		return CL_PHISH_CLEAN;/* its listed, but this link type is filtered */
1eed6af5
 	}
bd912dd8
 
 	if(urls->flags&CHECK_CLOAKING) {
 		/*Checks if URL is cloaked.
43ecd9a1
 		Should we check if it contains another http://, https://?
bd912dd8
 		No because we might get false positives from redirect services.*/
c7090d88
 		if(strchr(urls->realLink.data,0x1)) {
bd912dd8
 			free_if_needed(&host_url);
 			return CL_PHISH_CLOAKED_NULL;
 		}
 	}
 
 	if(urls->flags&CHECK_SSL && isSSL(urls->displayLink.data) && !isSSL(urls->realLink.data)) {
 		free_if_needed(&host_url);
 		return CL_PHISH_SSL_SPOOF;
 	}
 
ff9845c0
 	if (!(phishy & DOMAIN_LISTED)) {
 		free_if_needed(&host_url);
 		return CL_PHISH_CLEAN;
 	}
 
08402afa
 	if((rc = url_get_host(urls,&host_url,DOMAIN_REAL,&phishy)))
5c23fc2f
 	{
bd912dd8
 		free_if_needed(&host_url);
813864ce
 		return rc < 0 ? rc : CL_PHISH_CLEAN;
bd912dd8
 	}
 
813864ce
 	if(whitelist_check(engine,&host_url,1)) {
19b3e182
 		free_if_needed(&host_url);
813864ce
 		return CL_PHISH_CLEAN;
19b3e182
 	}
 
813864ce
 	if(!strcmp(urls->realLink.data,urls->displayLink.data)) {
ec481027
 		free_if_needed(&host_url);
813864ce
 		return CL_PHISH_CLEAN;
ec481027
 	}
 
813864ce
 	{
 		struct url_check domain_url;
 		url_check_init(&domain_url);
08402afa
 		url_get_domain(&host_url,&domain_url);
813864ce
 		if(!strcmp(domain_url.realLink.data,domain_url.displayLink.data)) {
bd912dd8
 			free_if_needed(&host_url);
 			free_if_needed(&domain_url);
813864ce
 			return CL_PHISH_CLEAN;
bd912dd8
 		}
813864ce
 		free_if_needed(&domain_url);
 	}
bd912dd8
 
813864ce
 	free_if_needed(&host_url);
43ecd9a1
 	/*we failed to find a reason why the 2 URLs are different, this is definitely phishing*/
bd912dd8
 	return phishy_map(phishy,CL_PHISH_NOMATCH);
 }
 
fc83da82
 static const char* phishing_ret_toString(enum phish_status rc)
bd912dd8
 {
 	switch(rc) {
 		case CL_PHISH_CLEAN:
 			return "Clean";
 		case CL_PHISH_CLOAKED_NULL:
 			return "Link URL is cloaked (null byte %00)";
 		case CL_PHISH_CLOAKED_UIU:
 			return "Link URL contains username, and real<->displayed hosts don't match.";
 			/*username is a legit domain, and after the @ comes the evil one*/
 		case CL_PHISH_SSL_SPOOF:
 			return "Visible links is SSL, real link is not";
 		case CL_PHISH_NOMATCH:
 			return "URLs are way too different";
1126559f
 		case CL_PHISH_HASH0:
 		case CL_PHISH_HASH1:
 		case CL_PHISH_HASH2:
b43205cb
 			return "Blacklisted";
bd912dd8
 		default:
 			return "Unknown return code";
 	}
 }