1: <?php
2: /**
3: * IMSP authentication class for CRAM-MD5 authentication.
4: *
5: * Required parameters:<pre>
6: * 'username' Username to logon to IMSP server as.
7: * 'password' Password for current user.
8: * 'server' The hostname of the IMSP server.
9: * 'port' The port of the IMSP server.</pre>
10: *
11: * Copyright 2003-2012 Horde LLC (http://www.horde.org/)
12: *
13: * See the enclosed file COPYING for license information (LGPL). If you
14: * did not receive this file, see http://www.horde.org/licenses/lgpl21.
15: *
16: * @author Michael Rubinsky <mrubinsk@horde.org>
17: * @package Horde_Imsp
18: */
19: class Horde_Imsp_Auth_CramMd5 extends Horde_Imsp_Auth_Base
20: {
21: /**
22: * Private authentication function. Provides actual authentication code.
23: *
24: * @return boolean
25: */
26: protected function _authenticate()
27: {
28: $userId = $this->_params['username'];
29: $credentials = $this->_params['password'];
30: $this->_imsp->send('AUTHENTICATE CRAM-MD5');
31:
32: /* Get response and decode it. */
33: $server_response = $this->_imsp->receive();
34: $server_response = base64_decode(trim(substr($server_response, 2)));
35:
36: /* Build and base64 encode the response to the challange. */
37: $response_to_send = $userId . ' ' . $this->_hmac($credentials, $server_response);
38: $command_string = base64_encode($response_to_send);
39:
40: /* Send the response. */
41: $this->_imsp->send($command_string, false);
42: $result = $this->_imsp->receive();
43:
44: if ($result != 'OK') {
45: $this->_imsp->_logger->err('Login to IMSP host failed.');
46: return false;
47: }
48:
49: return true;
50: }
51:
52: /**
53: * RFC 2104 HMAC implementation.
54: *
55: * @access private
56: * @param string $key The HMAC key.
57: * @param string $data The data to hash with the key.
58: *
59: * @return string The MD5 HMAC.
60: */
61: protected function _hmac($key, $data)
62: {
63: if (function_exists('hash_hmac')) {
64: return hash_hmac('md5', $data, $key);
65: }
66:
67: /* Byte length for md5. */
68: $b = 64;
69:
70: if (strlen($key) > $b) {
71: $key = pack('H*', md5($key));
72: }
73:
74: $key = str_pad($key, $b, chr(0x00));
75: $ipad = str_pad('', $b, chr(0x36));
76: $opad = str_pad('', $b, chr(0x5c));
77: $k_ipad = $key ^ $ipad;
78: $k_opad = $key ^ $opad;
79: return md5($k_opad . pack('H*', md5($k_ipad . $data)));
80: }
81:
82: /**
83: * Force a logout command to the imsp stream.
84: *
85: */
86: public function logout()
87: {
88: $this->_imsp->logout();
89: }
90:
91: /**
92: * Return the driver type
93: *
94: * @return string the type of this IMSP_Auth driver
95: */
96: public function getDriverType()
97: {
98: return 'cram_md5';
99: }
100:
101: }
102: