2004-04-28 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / Mono.Http / Mono.Http.Modules / DigestAuthenticationModule.cs
1 //
2 // Digest Authentication implementation
3 //
4 // Authors:
5 //      Greg Reinacker (gregr@rassoc.com)
6 //      Sebastien Pouliot (spouliot@motus.com)
7 //
8 // Copyright 2002-2003 Greg Reinacker, Reinacker & Associates, Inc. All rights reserved.
9 // Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com)
10 //
11 // Original source code available at
12 // http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html
13 //
14
15 using System;
16 using System.Collections.Specialized;
17 using System.Configuration;
18 using System.IO;
19 using System.Security.Cryptography;
20 using System.Security.Principal;
21 using System.Text;
22 using System.Web;
23 using System.Xml;
24
25 namespace Mono.Http.Modules
26 {
27         public class DigestAuthenticationModule : AuthenticationModule
28         {
29                 // TODO: Digest.Nonce.Lifetime="0"      Never expires
30                 static int nonceLifetime = 60;
31                 static char[] trim = {'='};
32
33                 public DigestAuthenticationModule () : base ("Digest") {}
34
35                 protected virtual bool IsValidNonce (string nonce) 
36                 {
37                         DateTime expireTime;
38
39                         // pad nonce on the right with '=' until length is a multiple of 4
40                         int numPadChars = nonce.Length % 4;
41                         if (numPadChars > 0)
42                                 numPadChars = 4 - numPadChars;
43                         string newNonce = nonce.PadRight(nonce.Length + numPadChars, '=');
44
45                         try {
46                                 byte[] decodedBytes = Convert.FromBase64String(newNonce);
47                                 string expireStr = new ASCIIEncoding().GetString(decodedBytes);
48                                 expireTime = DateTime.Parse(expireStr);
49                         }
50                         catch (FormatException e) {
51                                 return false;
52                         }
53
54                         return (DateTime.Now <= expireTime);
55                 }
56
57                 protected virtual bool GetUserByName (HttpApplication app, string username,
58                                                                            out string password, out string[] roles)
59                 {
60                         password = String.Empty;
61                         roles = new string[0];
62
63                         string userFileName = app.Request.MapPath (ConfigurationSettings.AppSettings ["Digest.Users"]);
64                         if (userFileName == null || !File.Exists (userFileName))
65                                 return false;
66
67                         XmlDocument userDoc = new XmlDocument ();
68                         userDoc.Load (userFileName);
69
70                         string xPath = String.Format ("/users/user[@name='{0}']", username);
71                         XmlNode user = userDoc.SelectSingleNode (xPath);
72
73                         if (user == null)
74                                 return false;
75
76                         password = user.Attributes ["password"].Value;
77
78                         XmlNodeList roleNodes = user.SelectNodes ("role");
79                         roles = new string [roleNodes.Count];
80                         int i = 0;
81                         foreach (XmlNode xn in roleNodes)
82                                 roles [i++] = xn.Attributes ["name"].Value;
83
84                         return true;
85                 }
86
87                 protected override bool AcceptCredentials (HttpApplication app, string authentication) 
88                 {
89                         // digest
90                         ListDictionary reqInfo = new ListDictionary ();
91
92                         string[] elems = authentication.Split( new char[] {','});
93                         foreach (string elem in elems) {
94                                 // form key="value"
95                                 string[] parts = elem.Split (new char[] {'='}, 2);
96                                 string key = parts [0].Trim (new char[] {' ','\"'});
97                                 string val = parts [1].Trim (new char[] {' ','\"'});
98                                 reqInfo.Add (key,val);
99                         }
100
101                         string username = (string) reqInfo ["username"];
102                         string password;
103                         string[] roles;
104
105                         if (!GetUserByName (app, username, out password, out roles))
106                                 return false;
107
108                         string realm = ConfigurationSettings.AppSettings ["Digest.Realm"];
109
110                         // calculate the Digest hashes
111
112                         // A1 = unq(username-value) ":" unq(realm-value) ":" passwd
113                         string A1 = String.Format ("{0}:{1}:{2}", username, realm, password);
114
115                         // H(A1) = MD5(A1)
116                         string HA1 = GetMD5HashBinHex (A1);
117
118                         // A2 = Method ":" digest-uri-value
119                         string A2 = String.Format ("{0}:{1}", app.Request.HttpMethod, (string)reqInfo["uri"]);
120
121                         // H(A2)
122                         string HA2 = GetMD5HashBinHex(A2);
123
124                         // KD(secret, data) = H(concat(secret, ":", data))
125                         // if qop == auth:
126                         // request-digest  = <"> < KD ( H(A1),     unq(nonce-value)
127                         //                              ":" nc-value
128                         //                              ":" unq(cnonce-value)
129                         //                              ":" unq(qop-value)
130                         //                              ":" H(A2)
131                         //                            ) <">
132                         // if qop is missing,
133                         // request-digest  = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
134
135                         string unhashedDigest;
136                         if (reqInfo["qop"] != null) {
137                                 unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
138                                         HA1,
139                                         (string)reqInfo["nonce"],
140                                         (string)reqInfo["nc"],
141                                         (string)reqInfo["cnonce"],
142                                         (string)reqInfo["qop"],
143                                         HA2);
144                         }
145                         else {
146                                 unhashedDigest = String.Format("{0}:{1}:{2}",
147                                         HA1,
148                                         (string)reqInfo["nonce"],
149                                         HA2);
150                         }
151
152                         string hashedDigest = GetMD5HashBinHex (unhashedDigest);
153
154                         bool isNonceStale = !IsValidNonce((string)reqInfo["nonce"]);
155                         app.Context.Items["staleNonce"] = isNonceStale;
156
157                         bool result = (((string)reqInfo["response"] == hashedDigest) && (!isNonceStale));
158                         if (result) {
159                                 IIdentity id = new GenericIdentity (username, AuthenticationMethod);
160                                 app.Context.User = new GenericPrincipal (id, roles);
161                         }
162                         return result;
163                 }
164
165                 #region Event Handlers
166
167                 public override void OnEndRequest(object source, EventArgs eventArgs)
168                 {
169                         // We add the WWW-Authenticate header here, so if an authorization 
170                         // fails elsewhere than in this module, we can still request authentication 
171                         // from the client.
172
173                         HttpApplication app = (HttpApplication) source;
174                         if (app.Response.StatusCode != 401 || !AuthenticationRequired)
175                                 return;
176                                 
177                         string realm = ConfigurationSettings.AppSettings ["Digest.Realm"];
178                         string nonce = GetCurrentNonce ();
179                         bool isNonceStale = false;
180                         object staleObj = app.Context.Items ["staleNonce"];
181                         if (staleObj != null)
182                                 isNonceStale = (bool)staleObj;
183
184                         StringBuilder challenge = new StringBuilder ("Digest realm=\"");
185                         challenge.Append(realm);
186                         challenge.Append("\"");
187                         challenge.Append(", nonce=\"");
188                         challenge.Append(nonce);
189                         challenge.Append("\"");
190                         challenge.Append(", opaque=\"0000000000000000\"");
191                         challenge.Append(", stale=");
192                         challenge.Append(isNonceStale ? "true" : "false");
193                         challenge.Append(", algorithm=MD5");
194                         challenge.Append(", qop=\"auth\"");
195
196                         app.Response.AppendHeader("WWW-Authenticate", challenge.ToString());
197                         app.Response.StatusCode = 401;
198                 }
199
200                 #endregion
201
202                 private string GetMD5HashBinHex (string toBeHashed)
203                 {
204                         MD5 hash = MD5.Create ();
205                         byte[] result = hash.ComputeHash (Encoding.ASCII.GetBytes (toBeHashed));
206
207                         StringBuilder sb = new StringBuilder ();
208                         foreach (byte b in result)
209                                 sb.Append (b.ToString ("x2"));
210                         return sb.ToString ();
211                 }
212
213                 protected virtual string GetCurrentNonce ()
214                 {
215                         DateTime nonceTime = DateTime.Now.AddSeconds (nonceLifetime);
216                         byte[] expireBytes = Encoding.ASCII.GetBytes (nonceTime.ToString ("G"));
217                         string nonce = Convert.ToBase64String (expireBytes);
218                         // nonce can't end in '=', so trim them from the end
219                         nonce = nonce.TrimEnd (trim);
220                         return nonce;
221                 }
222         }
223 }