收到服务器401响应的处理(HTTP或SIP)

本文涉及的产品
密钥管理服务KMS,1000个密钥,100个凭据,1个月
简介: 收到服务器401响应的处理(HTTP或SIP)

我们先来看看一个SIP的请求:


REGISTER sip:ocp.gz.com SIP/2.0

Call-ID: 3143514a66f010254e8cfdcde0ef59d9@192.168.2.1

CSeq: 1 REGISTER

From: "anson" <sip:anson@ocp.gz.com:5060>;tag=textclientv1.0

To: <sip:anson@ocp.gz.com>

Via: SIP/2.0/TCP ocp.gz.com:5060;branch=branch1

Max-Forwards: 70

Contact: "anson" <sip:anson@192.168.2.1:5060>

Content-Length: 0


这是一个简单的SIP的REGISTER请求,

用户anson,要REGISTER到ocp.gz.com上的

那么,服务器返回来的结果是什么呢,请看:


SIP/2.0 401 Unauthorized

Via: SIP/2.0/TCP 192.168.2.1:5060;branch=z9hG4bK-19f0145d-3238-4891-ad6f-07f7e7d64fdf.1;received=192.168.2.1;rport=1318

To: <sip:anson@ocp.gz.com>;tag=-11euscraj71o1768560179

From: "ansonlai" <sip:anson@ocp.gz.com>;tag=baf08061-a017-463d-8540-6aaed6bb1bb0

Call-ID: 373cfbd3-84f5-456a-ab93-cc26d26d1404

CSeq: 1 REGISTER

Server: Oracle-OCMS/10.1.3.4.0

Content-Length: 0

WWW-Authenticate: Digest qop="auth",stale=false,realm="ocp.gz.com",opaque="242a40eaaadcf7d4f96838f5b047219f",nonce="MTI2OTU2Nzk5NjU0NDY2NTdlM2ZiYjkyNjcyYzIyNGI1OWMwNmVkNDA0MmRj"


其它的地方可以忽略不看,毕竟跟我这篇文章所要阐明的没什么交集,

集中看一个这个响应的头:WWW-Authenticate

这个401的响应里面,带了一个验证信息的HEADER,

很明显,这是需要我们发信息去验证,那么,发什么过去呢,问题就来了.

之前并未了解过这一部分的内容,

于是上网查了不少资料.

从HEADER的内容可以看到:Digest 在网上查到的还有另一种:Basic.

在这里,对Basic不作深入了解,至少没涉及到,网上资料也不少.

最后在WIKI找一和篇文章:内容如下:


Digest access authentication


HTTP Digest access authentication is one of the agreed methods a web server can use to negotiate credentials with a web user (using the HTTP protocol). Digest authentication is intended to supersede unencrypted use of the Basic access authentication, allowing user identity to be established securely without having to send a password in plaintext over the network. Digest authentication is basically an application of MD5 cryptographic hashing with usage of nonce values to prevent cryptanalysis.


Contents


 [hide]

1 Overview

2 Impact of MD5 security on Digest authentication

3 HTTP Digest Authentication considerations

3.1 Advantages

3.2 Disadvantages

3.3 Alternative authentication protocols

4 Example with explanation

5 SIP Digest Authentication

6 Browser Implementation

7 References

8 See also

9 External links


[edit]Overview


Digest access authentication was originally specified by RFC 2069 (An Extension to HTTP: Digest Access Authentication). RFC 2069specifies roughly a traditional digest authentication scheme with security maintained by a server-generated nonce value.

image.png

RFC 2069 was later replaced by RFC 2617 (HTTP Authentication: Basic and Digest Access Authentication). RFC 2617 introduced a number of optional security enhancements to Digest Authentication; "Quality of Protection" (qop), nonce counter incremented by client, and a client generated random nonce. These enhancements are designed to protect against e.g. chosen-plaintext attack cryptanalysis.


image.png


If the qop directive's value is "auth" or is unspecified, then HA2 is


image.png


If the qop directive's value is "auth-int" , then HA2 is


image.png


If the qop directive's value is "auth" or "auth-int" , then compute the response as follows:


image.png


If the qop directive is unspecified, then compute the response as follows:


image.png


(The above shows that when qop is not specified, the simpler RFC 2069 standard is followed).


[edit]Impact of MD5 security on Digest authentication


The MD5 calculations used in HTTP Digest Authentication is intended to be "one way", meaning that it should be difficult to determine the original input when only the output is known. If the password itself is too simple, however, then it may be possible to test all possible inputs and find a matching output (a brute force attack) – perhaps aided by a dictionary or suitable look-up list. For the most security, users should use long, non-trivial passwords - however this is not ideal since it is an inconvenience on the user-side.


The HTTP scheme was designed at CERN in 1993 and does not incorporate subsequent improvements in authentication systems, such as the development of keyed-hash message authentication code (HMAC). Although the cryptographic construction that is used is based on the MD5hash function, collision attacks were in 2004 generally believed (e.g. Hash collision news) to not affect applications where the plaintext (i.e. password) is not known. However, claims in 2006 (Kim, Biryukov2, Preneel, Hong On the Security of HMAC and NMAC Based on HAVAL MD4 MD5 SHA-0 and SHA-1) cause some doubt over other MD5 applications as well. However, so far MD5 collision attacks have not been shown to pose a threat to Digest Authentication, and the RFC 2617 allows servers to implement mechanisms to detect some collision and replay attacks.


[edit]HTTP Digest Authentication considerations


[edit]Advantages


HTTP Digest authentication is designed to be more secure than traditional digest authentication schemes; "significantly stronger than (e.g.)CRAM-MD5 ..." (RFC2617).


Some of the security strengths of HTTP Digest authentication are:


The password is not used directly in the digest, but rather HA1 = MD5(username:realm:password). This allows some implementations (e.g.JBoss DIGESTAuth) to store HA1 rather than the clear text password.

Client nonce was introduced in RFC2617, which allows the client to prevent chosen plaintext attacks (which otherwise makes e.g. rainbow tables a threat to digest authentication schemes).

Server nonce is allowed to contain timestamps. Therefore the server may inspect nonce attributes submitted by clients, to prevent replay attacks.

Server is also allowed to maintain a list of recently issued or used server nonce values to prevent reuse.


[edit]Disadvantages


Digest access authentication is intended as a security trade-off; it is intended to replace unencrypted HTTP Basic access authentication which is extremely weak. However it is not intended to replace strong authentication protocols, such as Public key or Kerberos authentication.


In terms of security, there are several drawbacks with Digest access authentication:


Many of the security options in RFC2617 are optional. If quality-of-protection (qop) is not specified by the server, the client will operate in a security-reduced legacy RFC2069 mode.

Digest access authentication is vulnerable to Man-in-the-middle attack; for example, a MitM attacker could tell clients to use Basic access authentication or legacy RFC2069 Digest access authentication mode. To extend this further, Digest access authentication provides no mechanism for clients to verify the server's identity.

Some servers require passwords to be stored using reversible encryption. However, it is possible to instead store the digested value of the username, realm, and password.[1]


[edit]Alternative authentication protocols


Some strong authentication protocols for web based applications include:


Public key authentication (usually implemented with HTTPS / SSL client certificates).

Kerberos or SPNEGO authentication, primarily employed by Microsoft IIS running configured for "Integrated Windows Authentication".

Secure Remote Password protocol (preferably within the HTTPS / TLS layer).

Weak cleartext protocols are also often in use:


Basic access authentication scheme

HTTP+HTML Form based authentication

These weak cleartext protocols used together with HTTPS network encryption resolve many of the threats that Digest access authentication is designed to prevent.


[edit]Example with explanation


Warning: Please refer to the original specifications for a more comprehensive discussion of security issues.

The following example was originally given in RFC 2617 and is expanded here to show the full text expected for each request and response. Note that only the "auth" (authentication) quality of protection code is covered – at the time of writing only the Opera and Konqueror web browsers are known to support "auth-int" (authentication with integrity protection). Although the specification mentions HTTP version 1.1 the scheme can be successfully added to a version 1.0 server, as shown here.


This typical transaction consists of the following steps.


The client asks for a page that requires authentication but does not provide a user name and password. Typically this is because the user simply entered the address or followed a link to the page.

The server responds with the 401 response code, providing the authentication realm and a randomly-generated, single-use value called anonce.

At this point, the client will present the authentication realm (typically a description of the computer or system being accessed) to the user and prompt for a user name and password. The user may decide to cancel at this point.

Once a user name and password have been supplied, the client re-sends the same request but adds an authentication header that includes the response code.

In this example, the server accepts the authentication and the page is returned. If the user name is invalid and/or the password is incorrect, the server might return the "401" response code and the client would prompt the user again.

Note: A client may already have the required user name and password without needing to prompt the user, e.g. if they have previously been stored by a web browser.


Client request (no authentication):


GET /dir/index.html HTTP/1.0

Host: localhost

(followed by a new line, in the form of a carriage return followed by a line feed).


Server response:


HTTP/1.0 401 Unauthorized
Server: HTTPd/0.9
Date: Sun, 10 Apr 2005 20:26:47 GMT
WWW-Authenticate: Digest realm="testrealm@host.com",
                         qop="auth,auth-int",
                         nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
                         opaque="5ccc069c403ebaf9f0171e9517f40e41"
Content-Type: text/html
Content-Length: 311
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<HTML>
  <HEAD>
    <TITLE>Error</TITLE>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
  </HEAD>
  <BODY><H1>401 Unauthorized.</H1></BODY>
</HTML>
Client request (user name "Mufasa", password "Circle Of Life"):
GET /dir/index.html HTTP/1.0
Host: localhost
Authorization: Digest username="Mufasa",
                      realm="testrealm@host.com",
                      nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
                      uri="/dir/index.html",
                      qop=auth,
                      nc=00000001,
                      cnonce="0a4f113b",
                      response="6629fae49393a05397450978507c4ef1",
                      opaque="5ccc069c403ebaf9f0171e9517f40e41"
(followed by a blank line, as before).


Server response:


HTTP/1.0 200 OK

Server: HTTPd/0.9

Date: Sun, 10 Apr 2005 20:27:03 GMT

Content-Type: text/html

Content-Length: 7984

(followed by a blank line and HTML text of the restricted page).


The "response" value is calculated in three steps, as follows. Where values are combined, they are delimited by colon symbols.


The MD5 hash of the combined user name, authentication realm and password is calculated. The result is referred to as HA1.

The MD5 hash of the combined method and digest URI is calculated, e.g. of "GET" and "/dir/index.html". The result is referred to as HA2.

The MD5 hash of the combined HA1 result, server nonce (nonce), request counter (nc), client nonce (cnonce), quality of protection code (qop) and HA2 result is calculated. The result is the "response" value provided by the client.

Since the server has the same information as the client, the response can be checked by performing the same calculation. In the example given above the result is formed as follows – where MD5() represents a function used to calculate an MD5 hash, backslashes represent a continuation and the quotes shown are not used in the calculation.


Completing the example given in RFC 2617 gives the following results for each step.


   HA1 = MD5( "Mufasa:testrealm@host.com:Circle Of Life" )

       = 939e7578ed9e3c518a452acee763bce9


   HA2 = MD5( "GET:/dir/index.html" )

       = 39aff3a2bab6126f332b942af96d3366


   Response = MD5( "939e7578ed9e3c518a452acee763bce9:\

                    dcd98b7102dd2f0e8b11d0f600bfb0c093:\

                    00000001:0a4f113b:auth:\

                    39aff3a2bab6126f332b942af96d3366" )

            = 6629fae49393a05397450978507c4ef1

At this point the client may make another request, reusing the server nonce value (the server only issues a new nonce for each "401" response) but providing a new client nonce (cnonce). For subsequent requests, the hexadecimal request counter (nc) must be greater than the last value it used – otherwise an attacker could simply "replay" an old request with the same credentials. It is up to the server to ensure that the counter increases for each of the nonce values that it has issued, rejecting any bad requests appropriately. Obviously changing the method, URI and/or counter value will result in a different response value.


The server should remember nonce values that it has recently generated. It may also remember when each nonce value was issued, expiring them after a certain amount of time. If an expired value is used, the server should respond with the "401" status code and add stale=TRUE to the authentication header – indicating that the client should re-send with the new nonce provided, without prompting the user for another user name and password.


The server does not need to keep any expired nonce values – it can simply assume that any unrecognised values have expired. It is also possible for the server to only allow each nonce value to be returned once, although this forces the client to repeat every request. Note that expiring a server nonce immediately will not work, as the client would never get a chance to use it.


[edit]SIP Digest Authentication


SIP uses basically the same digest authentication algorithm. It is specified by RFC 3261.


[edit]Browser Implementation


Browsers that have fully implemented the spec:


Amaya

Gecko-based:

Mozilla Application Suite

Mozilla Firefox

Netscape 7+

iCab 3.0.3+

KHTML- and WebKit-based:

iCab 4

Konqueror

Google Chrome

Safari

Tasman-based:

Internet Explorer for Mac

Trident-based:

Internet Explorer 7+ [2]

Presto-based:

Opera

Opera Mobile

Opera Mini

Nintendo DS Browser

Nokia 770 Browser

Sony Mylo 1's Browser

Wii Internet Channel Browser


[edit]References


^ http://tools.ietf.org/html/rfc2617#section-4.13

^ http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie


[edit]See also


AKA (security)

Basic access authentication


[edit]External links


RFC 2617

RFC 2069 (obsolete)

关键看OVERVIEW开始的那一部份.

涉及的2617,2069还有SIP的RFC能看也看,

下面看看怎么来解决这个401的问题.

从上文及下面的例子可以得出一个结论,

要成功验证,需要通过MD5的算法来加密并发送验证信息给SERVER.

来看看上面401的请求要如何加密:

从这里提取所需要的验证信息:

WWW-Authenticate: Digest qop="auth",stale=false,realm="ocp.gz.com",opaque="242a40eaaadcf7d4f96838f5b047219f",nonce="MTI2OTU2Nzk5NjU0NDY2NTdlM2ZiYjkyNjcyYzIyNGI1OWMwNmVkNDA0MmRj"


username:anson

password: 12345

qop: auth

realm: ocp.gz.com

nonce:  MTI2OTU2Nzk5NjU0NDY2NTdlM2ZiYjkyNjcyYzIyNGI1OWMwNmVkNDA0MmRj

另外的一些信息:

method: REGISTER

uri: sip:ocp.gz.com

nc: 00000001

cnonce: 42BA2693


附:MD5加密算法

public class md5 {
 public static String md5s(String plainText) {
 String md5String = "";
 try {
 MessageDigest md = MessageDigest.getInstance("MD5");
 md.update(plainText.getBytes());
 byte b[] = md.digest();
 int i;
 StringBuffer buf = new StringBuffer("");
 for (int offset = 0; offset < b.length; offset++) {
 i = b[offset];
 if (i < 0)
 i += 256;
 if (i < 16)
 buf.append("0");
 buf.append(Integer.toHexString(i));
 }
 md5String = buf.toString();
 } catch (NoSuchAlgorithmException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 return md5String;
 }

这是从网上搜来的资料:

接着用MD5加密

String ha1 = md5s(username + ":" + realm + ":" + password);

String ha2 = md5s(method + ":" + uri);

最后的加密:

String response = md5s(ha1 + ":" + nonce + ":" + nc + ":" + cNonce + ":" + qop + ":"+ ha2);

取得的response在下面会有用到:

在这里加密验证完成,

重构请求如下:


REGISTER sip:ocp.gz.com SIP/2.0

Call-ID: 3143514a66f010254e8cfdcde0ef59d9@192.168.2.1

From: "anson" <sip:anson@ocp.gz.com:5060>;tag=textclientv1.0

To: <sip:anson@ocp.gz.com>

Via: SIP/2.0/TCP ocp.gz.com:5060;branch=branch1

Max-Forwards: 70

Contact: "anson" <sip:anson@192.168.2.1:5060>

Authorization: Digest response="b7431ac8d32d35a5dcfcc9f94a3bf714",cnonce="42BA2693",username="anson",nc=00000001,qop=auth,nonce="MTI2OTU2ODg3ODc5NDk2MDkwYjg4YmI4YjMwYzk0MDNmYzg4NzY2ZDg5MDUy",realm="ocp.gz.com",opaque="f14f98a15aa2f710a444d1bc4a23c5dc",uri="sip:ocp.gz.com"

CSeq: 2 REGISTER

Content-Length: 0


最后,服务器的响应:

SIP/2.0 200 OK

Via: SIP/2.0/TCP ocp.gz.com:5060;branch=branch1;received=192.168.2.1

To: <sip:anson@ocp.gz.com>;tag=-1knbda37mzjvk1690651699

From: "anson" <sip:anson@ocp.gz.com:5060>;tag=textclientv1.0

Call-ID: 3143514a66f010254e8cfdcde0ef59d9@192.168.2.1

CSeq: 2 REGISTER

Server: Oracle-OCMS/10.1.3.4.0

Supported: path,pref

Contact: "anson" <sip:anson@192.168.2.1:5060>;methods="INVITE,BYE,CANCEL,ACK,OPTIONS";expires=3600

P-Associated-URI: <sip:anson@ocp.gz.com>

Content-Length: 0


自此,一个REGISTER的请求才算完成.


相关文章
|
1月前
|
缓存 移动开发 安全
Web安全-HTTP响应拆分(CRLF注入)漏洞
Web安全-HTTP响应拆分(CRLF注入)漏洞
89 1
|
19天前
|
搜索推荐 安全 网络安全
服务器支持HTTPS的时机和条件
【10月更文挑战第23天】服务器支持HTTPS的时机和条件
14 5
|
1月前
使用Netty实现文件传输的HTTP服务器和客户端
本文通过详细的代码示例,展示了如何使用Netty框架实现一个文件传输的HTTP服务器和客户端,包括服务端的文件处理和客户端的文件请求与接收。
38 1
使用Netty实现文件传输的HTTP服务器和客户端
|
13天前
|
存储 Oracle 关系型数据库
oracle服务器存储过程中调用http
通过配置权限、创建和调用存储过程,您可以在Oracle数据库中使用UTL_HTTP包发起HTTP请求。这使得Oracle存储过程可以与外部HTTP服务进行交互,从而实现更复杂的数据处理和集成。在实际应用中,根据具体需求调整请求类型和错误处理逻辑,以确保系统的稳定性和可靠性。
15 0
|
1月前
|
存储 JSON API
HTTP 请求与响应处理:C#中的实践
【10月更文挑战第4天】在现代Web开发中,HTTP协议至关重要,无论构建Web应用还是API开发,都需要熟练掌握HTTP请求与响应处理。本文从C#角度出发,介绍HTTP基础知识,包括请求与响应结构,并通过`HttpClient`库演示如何发送GET请求及处理响应,同时分析常见错误并提供解决方案,助你更高效地完成HTTP相关任务。
83 2
|
1月前
|
前端开发 Java
学习SpringMVC,建立连接,请求,响应 SpringBoot初学,如何前后端交互(后端版)?最简单的能通过网址访问的后端服务器代码举例
文章介绍了如何使用SpringBoot创建简单的后端服务器来处理HTTP请求,包括建立连接、编写Controller处理请求,并返回响应给前端或网址。
53 0
学习SpringMVC,建立连接,请求,响应 SpringBoot初学,如何前后端交互(后端版)?最简单的能通过网址访问的后端服务器代码举例
|
2月前
|
缓存 移动开发 安全
Web安全-HTTP响应拆分(CRLF注入)漏洞
Web安全-HTTP响应拆分(CRLF注入)漏洞
149 8
|
2月前
|
开发者
HTTP状态码是由网页服务器返回的三位数字响应代码,用于表示请求的处理结果和状态
HTTP状态码是由网页服务器返回的三位数字响应代码,用于表示请求的处理结果和状态
31 1
|
5天前
|
机器学习/深度学习 人工智能 弹性计算
什么是阿里云GPU云服务器?GPU服务器优势、使用和租赁费用整理
阿里云GPU云服务器提供强大的GPU算力,适用于深度学习、科学计算、图形可视化和视频处理等多种场景。作为亚太领先的云服务提供商,阿里云的GPU云服务器具备灵活的资源配置、高安全性和易用性,支持多种计费模式,帮助企业高效应对计算密集型任务。
|
7天前
|
存储 分布式计算 固态存储
阿里云2核16G、4核32G、8核64G配置云服务器租用收费标准与活动价格参考
2核16G、8核64G、4核32G配置的云服务器处理器与内存比为1:8,这种配比的云服务器一般适用于数据分析与挖掘,Hadoop、Spark集群和数据库,缓存等内存密集型场景,因此,多为企业级用户选择。目前2核16G配置按量收费最低收费标准为0.54元/小时,按月租用标准收费标准为260.44元/1个月。4核32G配置的阿里云服务器按量收费标准最低为1.08元/小时,按月租用标准收费标准为520.88元/1个月。8核64G配置的阿里云服务器按量收费标准最低为2.17元/小时,按月租用标准收费标准为1041.77元/1个月。本文介绍这些配置的最新租用收费标准与活动价格情况,以供参考。