3130e5b2b692018da6a89a4b7548a539ef00eeb8
[aaf/authz.git] / auth / auth-certman / src / main / java / org / onap / aaf / auth / cm / service / CMService.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 IBM.
7  * ===========================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END====================================================
20  *
21  */
22
23 package org.onap.aaf.auth.cm.service;
24
25 import java.io.IOException;
26 import java.net.InetAddress;
27 import java.net.UnknownHostException;
28 import java.nio.ByteBuffer;
29 import java.security.NoSuchAlgorithmException;
30 import java.security.cert.Certificate;
31 import java.security.cert.X509Certificate;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Date;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Set;
39
40 import org.onap.aaf.auth.cm.AAF_CM;
41 import org.onap.aaf.auth.cm.ca.CA;
42 import org.onap.aaf.auth.cm.ca.X509andChain;
43 import org.onap.aaf.auth.cm.cert.BCFactory;
44 import org.onap.aaf.auth.cm.cert.CSRMeta;
45 import org.onap.aaf.auth.cm.data.CertDrop;
46 import org.onap.aaf.auth.cm.data.CertRenew;
47 import org.onap.aaf.auth.cm.data.CertReq;
48 import org.onap.aaf.auth.cm.data.CertResp;
49 import org.onap.aaf.auth.cm.validation.CertmanValidator;
50 import org.onap.aaf.auth.common.Define;
51 import org.onap.aaf.auth.dao.CassAccess;
52 import org.onap.aaf.auth.dao.cass.ArtiDAO;
53 import org.onap.aaf.auth.dao.cass.CacheInfoDAO;
54 import org.onap.aaf.auth.dao.cass.CertDAO;
55 import org.onap.aaf.auth.dao.cass.CertDAO.Data;
56 import org.onap.aaf.auth.dao.cass.CredDAO;
57 import org.onap.aaf.auth.dao.cass.HistoryDAO;
58 import org.onap.aaf.auth.dao.cass.Status;
59 import org.onap.aaf.auth.dao.hl.Question;
60 import org.onap.aaf.auth.env.AuthzTrans;
61 import org.onap.aaf.auth.layer.Result;
62 import org.onap.aaf.auth.org.Organization;
63 import org.onap.aaf.auth.org.Organization.Identity;
64 import org.onap.aaf.auth.org.OrganizationException;
65 import org.onap.aaf.cadi.Access.Level;
66 import org.onap.aaf.cadi.Hash;
67 import org.onap.aaf.cadi.Permission;
68 import org.onap.aaf.cadi.aaf.AAFPermission;
69 import org.onap.aaf.cadi.config.Config;
70 import org.onap.aaf.cadi.configure.Factory;
71 import org.onap.aaf.cadi.util.FQI;
72 import org.onap.aaf.misc.env.APIException;
73 import org.onap.aaf.misc.env.util.Chrono;
74
75 public class CMService {
76     // If we add more CAs, may want to parameterize
77     private static final int STD_RENEWAL = 30;
78     private static final int MAX_RENEWAL = 60;
79     private static final int MIN_RENEWAL = 10;
80     // Limit total requests
81     private static final int MAX_X509s = 200; // Need a "LIMIT Exception" DB.
82     private static final String MAX_X509S_TAG = "cm_max_x509s"; // be able to adjust limit in future
83
84     public static final String REQUEST = "request";
85     public static final String IGNORE_IPS = "ignoreIPs";
86     public static final String RENEW = "renew";
87     public static final String DROP = "drop";
88     public static final String DOMAIN = "domain";
89     public static final String DYNAMIC_SANS="dynamic_sans";
90
91     private static final String CERTMAN = "certman";
92     private static final String ACCESS = "access";
93
94     private static final String[] NO_NOTES = new String[0];
95     private final Permission root_read_permission;
96     private final CertDAO certDAO;
97     private final CredDAO credDAO;
98     private final ArtiDAO artiDAO;
99     private AAF_CM certManager;
100     private Boolean allowIgnoreIPs;
101     private AAFPermission limitOverridePerm;
102     private int max_509s;
103
104     // @SuppressWarnings("unchecked")
105     public CMService(final AuthzTrans trans, AAF_CM certman) throws APIException, IOException {
106         // Jonathan 4/2015 SessionFilter unneeded... DataStax already deals with
107         // Multithreading well
108
109         HistoryDAO hd = new HistoryDAO(trans, certman.cluster, CassAccess.KEYSPACE);
110         CacheInfoDAO cid = new CacheInfoDAO(trans, hd);
111         certDAO = new CertDAO(trans, hd, cid);
112         credDAO = new CredDAO(trans, hd, cid);
113         artiDAO = new ArtiDAO(trans, hd, cid);
114
115         this.certManager = certman;
116
117         root_read_permission=new AAFPermission(
118                 trans.getProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF),
119                 ACCESS,
120                 "*",
121                 "read"
122         );
123         try {
124             max_509s = Integer.parseInt(trans.env().getProperty(MAX_X509S_TAG,Integer.toString(MAX_X509s)));
125         } catch (Exception e) {
126             trans.env().log(e, "");
127             max_509s = MAX_X509s;
128         }
129         limitOverridePerm = new AAFPermission(Define.ROOT_NS(),"certman","quantity","override");
130         allowIgnoreIPs = Boolean.valueOf(certman.access.getProperty(Config.CM_ALLOW_IGNORE_IPS, "false"));
131         if(allowIgnoreIPs) {
132             trans.env().access().log(Level.INIT, "Allowing DNS Evaluation to be turned off with <ns>.certman|<ca name>|"+IGNORE_IPS);
133         }
134     }
135
136     public Result<CertResp> requestCert(final AuthzTrans trans, final Result<CertReq> req, final CA ca) {
137         if (req.isOK()) {
138             if (req.value.fqdns.isEmpty()) {
139                 return Result.err(Result.ERR_BadData, "No Machines passed in Request");
140             }
141
142             String key = req.value.fqdns.get(0);
143
144             // Policy 6: Requester must be granted Change permission in Namespace requested
145             String mechNS = FQI.reverseDomain(req.value.mechid);
146             if (mechNS == null) {
147                 return Result.err(Status.ERR_Denied, "%s does not reflect a valid AAF Namespace", req.value.mechid);
148             }
149
150             List<String> notes = null;
151             List<String> fqdns;
152             boolean domain_based = false;
153             boolean dynamic_sans = false;
154
155             if(req.value.fqdns.isEmpty()) {
156                 fqdns = new ArrayList<>();
157             } else {
158                 // Only Template or Dynamic permitted to pass in FQDNs
159                 if (req.value.fqdns.get(0).startsWith("*")) { // Domain set
160                     if (trans.fish(new AAFPermission(null,ca.getPermType(), ca.getName(), DOMAIN))) {
161                         domain_based = true;
162                     } else {
163                         return Result.err(Result.ERR_Denied,
164                               "Domain based Authorizations (" + req.value.fqdns.get(0) + ") requires Exception");
165                     }
166                 } else {
167                     if(trans.fish(new AAFPermission(null, ca.getPermType(), ca.getName(),DYNAMIC_SANS))) {
168                         dynamic_sans = true;
169                     } else {
170                         return Result.err(Result.ERR_Denied,
171                             "Dynamic SANs for (" + req.value.mechid + ") requires Permission");
172                     }
173                 }
174                 fqdns = new ArrayList<>(req.value.fqdns);
175             }
176
177             String email = null;
178
179             try {
180                 Organization org = trans.org();
181
182                 boolean ignoreIPs;
183                 if(allowIgnoreIPs) {
184                     ignoreIPs = trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), IGNORE_IPS));
185                 } else {
186                     ignoreIPs = false;
187                 }
188
189
190                 InetAddress primary = null;
191                 // Organize incoming information to get to appropriate Artifact
192                 if (!fqdns.isEmpty()) { // Passed in FQDNS, validated above
193                     // Accept domain wild cards, but turn into real machines
194                     // Need *domain.com:real.machine.domain.com:san.machine.domain.com:...
195                     if (domain_based) { // Domain set
196                         // check for Permission in Add Artifact?
197                         String domain = fqdns.get(0).substring(1); // starts with *, see above
198                         fqdns.remove(0);
199                         if (fqdns.isEmpty()) {
200                             return Result.err(Result.ERR_Denied,
201                                 "Requests using domain require machine declaration");
202                         }
203
204                         if (!ignoreIPs) {
205                             InetAddress ia = InetAddress.getByName(fqdns.get(0));
206                             if (ia == null) {
207                                 return Result.err(Result.ERR_Denied,
208                                      "Request not made from matching IP matching domain");
209                             } else if (ia.getHostName().endsWith(domain)) {
210                                 primary = ia;
211                             }
212                         }
213
214                     } else {
215                         // Passed in FQDNs, but not starting with *
216                         if (!ignoreIPs) {
217                             for (String cn : req.value.fqdns) {
218                                 try {
219                                     InetAddress[] ias = InetAddress.getAllByName(cn);
220                                     Set<String> potentialSanNames = new HashSet<>();
221                                     for (InetAddress ia1 : ias) {
222                                         InetAddress ia2 = InetAddress.getByAddress(ia1.getAddress());
223                                         if (primary == null && ias.length == 1 && trans.ip().equals(ia1.getHostAddress())) {
224                                             primary = ia1;
225                                         } else if (!cn.equals(ia1.getHostName())
226                                                 && !ia2.getHostName().equals(ia2.getHostAddress())) {
227                                             potentialSanNames.add(ia1.getHostName());
228                                         }
229                                     }
230                                 } catch (UnknownHostException e1) {
231                                     trans.debug().log(e1);
232                                     return Result.err(Result.ERR_BadData, "There is no DNS lookup for %s", cn);
233                                 }
234                             }
235                         }
236                     }
237                 }
238
239                 final String host;
240                 if (ignoreIPs) {
241                     host = req.value.fqdns.get(0);
242                 } else if (primary == null) {
243                     return Result.err(Result.ERR_Denied, "Request not made from matching IP (%s)", req.value.fqdns.get(0));
244                 } else {
245                     String thost = primary.getHostName();
246                     host = thost==null?primary.getHostAddress():thost;
247                 }
248
249                 ArtiDAO.Data add = null;
250                 Result<List<ArtiDAO.Data>> ra = artiDAO.read(trans, req.value.mechid, host);
251                 if (ra.isOKhasData()) {
252                     add = ra.value.get(0); // single key
253                     if(dynamic_sans && (add.sans!=null && !add.sans.isEmpty())) { // do not allow both Dynamic and Artifact SANS
254                         return Result.err(Result.ERR_Denied,"Authorization must not include SANS when doing Dynamic SANS (%s, %s)", req.value.mechid, key);
255                     }
256                 } else {
257                     if(domain_based) {
258                         ra = artiDAO.read(trans, req.value.mechid, key);
259                         if (ra.isOKhasData()) { // is the Template available?
260                             add = ra.value.get(0);
261                             add.machine = host;
262                             for (String s : fqdns) {
263                                 if (!s.equals(add.machine)) {
264                                     add.sans(true).add(s);
265                                 }
266                             }
267                             Result<ArtiDAO.Data> rc = artiDAO.create(trans, add); // Create new Artifact from Template
268                             if (rc.notOK()) {
269                                 return Result.err(rc);
270                             }
271                         } else {
272                             return Result.err(Result.ERR_Denied,"No Authorization Template for %s, %s", req.value.mechid, key);
273                         }
274                     } else {
275                         return Result.err(Result.ERR_Denied,"No Authorization found for %s, %s", req.value.mechid, key);
276                     }
277                 }
278
279                 // Add Artifact listed FQDNs
280                 if(!dynamic_sans) {
281                     if (add.sans != null) {
282                         for (String s : add.sans) {
283                             if (!fqdns.contains(s)) {
284                                 fqdns.add(s);
285                             }
286                         }
287                     }
288                 }
289
290                 // Policy 2: If Config marked as Expired, do not create or renew
291                 Date now = new Date();
292                 if (add.expires != null && now.after(add.expires)) {
293                     return Result.err(Result.ERR_Policy, "Configuration for %s %s is expired %s", add.mechid,
294                             add.machine, Chrono.dateFmt.format(add.expires));
295                 }
296
297                 // Policy 3: MechID must be current
298                 Identity muser = org.getIdentity(trans, add.mechid);
299                 if (muser == null) {
300                     return Result.err(Result.ERR_Policy, "MechID must exist in %s", org.getName());
301                 }
302
303                 // Policy 4: Sponsor must be current
304                 Identity ouser = muser.responsibleTo();
305                 if (ouser == null) {
306                     return Result.err(Result.ERR_Policy, "%s does not have a current sponsor at %s", add.mechid,
307                             org.getName());
308                 } else if (!ouser.isFound() || ouser.mayOwn() != null) {
309                     return Result.err(Result.ERR_Policy, "%s reports that %s cannot be responsible for %s",
310                             org.getName(), trans.user());
311                 }
312
313                 // Set Email from most current Sponsor
314                 email = ouser.email();
315
316                 // Policy 5: keep Artifact data current
317                 if (!ouser.fullID().equals(add.sponsor)) {
318                     add.sponsor = ouser.fullID();
319                     artiDAO.update(trans, add);
320                 }
321
322                 // Policy 7: Caller must be the MechID or have specifically delegated
323                 // permissions
324                 if (!(trans.user().equals(req.value.mechid)
325                         || trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), REQUEST)))) {
326                     return Result.err(Status.ERR_Denied, "%s must have access to modify x509 certs in NS %s",
327                             trans.user(), mechNS);
328                 }
329
330                 // Make sure Primary is the first in fqdns
331                 if (fqdns.size() > 1) {
332                     for (int i = 0; i < fqdns.size(); ++i) {
333                         if (primary==null && !ignoreIPs) {
334                             trans.error().log("CMService var primary is null");
335                         } else {
336                             String fg = fqdns.get(i);
337                             if ((fg!=null && primary!=null && fg.equals(primary.getHostName()))&&(i != 0)) {
338                                     String tmp = fqdns.get(0);
339                                     fqdns.set(0, primary.getHostName());
340                                     fqdns.set(i, tmp);
341                             }
342                         }
343                     }
344                 }
345             } catch (Exception e) {
346                 trans.error().log(e);
347                 return Result.err(Status.ERR_Denied,
348                         "AppID Sponsorship cannot be determined at this time.  Try later.");
349             }
350
351             CSRMeta csrMeta;
352             try {
353                 csrMeta = BCFactory.createCSRMeta(ca, req.value.mechid, email, fqdns);
354                 csrMeta.environment(ca.getEnv());
355
356                 // Before creating, make sure they don't have too many
357                 if(!trans.fish(limitOverridePerm)) {
358                     Result<List<CertDAO.Data>> existing = certDAO.readID(trans, req.value.mechid);
359                     if(existing.isOK()) {
360                         String cn = "CN=" + csrMeta.cn();
361                         int count = 0;
362                         Date now = new Date();
363                         for (CertDAO.Data cdd : existing.value) {
364                             Collection<? extends Certificate> certs = Factory.toX509Certificate(cdd.x509);
365                             for(Iterator<? extends Certificate> iter = certs.iterator(); iter.hasNext();) {
366                                 X509Certificate x509 = (X509Certificate)iter.next();
367                                 if((x509.getNotAfter().after(now) && x509.getSubjectDN().getName().contains(cn))&&(++count>max_509s)) {
368                                         break;
369                                      }
370                             }
371                         }
372                         if(count>max_509s) {
373                             return Result.err(Result.ERR_Denied, "There are too many Certificates generated for " + cn + " for " + req.value.mechid);
374                         }
375                     }
376                 }
377                 // Here is where we send off to CA for Signing.
378                 X509andChain x509ac = ca.sign(trans, csrMeta);
379                 if (x509ac == null) {
380                     return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA");
381                 }
382                 trans.info().printf("X509 Subject: %s", x509ac.getX509().getSubjectDN());
383
384                 X509Certificate x509 = x509ac.getX509();
385                 CertDAO.Data cdd = new CertDAO.Data();
386                 cdd.ca = ca.getName();
387                 cdd.serial = x509.getSerialNumber();
388                 cdd.id = req.value.mechid;
389                 cdd.x500 = x509.getSubjectDN().getName();
390                 cdd.x509 = Factory.toString(trans, x509);
391
392                 certDAO.create(trans, cdd);
393
394                 CredDAO.Data crdd = new CredDAO.Data();
395                 crdd.other = Question.random.nextInt();
396                 crdd.cred = getChallenge256SaltedHash(csrMeta.challenge(), crdd.other);
397                 crdd.expires = x509.getNotAfter();
398                 crdd.id = req.value.mechid;
399                 crdd.ns = Question.domain2ns(crdd.id);
400                 crdd.type = CredDAO.CERT_SHA256_RSA;
401                 crdd.tag = cdd.ca + '|' + cdd.serial.toString();
402                 credDAO.create(trans, crdd);
403
404                 CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(notes));
405                 return Result.ok(cr);
406             } catch (Exception e) {
407                 trans.debug().log(e);
408                 return Result.err(Result.ERR_ActionNotCompleted, e.getMessage());
409             }
410         } else {
411             return Result.err(req);
412         }
413     }
414
415     public Result<CertResp> renewCert(AuthzTrans trans, Result<CertRenew> renew) {
416         if (renew.isOK()) {
417             return Result.err(Result.ERR_NotImplemented, "Not implemented yet");
418         } else {
419             return Result.err(renew);
420         }
421     }
422
423     public Result<Void> dropCert(AuthzTrans trans, Result<CertDrop> drop) {
424         if (drop.isOK()) {
425             return Result.err(Result.ERR_NotImplemented, "Not implemented yet");
426         } else {
427             return Result.err(drop);
428         }
429     }
430
431     public Result<List<Data>> readCertsByMechID(AuthzTrans trans, String mechID) {
432         // Policy 1: To Read, must have NS Read or is Sponsor
433         String ns = Question.domain2ns(mechID);
434         try {
435             if (trans.user().equals(mechID) || trans.fish(new AAFPermission(ns,ACCESS, "*", "read"))
436                     || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechID)) == null) {
437                 return certDAO.readID(trans, mechID);
438             } else {
439                 return Result.err(Result.ERR_Denied, "%s is not the ID, Sponsor or NS Owner/Admin for %s at %s",
440                         trans.user(), mechID, trans.org().getName());
441             }
442         } catch (OrganizationException e) {
443             return Result.err(e);
444         }
445     }
446
447     public Result<CertResp> requestPersonalCert(AuthzTrans trans, CA ca) {
448         if (ca.inPersonalDomains(trans.getUserPrincipal())) {
449             Organization org = trans.org();
450
451             // Policy 1: MechID must be current
452             Identity ouser;
453             try {
454                 ouser = org.getIdentity(trans, trans.user());
455             } catch (OrganizationException e1) {
456                 trans.debug().log(e1);
457                 ouser = null;
458             }
459             if (ouser == null) {
460                 return Result.err(Result.ERR_Policy, "Requesting User must exist in %s", org.getName());
461             }
462
463             // Set Email from most current Sponsor
464
465             CSRMeta csrMeta;
466             try {
467                 csrMeta = BCFactory.createPersonalCSRMeta(ca, trans.user(), ouser.email());
468                 X509andChain x509ac = ca.sign(trans, csrMeta);
469                 if (x509ac == null) {
470                     return Result.err(Result.ERR_ActionNotCompleted, "x509 Certificate not signed by CA");
471                 }
472                 X509Certificate x509 = x509ac.getX509();
473                 CertDAO.Data cdd = new CertDAO.Data();
474                 cdd.ca = ca.getName();
475                 cdd.serial = x509.getSerialNumber();
476                 cdd.id = trans.user();
477                 cdd.x500 = x509.getSubjectDN().getName();
478                 cdd.x509 = Factory.toString(trans, x509);
479                 certDAO.create(trans, cdd);
480
481                 CertResp cr = new CertResp(trans, ca, x509, csrMeta, x509ac.getTrustChain(), compileNotes(null));
482                 return Result.ok(cr);
483             } catch (Exception e) {
484                 trans.debug().log(e);
485                 return Result.err(Result.ERR_ActionNotCompleted, e.getMessage());
486             }
487         } else {
488             return Result.err(Result.ERR_Denied, trans.user(), " not supported for CA", ca.getName());
489         }
490     }
491
492     ///////////////
493     // Artifact
494     //////////////
495     public Result<Void> createArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) {
496         CertmanValidator v = new CertmanValidator().artisRequired(list, 1);
497         if (v.err()) {
498             return Result.err(Result.ERR_BadData, v.errs());
499         }
500         for (ArtiDAO.Data add : list) {
501             try {
502                 // Policy 1: MechID must exist in Org
503                 Identity muser = trans.org().getIdentity(trans, add.mechid);
504                 if (muser == null) {
505                     return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName());
506                 }
507
508                 // Policy 2: MechID must have valid Organization Owner
509                 Identity emailUser;
510                 if (muser.isPerson()) {
511                     emailUser = muser;
512                 } else {
513                     Identity ouser = muser.responsibleTo();
514                     if (ouser == null) {
515                         return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(),
516                                 add.mechid, trans.org().getName());
517                     }
518
519                     // Policy 3: Calling ID must be MechID Owner
520                     if (!trans.user().startsWith(ouser.id())) {
521                         return Result.err(Result.ERR_Denied, "%s is not the Sponsor for %s at %s", trans.user(),
522                                 add.mechid, trans.org().getName());
523                     }
524                     emailUser = ouser;
525                 }
526
527                 // Policy 4: Renewal Days are between 10 and 60 (constants, may be
528                 // parameterized)
529                 if (add.renewDays < MIN_RENEWAL) {
530                     add.renewDays = STD_RENEWAL;
531                 } else if (add.renewDays > MAX_RENEWAL) {
532                     add.renewDays = MAX_RENEWAL;
533                 }
534
535                 // Policy 5: If Notify is blank, set to Owner's Email
536                 if (add.notify == null || add.notify.length() == 0) {
537                     add.notify = "mailto:" + emailUser.email();
538                 }
539
540                 // Policy 6: Only do Domain by Exception
541                 if (add.machine.startsWith("*")) { // Domain set
542                     CA ca = certManager.getCA(add.ca);
543                     if (!trans.fish(new AAFPermission(ca.getPermNS(),ca.getPermType(), add.ca, DOMAIN))) {
544                         return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission",
545                                 add.machine);
546                     }
547                 }
548
549                 // Set Sponsor from Golden Source
550                 add.sponsor = emailUser.fullID();
551
552             } catch (OrganizationException e) {
553                 return Result.err(e);
554             }
555             // Add to DB
556             Result<ArtiDAO.Data> rv = artiDAO.create(trans, add);
557             //  come up with Partial Reporting Scheme, or allow only one at a time.
558             if (rv.notOK()) {
559                 return Result.err(rv);
560             }
561         }
562         return Result.ok();
563     }
564
565     public Result<List<ArtiDAO.Data>> readArtifacts(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException {
566         CertmanValidator v = new CertmanValidator().keys(add);
567         if (v.err()) {
568             return Result.err(Result.ERR_BadData, v.errs());
569         }
570         Result<List<ArtiDAO.Data>> data = artiDAO.read(trans, add);
571         if (data.notOKorIsEmpty()) {
572             return data;
573         }
574         add = data.value.get(0);
575         if (trans.user().equals(add.mechid)
576                 || trans.fish(root_read_permission,
577                 new AAFPermission(add.ns,ACCESS, "*", "read"),
578                 new AAFPermission(add.ns,CERTMAN, add.ca, "read"),
579                 new AAFPermission(add.ns,CERTMAN, add.ca, REQUEST))
580                 || (trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, add.mechid)) == null) {
581             return data;
582         } else {
583             return Result.err(Result.ERR_Denied,
584                     "%s is not %s, is not the sponsor, and doesn't have delegated permission.", trans.user(),
585                     add.mechid, add.ns + ".certman|" + add.ca + "|read or ...|request"); // note: reason is set by 2nd
586             // case, if 1st case misses
587         }
588
589     }
590
591     public Result<List<ArtiDAO.Data>> readArtifactsByMechID(AuthzTrans trans, String mechid)
592             throws OrganizationException {
593         CertmanValidator v = new CertmanValidator();
594         v.nullOrBlank("mechid", mechid);
595         if (v.err()) {
596             return Result.err(Result.ERR_BadData, v.errs());
597         }
598         String ns = FQI.reverseDomain(mechid);
599
600         String reason;
601         if (trans.fish(new AAFPermission(ns, ACCESS, "*", "read"))
602                 || (reason = trans.org().validate(trans, Organization.Policy.OWNS_MECHID, null, mechid)) == null) {
603             return artiDAO.readByMechID(trans, mechid);
604         } else {
605             return Result.err(Result.ERR_Denied, reason); // note: reason is set by 2nd case, if 1st case misses
606         }
607
608     }
609
610     public Result<List<ArtiDAO.Data>> readArtifactsByMachine(AuthzTrans trans, String machine) {
611         CertmanValidator v = new CertmanValidator();
612         v.nullOrBlank("machine", machine);
613         if (v.err()) {
614             return Result.err(Result.ERR_BadData, v.errs());
615         }
616
617         //  do some checks?
618
619         return artiDAO.readByMachine(trans, machine);
620     }
621
622     public Result<List<ArtiDAO.Data>> readArtifactsByNs(AuthzTrans trans, String ns) {
623         CertmanValidator v = new CertmanValidator();
624         v.nullOrBlank("ns", ns);
625         if (v.err()) {
626             return Result.err(Result.ERR_BadData, v.errs());
627         }
628
629         //  do some checks?
630         return artiDAO.readByNs(trans, ns);
631     }
632
633     public Result<Void> updateArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) throws OrganizationException {
634         CertmanValidator v = new CertmanValidator();
635         v.artisRequired(list, 1);
636         if (v.err()) {
637             return Result.err(Result.ERR_BadData, v.errs());
638         }
639
640         // Check if requesting User is Sponsor
641         //  Shall we do one, or multiples?
642         for (ArtiDAO.Data add : list) {
643             // Policy 1: MechID must exist in Org
644             Identity muser = trans.org().getIdentity(trans, add.mechid);
645             if (muser == null) {
646                 return Result.err(Result.ERR_Denied, "%s is not valid for %s", add.mechid, trans.org().getName());
647             }
648
649             // Policy 2: MechID must have valid Organization Owner
650             Identity ouser = muser.responsibleTo();
651             if (ouser == null) {
652                 return Result.err(Result.ERR_Denied, "%s is not a valid Sponsor for %s at %s", trans.user(), add.mechid,
653                         trans.org().getName());
654             }
655
656             // Policy 3: Renewal Days are between 10 and 60 (constants, may be
657             // parameterized)
658             if (add.renewDays < MIN_RENEWAL) {
659                 add.renewDays = STD_RENEWAL;
660             } else if (add.renewDays > MAX_RENEWAL) {
661                 add.renewDays = MAX_RENEWAL;
662             }
663
664             // Policy 4: Data is always updated with the latest Sponsor
665             // Add to Sponsor, to make sure we are always up to date.
666             add.sponsor = ouser.fullID();
667
668             // Policy 5: If Notify is blank, set to Owner's Email
669             if (add.notify == null || add.notify.length() == 0) {
670                 add.notify = "mailto:" + ouser.email();
671             }
672             // Policy 6: Only do Domain by Exception
673             if (add.machine.startsWith("*")) { // Domain set
674                 CA ca = certManager.getCA(add.ca);
675                 if (ca == null) {
676                     return Result.err(Result.ERR_BadData, "CA is required in Artifact");
677                 }
678                 if (!trans.fish(new AAFPermission(null,ca.getPermType(), add.ca, DOMAIN))) {
679                     return Result.err(Result.ERR_Denied, "Domain Artifacts (%s) requires specific Permission",
680                             add.machine);
681                 }
682             }
683
684             // Policy 7: only Owner may update info
685             if (trans.user().startsWith(ouser.id())) {
686                 return artiDAO.update(trans, add);
687             } else {
688                 return Result.err(Result.ERR_Denied, "%s may not update info for %s", trans.user(), muser.fullID());
689             }
690         }
691         return Result.err(Result.ERR_BadData, "No Artifacts to update");
692     }
693
694     public Result<Void> deleteArtifact(AuthzTrans trans, String mechid, String machine) throws OrganizationException {
695         CertmanValidator v = new CertmanValidator();
696         v.nullOrBlank("mechid", mechid).nullOrBlank("machine", machine);
697         if (v.err()) {
698             return Result.err(Result.ERR_BadData, v.errs());
699         }
700
701         Result<List<ArtiDAO.Data>> rlad = artiDAO.read(trans, mechid, machine);
702         if (rlad.notOKorIsEmpty()) {
703             return Result.err(Result.ERR_NotFound, "Artifact for %s %s does not exist.", mechid, machine);
704         }
705
706         return deleteArtifact(trans, rlad.value.get(0));
707     }
708
709     private Result<Void> deleteArtifact(AuthzTrans trans, ArtiDAO.Data add) throws OrganizationException {
710         // Policy 1: Record should be delete able only by Existing Sponsor.
711         String sponsor = null;
712         Identity muser = trans.org().getIdentity(trans, add.mechid);
713         if (muser != null) {
714             Identity ouser = muser.responsibleTo();
715             if (ouser != null) {
716                 sponsor = ouser.fullID();
717             }
718         }
719         // Policy 1.a: If Sponsorship is deleted in system of Record, then
720         // accept deletion by sponsor in Artifact Table
721         if (sponsor == null) {
722             sponsor = add.sponsor;
723         }
724
725         String ns = FQI.reverseDomain(add.mechid);
726
727         if (trans.fish(new AAFPermission(ns,ACCESS, "*", "write")) || trans.user().equals(sponsor)) {
728             return artiDAO.delete(trans, add, false);
729         }
730         return Result.err(Result.ERR_Denied, "%1 is not allowed to delete this item", trans.user());
731     }
732
733     public Result<Void> deleteArtifact(AuthzTrans trans, List<ArtiDAO.Data> list) {
734         CertmanValidator v = new CertmanValidator().artisRequired(list, 1);
735         if (v.err()) {
736             return Result.err(Result.ERR_BadData, v.errs());
737         }
738
739         try {
740             boolean partial = false;
741             Result<Void> result = null;
742             for (ArtiDAO.Data add : list) {
743                 result = deleteArtifact(trans, add);
744                 if (result.notOK()) {
745                     partial = true;
746                 }
747             }
748             if (result == null) {
749                 result = Result.err(Result.ERR_BadData, "No Artifacts to delete");
750             } else if (partial) {
751                 result.partialContent(true);
752             }
753             return result;
754         } catch (Exception e) {
755             return Result.err(e);
756         }
757     }
758
759     private String[] compileNotes(List<String> notes) {
760         String[] rv;
761         if (notes == null) {
762             rv = NO_NOTES;
763         } else {
764             rv = new String[notes.size()];
765             notes.toArray(rv);
766         }
767         return rv;
768     }
769
770     private ByteBuffer getChallenge256SaltedHash(String challenge, int salt) throws NoSuchAlgorithmException {
771         ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE + challenge.length());
772         bb.putInt(salt);
773         bb.put(challenge.getBytes());
774         byte[] hash = Hash.hashSHA256(bb.array());
775         return ByteBuffer.wrap(hash);
776     }
777 }