1 /*
   2  * Copyright (c) 1997, 2016, 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 
  26 package sun.net.www.protocol.http;
  27 
  28 import java.net.URL;
  29 import java.net.URI;
  30 import java.net.URISyntaxException;
  31 import java.net.PasswordAuthentication;
  32 import java.nio.ByteBuffer;
  33 import java.nio.CharBuffer;
  34 import java.nio.charset.Charset;
  35 import java.io.IOException;
  36 import java.io.OutputStream;
  37 import java.util.Arrays;
  38 import java.util.Base64;
  39 import java.util.Objects;
  40 import sun.net.www.HeaderParser;
  41 import static java.nio.charset.StandardCharsets.UTF_8;
  42 import static java.nio.charset.StandardCharsets.ISO_8859_1;
  43 
  44 /**
  45  * BasicAuthentication: Encapsulate an http server authentication using
  46  * the "basic" scheme.
  47  *
  48  * @author Bill Foote
  49  */
  50 
  51 
  52 class BasicAuthentication extends AuthenticationInfo {
  53 
  54     private static final long serialVersionUID = 100L;
  55 
  56     /** The authentication string for this host, port, and realm.  This is
  57         a simple BASE64 encoding of "login:password".    */
  58     final String auth;
  59 
  60     /**
  61      * Create a BasicAuthentication
  62      */
  63     public BasicAuthentication(boolean isProxy, String host, int port,
  64                                String realm, PasswordAuthentication pw,
  65                                boolean isUTF8, String authenticatorKey) {
  66         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
  67               AuthScheme.BASIC, host, port, realm,
  68               Objects.requireNonNull(authenticatorKey));
  69         this.auth = authValueFrom(pw, isUTF8);
  70         this.pw = pw;
  71     }
  72 
  73     /**
  74      * Create a BasicAuthentication
  75      */
  76     public BasicAuthentication(boolean isProxy, String host, int port,
  77                                String realm, String auth,
  78                                String authenticatorKey) {
  79         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
  80               AuthScheme.BASIC, host, port, realm,
  81               Objects.requireNonNull(authenticatorKey));
  82         this.auth = "Basic " + auth;
  83     }
  84 
  85     /**
  86      * Create a BasicAuthentication
  87      */
  88     public BasicAuthentication(boolean isProxy, URL url, String realm,
  89                                PasswordAuthentication pw, boolean isUTF8,
  90                                String authenticatorKey) {
  91         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
  92               AuthScheme.BASIC, url, realm,
  93               Objects.requireNonNull(authenticatorKey));
  94         this.auth = authValueFrom(pw, isUTF8);
  95         this.pw = pw;
  96     }
  97 
  98     private static String authValueFrom(PasswordAuthentication pw, boolean isUTF8) {
  99         String plain = pw.getUserName() + ":";
 100         char[] password = pw.getPassword();
 101         CharBuffer cbuf = CharBuffer.allocate(plain.length() + password.length);
 102         cbuf.put(plain).put(password).flip();
 103         Charset charset = isUTF8 ? UTF_8 : ISO_8859_1;
 104         ByteBuffer buf = charset.encode(cbuf);
 105         ByteBuffer enc = Base64.getEncoder().encode(buf);
 106         String ret = "Basic " + new String(enc.array(), enc.position(), enc.remaining(), ISO_8859_1);
 107         Arrays.fill(buf.array(), (byte) 0);
 108         Arrays.fill(enc.array(), (byte) 0);
 109         Arrays.fill(cbuf.array(), (char) 0);
 110         return ret;
 111     }
 112 
 113     /**
 114      * Create a BasicAuthentication
 115      */
 116     public BasicAuthentication(boolean isProxy, URL url, String realm,
 117                                String auth, String authenticatorKey) {
 118         super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION,
 119               AuthScheme.BASIC, url, realm,
 120               Objects.requireNonNull(authenticatorKey));
 121         this.auth = "Basic " + auth;
 122     }
 123 
 124     /**
 125      * @return true if this authentication supports preemptive authorization
 126      */
 127     @Override
 128     public boolean supportsPreemptiveAuthorization() {
 129         return true;
 130     }
 131 
 132     /**
 133      * Set header(s) on the given connection. This will only be called for
 134      * definitive (i.e. non-preemptive) authorization.
 135      * @param conn The connection to apply the header(s) to
 136      * @param p A source of header values for this connection, if needed.
 137      * @param raw The raw header values for this connection, if needed.
 138      * @return true if all goes well, false if no headers were set.
 139      */
 140     @Override
 141     public boolean setHeaders(HttpURLConnection conn, HeaderParser p, String raw) {
 142         conn.setAuthenticationProperty(getHeaderName(), getHeaderValue(null,null));
 143         return true;
 144     }
 145 
 146     /**
 147      * @return the value of the HTTP header this authentication wants set
 148      */
 149     @Override
 150     public String getHeaderValue(URL url, String method) {
 151         /* For Basic the authorization string does not depend on the request URL
 152          * or the request method
 153          */
 154         return auth;
 155     }
 156 
 157     /**
 158      * For Basic Authentication, the security parameters can never be stale.
 159      * In other words there is no possibility to reuse the credentials.
 160      * They are always either valid or invalid.
 161      */
 162     @Override
 163     public boolean isAuthorizationStale (String header) {
 164         return false;
 165     }
 166 
 167     /**
 168      * @return the common root path between npath and path.
 169      * This is used to detect when we have an authentication for two
 170      * paths and the root of th authentication space is the common root.
 171      */
 172 
 173     static String getRootPath(String npath, String opath) {
 174         int index = 0;
 175         int toindex;
 176 
 177         /* Must normalize so we don't get confused by ../ and ./ segments */
 178         try {
 179             npath = new URI (npath).normalize().getPath();
 180             opath = new URI (opath).normalize().getPath();
 181         } catch (URISyntaxException e) {
 182             /* ignore error and use the old value */
 183         }
 184 
 185         while (index < opath.length()) {
 186             toindex = opath.indexOf('/', index+1);
 187             if (toindex != -1 && opath.regionMatches(0, npath, 0, toindex+1))
 188                 index = toindex;
 189             else
 190                 return opath.substring(0, index+1);
 191         }
 192         /*should not reach here. If we do simply return npath*/
 193         return npath;
 194     }
 195 }