Mass whitespace changes (Style Warnings)
[aaf/authz.git] / cadi / core / src / main / java / org / onap / aaf / cadi / taf / basic / BasicHttpTaf.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.taf.basic;
23
24 import java.io.IOException;
25 import java.security.Principal;
26 import java.util.Map;
27 import java.util.TreeMap;
28
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
31
32 import org.onap.aaf.cadi.Access;
33 import org.onap.aaf.cadi.Access.Level;
34 import org.onap.aaf.cadi.BasicCred;
35 import org.onap.aaf.cadi.CachedPrincipal;
36 import org.onap.aaf.cadi.CachedPrincipal.Resp;
37 import org.onap.aaf.cadi.CredVal;
38 import org.onap.aaf.cadi.CredVal.Type;
39 import org.onap.aaf.cadi.CredValDomain;
40 import org.onap.aaf.cadi.Taf;
41 import org.onap.aaf.cadi.principal.BasicPrincipal;
42 import org.onap.aaf.cadi.principal.CachedBasicPrincipal;
43 import org.onap.aaf.cadi.taf.HttpTaf;
44 import org.onap.aaf.cadi.taf.TafResp;
45 import org.onap.aaf.cadi.taf.TafResp.RESP;
46 import org.onap.aaf.cadi.taf.dos.DenialOfServiceTaf;
47
48 /**
49  * BasicHttpTaf
50  * 
51  * This TAF implements the "Basic Auth" protocol.  
52  * 
53  * WARNING! It is true for any implementation of "Basic Auth" that the password is passed unencrypted.  
54  * This is because the expectation, when designed years ago, was that it would only be used in 
55  * conjunction with SSL (https).  It is common, however, for users to ignore this on the assumption that
56  * their internal network is secure, or just ignorance.  Therefore, a WARNING will be printed
57  * when the HTTP Channel is not encrypted (unless explicitly turned off).
58  * 
59  * @author Jonathan
60  *
61  */
62 public class BasicHttpTaf implements HttpTaf {
63     private Access access;
64     private String realm;
65     private CredVal rbac;
66     private Map<String,CredVal> rbacs = new TreeMap<>();
67     private boolean warn;
68     private long timeToLive;
69     
70     public BasicHttpTaf(Access access, CredVal rbac, String realm, long timeToLive, boolean turnOnWarning) {
71         this.access = access;
72         this.realm = realm;
73         this.rbac = rbac;
74         this.warn = turnOnWarning;
75         this.timeToLive = timeToLive;
76     }
77
78     public void add(final CredValDomain cvd) {
79         rbacs.put(cvd.domain(), cvd);
80     }
81     
82     /**
83      * Note: BasicHttp works for either Carbon Based (Humans) or Silicon Based (machine) Lifeforms.  
84      * @see Taf
85      */
86     public TafResp validate(Taf.LifeForm reading, HttpServletRequest req, HttpServletResponse resp) {
87         // See if Request implements BasicCred (aka CadiWrap or other), and if User/Pass has already been set separately
88         if (req instanceof BasicCred) {
89             BasicCred bc = (BasicCred)req;
90             if (bc.getUser()!=null) { // CadiWrap, if set, makes sure User & Password are both valid, or both null
91                 if (DenialOfServiceTaf.isDeniedID(bc.getUser())!=null) {
92                     return DenialOfServiceTaf.respDenyID(access,bc.getUser());
93                 }
94                 CachedBasicPrincipal bp = new CachedBasicPrincipal(this,bc,realm,timeToLive);
95                 
96                 // Be able to do Organizational specific lookups by Domain
97                 CredVal cv = rbacs.get(bp.getDomain());
98                 if (cv==null) {
99                     cv = rbac;
100                 }
101                 
102                 // ONLY FOR Last Ditch DEBUGGING... 
103                 // access.log(Level.WARN,bp.getName() + ":" + new String(bp.getCred()));
104                 if (cv.validate(bp.getName(),Type.PASSWORD,bp.getCred(),req)) {
105                     return new BasicHttpTafResp(access,bp,bp.getName()+" authenticated by password",RESP.IS_AUTHENTICATED,resp,realm,false);
106                 } else {
107                     //TODO may need timed retries in a given time period
108                     return new BasicHttpTafResp(access,null,buildMsg(bp,req,"user/pass combo invalid for ",bc.getUser(),"from",req.getRemoteAddr()), 
109                             RESP.TRY_AUTHENTICATING,resp,realm,true);
110                 }
111             }
112         }
113         // Get User/Password from Authorization Header value
114         String authz = req.getHeader("Authorization");
115         if (authz != null && authz.startsWith("Basic ")) {
116             if (warn&&!req.isSecure()) {
117                 access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel");
118             }
119             try {
120                 CachedBasicPrincipal ba = new CachedBasicPrincipal(this,authz,realm,timeToLive);
121                 if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) {
122                     return DenialOfServiceTaf.respDenyID(access,ba.getName());
123                 }
124                 
125                 final int at = ba.getName().indexOf('@');
126                 CredVal cv = rbacs.get(ba.getName().substring(at+1));
127                 if (cv==null) { 
128                     cv = rbac; // default
129                 }
130
131                 // ONLY FOR Last Ditch DEBUGGING... 
132                 // access.log(Level.WARN,ba.getName() + ":" + new String(ba.getCred()));
133                 if (cv.validate(ba.getName(), Type.PASSWORD, ba.getCred(), req)) {
134                     return new BasicHttpTafResp(access,ba, ba.getName()+" authenticated by BasicAuth password",RESP.IS_AUTHENTICATED,resp,realm,false);
135                 } else {
136                     //TODO may need timed retries in a given time period
137                     return new BasicHttpTafResp(access,null,buildMsg(ba,req,"user/pass combo invalid"), 
138                             RESP.TRY_AUTHENTICATING,resp,realm,true);
139                 }
140             } catch (IOException e) {
141                 String msg = buildMsg(null,req,"Failed HTTP Basic Authorization (", e.getMessage(), ')');
142                 access.log(Level.INFO,msg);
143                 return new BasicHttpTafResp(access,null,msg, RESP.TRY_AUTHENTICATING, resp, realm,true);
144             }
145         }
146         return new BasicHttpTafResp(access,null,"Requesting HTTP Basic Authorization",RESP.TRY_AUTHENTICATING,resp,realm,false);
147     }
148     
149     protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) {
150         StringBuilder sb = new StringBuilder();
151         if (pr!=null) {
152             sb.append("user=");
153             sb.append(pr.getName());
154             sb.append(',');
155         }
156         sb.append("ip=");
157         sb.append(req.getRemoteAddr());
158         sb.append(",port=");
159         sb.append(req.getRemotePort());
160         if (msg.length>0) {
161             sb.append(",msg=\"");
162             for (Object s : msg) {
163                 sb.append(s.toString());
164             }
165             sb.append('"');
166         }
167         return sb.toString();
168     }
169     
170     public void addCredVal(final String realm, final CredVal cv) {
171         rbacs.put(realm, cv);
172     }
173
174     public CredVal getCredVal(String key) {
175         CredVal cv = rbacs.get(key);
176         if (cv==null) {
177             cv = rbac;
178         }
179         return cv;
180     }
181     
182     @Override
183     public Resp revalidate(CachedPrincipal prin, Object state) {
184         if (prin instanceof BasicPrincipal) {
185             BasicPrincipal ba = (BasicPrincipal)prin;
186             if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) {
187                 return Resp.UNVALIDATED;
188             }
189             return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED;
190         }
191         return Resp.NOT_MINE;
192     }
193     
194     public String toString() {
195         return "Basic Auth enabled on realm: " + realm;
196     }
197
198 }