|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Net |
| 4 | + class IMAP < Protocol |
| 5 | + module SASL |
| 6 | + |
| 7 | + # Authenticator for the "+CRAM-MD5+" SASL mechanism, specified in |
| 8 | + # RFC2195[https://tools.ietf.org/html/rfc2195]. See Net::IMAP#authenticate. |
| 9 | + # |
| 10 | + # == Deprecated |
| 11 | + # |
| 12 | + # +CRAM-MD5+ is obsolete and insecure. It is included for compatibility with |
| 13 | + # existing servers. |
| 14 | + # {draft-ietf-sasl-crammd5-to-historic}[https://tools.ietf.org/html/draft-ietf-sasl-crammd5-to-historic-00.html] |
| 15 | + # recommends using +SCRAM-*+ or +PLAIN+ protected by TLS instead. |
| 16 | + # |
| 17 | + # Additionally, RFC8314[https://tools.ietf.org/html/rfc8314] discourage the use |
| 18 | + # of cleartext and recommends TLS version 1.2 or greater be used for all |
| 19 | + # traffic. With TLS +CRAM-MD5+ is okay, but so is +PLAIN+ |
| 20 | + class CramMD5Authenticator |
| 21 | + def process(challenge) |
| 22 | + digest = hmac_md5(challenge, @password) |
| 23 | + return @user + " " + digest |
| 24 | + ensure |
| 25 | + @done = true |
| 26 | + end |
| 27 | + |
| 28 | + def done?; @done end |
| 29 | + |
| 30 | + private |
| 31 | + |
| 32 | + def initialize(user, password, warn_deprecation: true, **_ignored) |
| 33 | + if warn_deprecation |
| 34 | + warn "WARNING: CRAM-MD5 mechanism is deprecated." # TODO: recommend SCRAM |
| 35 | + end |
| 36 | + require "digest/md5" |
| 37 | + @user = user |
| 38 | + @password = password |
| 39 | + @done = false |
| 40 | + end |
| 41 | + |
| 42 | + def hmac_md5(text, key) |
| 43 | + if key.length > 64 |
| 44 | + key = Digest::MD5.digest(key) |
| 45 | + end |
| 46 | + |
| 47 | + k_ipad = key + "\0" * (64 - key.length) |
| 48 | + k_opad = key + "\0" * (64 - key.length) |
| 49 | + for i in 0..63 |
| 50 | + k_ipad[i] = (k_ipad[i].ord ^ 0x36).chr |
| 51 | + k_opad[i] = (k_opad[i].ord ^ 0x5c).chr |
| 52 | + end |
| 53 | + |
| 54 | + digest = Digest::MD5.digest(k_ipad + text) |
| 55 | + |
| 56 | + return Digest::MD5.hexdigest(k_opad + digest) |
| 57 | + end |
| 58 | + |
| 59 | + Net::IMAP.add_authenticator "CRAM-MD5", self |
| 60 | + end |
| 61 | + end |
| 62 | + |
| 63 | + CramMD5Authenticator = SASL::CramMD5Authenticator |
| 64 | + deprecate_constant :CramMD5Authenticator |
| 65 | + |
| 66 | + end |
| 67 | +end |
0 commit comments