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