Index: channels/chan_sip.c
===================================================================
--- channels/chan_sip.c	(revision 162867)
+++ channels/chan_sip.c	(working copy)
@@ -6611,10 +6611,81 @@
 /*! \brief Send a fake 401 Unauthorized response when the administrator
   wants to hide the names of local users/peers from fishers
 */
-static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, int reliable)
+static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, char *randdata, int randlen, int reliable, int ignore)
 {
-	snprintf(randdata, randlen, "%08x", thread_safe_rand());
-	transmit_response_with_auth(p, "401 Unauthorized", req, randdata, reliable, "WWW-Authenticate", 0);
+	/* We have to emulate EXACTLY what we'd get with a good peer
+	 * and a bad password, or else we leak information. */
+	char *response = "407 Proxy Authentication Required";
+	char *reqheader = "Proxy-Authorization";
+	char *respheader = "Proxy-Authenticate";
+	const char *authtoken;
+
+	if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
+		response = "401 Unauthorized";
+		reqheader = "Authorization";
+		respheader = "WWW-Authenticate";
+	}
+
+	authtoken = get_header(req, reqheader);
+	if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
+		/* This is a retransmitted invite/register/etc, don't reconstruct authentication
+		 * information */
+		if (!reliable) {
+			/* Resend message if this was NOT a reliable delivery.   Otherwise the
+			   retransmission should get it */
+			transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
+			/* Schedule auto destroy in 15 seconds */
+			sip_scheddestroy(p, 15000);
+		}
+	} else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
+		/* We have no auth, so issue challenge and request authentication */
+		snprintf(p->randdata, sizeof(p->randdata), "%08x", thread_safe_rand());
+		transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
+		sip_scheddestroy(p, 15000);
+	} else {
+		char tmp[256], *c = tmp, *z, *nonce = "";
+
+		/* Find their response among the mess that we'r sent for comparison */
+		ast_copy_string(tmp, authtoken, sizeof(tmp));
+
+		while (c) {
+			c = ast_skip_blanks(c);
+			if (!*c) {
+				break;
+			}
+			if (!strncasecmp(c, "nonce=", strlen("nonce="))) {
+				c += strlen("nonce=");
+				if ((*c == '\"')) {
+					nonce = ++c;
+					if ((c = strchr(c,'\"'))) {
+						*c = '\0';
+					}
+				} else {
+					nonce = c;
+					if ((c = strchr(c,','))) {
+						*c = '\0';
+					}
+				}
+				/* Don't need anything beyond the nonce sent. */
+				break;
+			} else if ((z = strchr(c, ' ')) || (z = strchr(c, ','))) {
+				c = z;
+			}
+			if (c) {
+				c++;
+			}
+		}
+		/* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
+		if (strncasecmp(randdata, nonce, randlen)) {
+			snprintf(randdata, randlen, "%08x", thread_safe_rand());
+			transmit_response_with_auth(p, response, req, randdata, reliable, respheader, 0);
+
+			/* Schedule auto destroy in 15 seconds */
+			sip_scheddestroy(p, 15000);
+		} else {
+			transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
+		}
+	}
 }
 
 /*! \brief  register_verify: Verify registration of user */
@@ -6736,6 +6807,14 @@
 			}
 		}
 	}
+	if (!peer && global_alwaysauthreject) {
+		/* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
+		 * trying to avoid leaking information, we MUST also transmit the same
+		 * response when we DON'T find a peer. */
+		transmit_response(p, "100 Trying", req);
+		/* Insert a fake delay between the 100 and the subsequent failure. */
+		sched_yield();
+	}
 	if (!res) {
 		ast_device_state_changed("SIP/%s", peer->name);
 	}
@@ -6756,7 +6835,7 @@
 		case -4:	/* ACL error */
 		case -5:	/* Peer is not supposed to register with us at all */
 			if (global_alwaysauthreject) {
-				transmit_fake_auth_response(p, &p->initreq, p->randdata, sizeof(p->randdata), 1);
+				transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, p->randdata, sizeof(p->randdata), 1, ignore);
 			} else {
 				/* URI not found */
 				if (res == -5)
@@ -10699,7 +10778,7 @@
 		if (res < 0) {
 			if (res == -4) {
 				ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
-				transmit_fake_auth_response(p, req, p->randdata, sizeof(p->randdata), 1);
+				transmit_fake_auth_response(p, SIP_INVITE, req, p->randdata, sizeof(p->randdata), 1, ignore);
 			} else {
 				ast_log(LOG_NOTICE, "Failed to authenticate user %s\n", get_header(req, "From"));
 				transmit_response_reliable(p, "403 Forbidden", req, 1);
@@ -11105,7 +11184,7 @@
 		if (res < 0) {
 			if (res == -4) {
 				ast_log(LOG_NOTICE, "Sending fake auth rejection for user %s\n", get_header(req, "From"));
-				transmit_fake_auth_response(p, req, p->randdata, sizeof(p->randdata), 1);
+				transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, p->randdata, sizeof(p->randdata), 1, ignore);
 			} else {
 				ast_log(LOG_NOTICE, "Failed to authenticate user %s for SUBSCRIBE\n", get_header(req, "From"));
 				if (ignore)
Index: channels/chan_iax2.c
===================================================================
--- channels/chan_iax2.c	(revision 162867)
+++ channels/chan_iax2.c	(working copy)
@@ -164,6 +164,7 @@
 static int authdebug = 1;
 static int autokill = 0;
 static int iaxcompat = 0;
+static int lastauthmethod = 0;
 
 static int iaxdefaultdpcache=10 * 60;	/* Cache dialplan entries for 10 minutes by default */
 
@@ -545,6 +546,8 @@
 	char username[80];
 	/*! Expected Secret */
 	char secret[80];
+	/*! AUTHREJ all AUTHREP frames */
+	int authrej;
 	/*! permitted authentication methods */
 	int authmethods;
 	/*! permitted encryption methods */
@@ -1444,7 +1447,7 @@
 		ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
 		return -1;
 	}
-	fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
+	fd = open(s2, O_RDWR | O_CREAT | O_EXCL, 0600);
 	if (fd < 0) {
 		ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
 		close(ifd);
@@ -5177,6 +5180,18 @@
 		if (ast_test_flag(user, IAX_TEMPONLY))
 			destroy_user(user);
 		res = 0;
+	} else {
+		 /* user was not found, but we should still fake an AUTHREQ.
+		  * Set authmethods to the last known authmethods used by the system.
+		  * Set a fake secret, it's not looked at, just required to attempt authentication.
+		  * Set authrej so the AUTHREP is rejected without even looking at its contents */
+		iaxs[callno]->authmethods = lastauthmethod ? lastauthmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
+		ast_copy_string(iaxs[callno]->secret, "badsecret", sizeof(iaxs[callno]->secret));
+		iaxs[callno]->authrej = 1;
+		if (!ast_strlen_zero(iaxs[callno]->username)) {
+			/* only send the AUTHREQ if a username was specified. */
+			res = 0;
+		}
 	}
 	ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);	
 	return res;
@@ -5276,6 +5291,9 @@
 	int x;
 	struct iax2_user *user = NULL;
 
+	if (p->authrej) {
+		return res;
+	}
 	ast_mutex_lock(&userl.lock);
 	user = userl.users;
 	while (user) {
@@ -5376,9 +5394,16 @@
 		ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
 		return -1;
 	}
+
+	ast_copy_string(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer));
+	/* Choose lowest expiry number */
+	if (expire && (expire < iaxs[callno]->expiry)) 
+		iaxs[callno]->expiry = expire;
+
 	/* We release the lock for the call to prevent a deadlock, but it's okay because
 	   only the current thread could possibly make it go away or make changes */
 	ast_mutex_unlock(&iaxsl[callno]);
+
 	/* SLD: first call to lookup peer during registration */
 	p = find_peer(peer, 1);
 	ast_mutex_lock(&iaxsl[callno]);
@@ -5386,6 +5411,13 @@
 	if (!p) {
 		if (authdebug)
 			ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
+		ast_copy_string(iaxs[callno]->secret, "invalidpassword", sizeof(iaxs[callno]->secret));
+
+		/* A AUTHREQ must be sent to a invalid peer.  By returning 0, a REGAUTH with a md5/rsa challenge
+		 * will be sent.  If the challenge has already been sent, return -1 to REGREJ the invalid peer. */
+		if (ast_strlen_zero(iaxs[callno]->challenge)) {
+			return 0;
+		}
 		return -1;
 	}
 
@@ -5419,7 +5451,7 @@
 				if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
 					ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
 					break;
-				} else if (!key) 
+				} else if (!key)
 					ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
 				keyn = strsep(&stringp, ":");
 			}
@@ -5451,7 +5483,7 @@
 		struct MD5Context md5;
 		unsigned char digest[16];
 		char *tmppw, *stringp;
-		
+
 		tmppw = ast_strdupa(p->secret);
 		stringp = tmppw;
 		while((tmppw = strsep(&stringp, ";"))) {
@@ -5461,7 +5493,7 @@
 			MD5Final(digest, &md5);
 			for (x=0;x<16;x++)
 				sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
-			if (!strcasecmp(requeststr, md5secret)) 
+			if (!strcasecmp(requeststr, md5secret))
 				break;
 		}
 		if (tmppw) {
@@ -5473,24 +5505,17 @@
 				destroy_peer(p);
 			return -1;
 		}
-	} else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
-		if (authdebug)
-			ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
+	} else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
+		/* if challenge has been sent, but no challenge response if given, reject. */
 		if (ast_test_flag(p, IAX_TEMPONLY))
 			destroy_peer(p);
 		return -1;
 	}
-	ast_copy_string(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer));
-	/* Choose lowest expiry number */
-	if (expire && (expire < iaxs[callno]->expiry)) 
-		iaxs[callno]->expiry = expire;
-
 	ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
 
 	if (ast_test_flag(p, IAX_TEMPONLY))
 		destroy_peer(p);
 	return 0;
-	
 }
 
 static int authenticate(char *challenge, char *secret, char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
@@ -6087,23 +6112,33 @@
 {
 	struct iax_ie_data ied;
 	struct iax2_peer *p;
+	int authmethods;
+
+	if (!callno || !iaxs[callno]) {
+		return 0;
+	}
+
 	/* SLD: third call to find_peer in registration */
-	p = find_peer(name, 1);
-	if (p) {
-		memset(&ied, 0, sizeof(ied));
-		iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
-		if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
-			/* Build the challenge */
-			snprintf(iaxs[callno]->challenge, sizeof(iaxs[callno]->challenge), "%d", rand());
-			iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
-		}
-		iax_ie_append_str(&ied, IAX_IE_USERNAME, name);
-		if (ast_test_flag(p, IAX_TEMPONLY))
-			destroy_peer(p);
-		return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
-	} 
-	ast_log(LOG_WARNING, "No such peer '%s'\n", name);
-	return 0;
+	if ((p = find_peer(name, 1))) {
+		lastauthmethod = p->authmethods;
+	}
+
+	authmethods = p ? p->authmethods : lastauthmethod ? lastauthmethod : (IAX_AUTH_PLAINTEXT | IAX_AUTH_MD5);
+	if (p && ast_test_flag(p, IAX_TEMPONLY)) {
+		destroy_peer(p);
+	} else if (!p) {
+		ast_log(LOG_WARNING, "No such peer '%s'\n", name);
+	}
+
+	memset(&ied, 0, sizeof(ied));
+	iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, authmethods);
+	if (authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
+		/* Build the challenge */
+		snprintf(iaxs[callno]->challenge, sizeof(iaxs[callno]->challenge), "%d", rand());
+		iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
+	}
+	iax_ie_append_str(&ied, IAX_IE_USERNAME, name);
+	return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
 }
 
 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
Index: configs/sip.conf.sample
===================================================================
--- configs/sip.conf.sample	(revision 162867)
+++ configs/sip.conf.sample	(working copy)
@@ -108,10 +108,12 @@
 				; Useful to limit subscriptions to local extensions
 				; Settable per peer/user also
 ;notifyringing = yes		; Notify subscriptions on RINGING state
-;alwaysauthreject = yes		; When an incoming INVITE or REGISTER is to be rejected,
-		    		; for any reason, always reject with '401 Unauthorized'
-				; instead of letting the requester know whether there was
-				; a matching user or peer for their request
+;alwaysauthreject = yes          ; When an incoming INVITE or REGISTER is to be rejected,
+                                 ; for any reason, always reject with an identical response
+                                 ; equivalent to valid username and invalid password/hash
+                                 ; instead of letting the requester know whether there was
+                                 ; a matching user or peer for their request.  This reduces
+                                 ; the ability of an attacker to scan for valid SIP usernames.
 ;
 ; If regcontext is specified, Asterisk will dynamically create and destroy a
 ; NoOp priority 1 extension for a given peer who registers or unregisters with
