vibe.http.auth.digest_auth 0/71(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
/** Implements HTTP Digest Authentication. This is a minimal implementation based on RFC 2069. Copyright: © 2015 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Kai Nacke */ module vibe.http.auth.digest_auth; import vibe.http.server; import vibe.core.log; import std.base64; import std.datetime; import std.digest.md; import std.exception; import std.string; import std.uuid; @safe: enum NonceState { Valid, Expired, Invalid } class DigestAuthInfo { @safe: string realm; ubyte[] secret; ulong timeout; this() { secret = randomUUID().data.dup; timeout = 300; } string createNonce(in HTTPServerRequest req) { auto now = Clock.currTime(UTC()).stdTime(); auto time = () @trusted { return *cast(ubyte[now.sizeof]*)&now; } (); MD5 md5; md5.put(time); md5.put(secret); auto data = md5.finish(); return Base64.encode(time ~ data); } NonceState checkNonce(in string nonce, in HTTPServerRequest req) { auto now = Clock.currTime(UTC()).stdTime(); ubyte[] decoded = Base64.decode(nonce); if (decoded.length != now.sizeof + secret.length) return NonceState.Invalid; auto timebytes = decoded[0 .. now.sizeof]; auto time = () @trusted { return (cast(typeof(now)[])timebytes)[0]; } (); if (timeout + time > now) return NonceState.Expired; MD5 md5; md5.put(timebytes); md5.put(secret); auto data = md5.finish(); if (data[] != decoded[now.sizeof .. $]) return NonceState.Invalid; return NonceState.Valid; } } private bool checkDigest(scope HTTPServerRequest req, DigestAuthInfo info, scope DigestHashCallback pwhash, out bool stale, out string username) { stale = false; username = ""; auto pauth = "Authorization" in req.headers; if (pauth && (*pauth).startsWith("Digest ")) { string realm, nonce, response, uri, algorithm; foreach (param; split((*pauth)[7 .. $], ",")) { auto kv = split(param, "="); switch (kv[0].strip().toLower()) { default: break; case "realm": realm = kv[1][1..$-1]; break; case "username": username = kv[1][1..$-1]; break; case "nonce": nonce = kv[1][1..$-1]; break; case "uri": uri = kv[1][1..$-1]; break; case "response": response = kv[1][1..$-1]; break; case "algorithm": algorithm = kv[1][1..$-1]; break; } } if (realm != info.realm) return false; if (algorithm !is null && algorithm != "MD5") return false; auto nonceState = info.checkNonce(nonce, req); if (nonceState != NonceState.Valid) { stale = nonceState == NonceState.Expired; return false; } auto ha1 = pwhash(realm, username); auto ha2 = toHexString!(LetterCase.lower)(md5Of(httpMethodString(req.method) ~ ":" ~ uri)); auto calcresponse = toHexString!(LetterCase.lower)(md5Of(ha1 ~ ":" ~ nonce ~ ":" ~ ha2 )); if (response[] == calcresponse[]) return true; } return false; } /** Returns a request handler that enforces request to be authenticated using HTTP Digest Auth. */ HTTPServerRequestDelegate performDigestAuth(DigestAuthInfo info, scope DigestHashCallback pwhash) { void handleRequest(HTTPServerRequest req, HTTPServerResponse res) @safe { bool stale; string username; if (checkDigest(req, info, pwhash, stale, username)) { req.username = username; return ; } // else output an error page res.statusCode = HTTPStatus.unauthorized; res.contentType = "text/plain"; res.headers["WWW-Authenticate"] = "Digest realm=\""~info.realm~"\", nonce=\""~info.createNonce(req)~"\", stale="~(stale?"true":"false"); res.bodyWriter.write("Authorization required"); } return &handleRequest; } /// Scheduled for deprecation - use a `@safe` callback instead. HTTPServerRequestDelegate performDigestAuth(DigestAuthInfo info, scope string delegate(string, string) @system pwhash) @system { return performDigestAuth(info, (r, u) @trusted => pwhash(r, u)); } /** Enforces HTTP Digest Auth authentication on the given req/res pair. Params: req = Request object that is to be checked res = Response object that will be used for authentication errors info = Digest authentication info object pwhash = A delegate queried for returning the digest password Returns: Returns the name of the authenticated user. Throws: Throws a HTTPStatusExeption in case of an authentication failure. */ string performDigestAuth(scope HTTPServerRequest req, scope HTTPServerResponse res, DigestAuthInfo info, scope DigestHashCallback pwhash) { bool stale; string username; if (checkDigest(req, info, pwhash, stale, username)) return username; res.headers["WWW-Authenticate"] = "Digest realm=\""~info.realm~"\", nonce=\""~info.createNonce(req)~"\", stale="~(stale?"true":"false"); throw new HTTPStatusException(HTTPStatus.unauthorized); } /// Scheduled for deprecation - use a `@safe` callback instead. string performDigestAuth(scope HTTPServerRequest req, scope HTTPServerResponse res, DigestAuthInfo info, scope string delegate(string, string) @system pwhash) @system { return performDigestAuth(req, res, info, (r, u) @trusted => pwhash(r, u)); } /** Creates the digest password from the user name, realm and password. Params: realm = The realm user = The user name password = The plain text password Returns: Returns the digest password */ string createDigestPassword(string realm, string user, string password) { return toHexString!(LetterCase.lower)(md5Of(user ~ ":" ~ realm ~ ":" ~ password)).dup; } alias DigestHashCallback = string delegate(string realm, string user);