1/*
2 * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.security.ntlm;
27
28import java.util.Arrays;
29import java.util.Locale;
30
31/**
32 * The NTLM server, not multi-thread enabled.<p>
33 * Example:
34 * <pre>
35 * Server server = new Server(null, "REALM") {
36 *     public char[] getPassword(String ntdomain, String username) {
37 *         switch (username) {
38 *             case "dummy": return "t0pSeCr3t".toCharArray();
39 *             case "guest": return "".toCharArray();
40 *             default: return null;
41 *         }
42 *     }
43 * };
44 * // Receive client request as type1
45 * byte[] type2 = server.type2(type1, nonce);
46 * // Send type2 to client and receive type3
47 * verify(type3, nonce);
48 * </pre>
49 */
50public abstract class Server extends NTLM {
51    private final String domain;
52    private final boolean allVersion;
53    /**
54     * Creates a Server instance.
55     * @param version the NTLM version to use, which can be:
56     * <ul>
57     * <li>NTLM: Original NTLM v1
58     * <li>NTLM2: NTLM v1 with Client Challenge
59     * <li>NTLMv2: NTLM v2
60     * </ul>
61     * If null, all versions will be supported. Please note that unless NTLM2
62     * is selected, authentication succeeds if one of LM (or LMv2) or
63     * NTLM (or NTLMv2) is verified.
64     * @param domain the domain, must not be null
65     * @throws NTLMException if {@code domain} is null.
66     */
67    public Server(String version, String domain) throws NTLMException {
68        super(version);
69        if (domain == null) {
70            throw new NTLMException(NTLMException.PROTOCOL,
71                    "domain cannot be null");
72        }
73        this.allVersion = (version == null);
74        this.domain = domain;
75        debug("NTLM Server: (t,version) = (%s,%s)\n", domain, version);
76    }
77
78    /**
79     * Generates the Type 2 message
80     * @param type1 the Type1 message received, must not be null
81     * @param nonce the random 8-byte array to be used in message generation,
82     * must not be null
83     * @return the message generated
84     * @throws NTLMException if the incoming message is invalid, or
85     * {@code nonce} is null.
86     */
87    public byte[] type2(byte[] type1, byte[] nonce) throws NTLMException {
88        if (nonce == null) {
89            throw new NTLMException(NTLMException.PROTOCOL,
90                    "nonce cannot be null");
91        }
92        debug("NTLM Server: Type 1 received\n");
93        if (type1 != null) debug(type1);
94        Writer p = new Writer(2, 32);
95        // Negotiate NTLM2 Key, Target Type Domain,
96        // Negotiate NTLM, Request Target, Negotiate unicode
97        int flags = 0x90205;
98        p.writeSecurityBuffer(12, domain, true);
99        p.writeInt(20, flags);
100        p.writeBytes(24, nonce);
101        debug("NTLM Server: Type 2 created\n");
102        debug(p.getBytes());
103        return p.getBytes();
104    }
105
106    /**
107     * Verifies the Type3 message received from client and returns
108     * various negotiated information.
109     * @param type3 the incoming Type3 message from client, must not be null
110     * @param nonce the same nonce provided in {@link #type2}, must not be null
111     * @return client username, client hostname, and the request target
112     * @throws NTLMException if the incoming message is invalid, or
113     * {@code nonce} is null.
114     */
115    public String[] verify(byte[] type3, byte[] nonce)
116            throws NTLMException {
117        if (type3 == null || nonce == null) {
118            throw new NTLMException(NTLMException.PROTOCOL,
119                    "type1 or nonce cannot be null");
120        }
121        debug("NTLM Server: Type 3 received\n");
122        if (type3 != null) debug(type3);
123        Reader r = new Reader(type3);
124        String username = r.readSecurityBuffer(36, true);
125        String hostname = r.readSecurityBuffer(44, true);
126        String incomingDomain = r.readSecurityBuffer(28, true);
127        /*if (incomingDomain != null && !incomingDomain.equals(domain)) {
128            throw new NTLMException(NTLMException.DOMAIN_UNMATCH,
129                    "Wrong domain: " + incomingDomain +
130                    " vs " + domain); // Needed?
131        }*/
132
133        boolean verified = false;
134        char[] password = getPassword(incomingDomain, username);
135        if (password == null) {
136            throw new NTLMException(NTLMException.USER_UNKNOWN,
137                    "Unknown user");
138        }
139        byte[] incomingLM = r.readSecurityBuffer(12);
140        byte[] incomingNTLM = r.readSecurityBuffer(20);
141
142        if (!verified && (allVersion || v == Version.NTLM)) {
143            if (incomingLM.length > 0) {
144                byte[] pw1 = getP1(password);
145                byte[] lmhash = calcLMHash(pw1);
146                byte[] lmresponse = calcResponse (lmhash, nonce);
147                if (Arrays.equals(lmresponse, incomingLM)) {
148                    verified = true;
149                }
150            }
151            if (incomingNTLM.length > 0) {
152                byte[] pw2 = getP2(password);
153                byte[] nthash = calcNTHash(pw2);
154                byte[] ntresponse = calcResponse (nthash, nonce);
155                if (Arrays.equals(ntresponse, incomingNTLM)) {
156                    verified = true;
157                }
158            }
159            debug("NTLM Server: verify using NTLM: " + verified  + "\n");
160        }
161        if (!verified && (allVersion || v == Version.NTLM2)) {
162            byte[] pw2 = getP2(password);
163            byte[] nthash = calcNTHash(pw2);
164            byte[] clientNonce = Arrays.copyOf(incomingLM, 8);
165            byte[] ntlmresponse = ntlm2NTLM(nthash, clientNonce, nonce);
166            if (Arrays.equals(incomingNTLM, ntlmresponse)) {
167                verified = true;
168            }
169            debug("NTLM Server: verify using NTLM2: " + verified + "\n");
170        }
171        if (!verified && (allVersion || v == Version.NTLMv2)) {
172            byte[] pw2 = getP2(password);
173            byte[] nthash = calcNTHash(pw2);
174            if (incomingLM.length > 0) {
175                byte[] clientNonce = Arrays.copyOfRange(
176                        incomingLM, 16, incomingLM.length);
177                byte[] lmresponse = calcV2(nthash,
178                        username.toUpperCase(Locale.US)+incomingDomain,
179                        clientNonce, nonce);
180                if (Arrays.equals(lmresponse, incomingLM)) {
181                    verified = true;
182                }
183            }
184            if (incomingNTLM.length > 0) {
185                // We didn't sent alist in type2(), so there
186                // is nothing to check here.
187                byte[] clientBlob = Arrays.copyOfRange(
188                        incomingNTLM, 16, incomingNTLM.length);
189                byte[] ntlmresponse = calcV2(nthash,
190                        username.toUpperCase(Locale.US)+incomingDomain,
191                        clientBlob, nonce);
192                if (Arrays.equals(ntlmresponse, incomingNTLM)) {
193                    verified = true;
194                }
195            }
196            debug("NTLM Server: verify using NTLMv2: " + verified + "\n");
197        }
198        if (!verified) {
199            throw new NTLMException(NTLMException.AUTH_FAILED,
200                    "None of LM and NTLM verified");
201        }
202        return new String[] {username, hostname, incomingDomain};
203    }
204
205    /**
206     * Retrieves the password for a given user. This method should be
207     * overridden in a concrete class.
208     * @param domain can be null
209     * @param username must not be null
210     * @return the password for the user, or null if unknown
211     */
212    public abstract char[] getPassword(String domain, String username);
213}
214