/**
  * Seeds the bound instance's local ads-truststore with a set of instance key-pair public key
  * certificates. The result is the instance will trust any instance posessing the private key
  * corresponding to one of the public-key certificates. This trust is necessary at least to
  * initialize replication, which uses the trusted certificate entries in the ads-truststore for
  * server authentication.
  *
  * @param ctx The bound instance.
  * @param keyEntryMap The set of valid (i.e., not tagged as compromised) instance key-pair
  *     public-key certificate entries in ADS represented as a map from keyID to public-key
  *     certificate (binary).
  * @throws NamingException in case an error occurs while updating the instance's ads-truststore
  *     via LDAP.
  */
 public static void seedAdsTrustStore(InitialLdapContext ctx, Map<String, byte[]> keyEntryMap)
     throws NamingException {
   /* TODO: this DN is declared in some core constants file. Create a
   constants file for the installer and import it into the core. */
   final Attribute oc = new BasicAttribute("objectclass");
   oc.add("top");
   oc.add("ds-cfg-instance-key");
   for (Map.Entry<String, byte[]> keyEntry : keyEntryMap.entrySet()) {
     final BasicAttributes keyAttrs = new BasicAttributes();
     keyAttrs.put(oc);
     final Attribute rdnAttr =
         new BasicAttribute(
             ADSContext.ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyEntry.getKey());
     keyAttrs.put(rdnAttr);
     keyAttrs.put(
         new BasicAttribute(
             ADSContext.ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName()
                 + ";binary",
             keyEntry.getValue()));
     final LdapName keyDn =
         new LdapName(
             (new StringBuilder(rdnAttr.getID()))
                 .append("=")
                 .append(Rdn.escapeValue(rdnAttr.get()))
                 .append(",")
                 .append(TRUSTSTORE_DN)
                 .toString());
     try {
       ctx.createSubcontext(keyDn, keyAttrs).close();
     } catch (NameAlreadyBoundException x) {
       ctx.destroySubcontext(keyDn);
       ctx.createSubcontext(keyDn, keyAttrs).close();
     }
   }
 }
Esempio n. 2
0
  @SuppressWarnings("unchecked")
  void jndiInJEE() throws NamingException {
    @SuppressWarnings("rawtypes")
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");

    InitialContext context = new InitialContext(env);

    DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/AccountDS");

    NamingEnumeration<Binding> bindings = context.listBindings("java:comp/env/jdbc");

    while (bindings.hasMore()) {
      Binding bd = (Binding) bindings.next();
      System.out.println("Name = " + bd.getName() + ", Object = " + bd.getObject());
    }

    context.bind("java:comp/env/jdbc/AccountDS", ds);

    // Directory search

    InitialDirContext dirContext = new InitialDirContext();

    SearchControls control = new SearchControls();

    ds = (DataSource) dirContext.search("java:comp/env/jdbc/AccountDS", "(ver=1.1)", control);

    // Or...

    BasicAttributes attrs = new BasicAttributes();
    attrs.put(new BasicAttribute("ver", "1.1"));

    ds = (DataSource) dirContext.search("java:comp/env/jdbc/AccountDS", attrs);
  }
 private static Attributes storeTo(AttributeFilter filter, Entity entity, BasicAttributes attrs) {
   attrs.put("objectclass", "dcmAttributeFilter");
   attrs.put("dcmEntity", entity.name());
   attrs.put(tagsAttr("dcmTag", filter.getSelection()));
   storeNotNull(attrs, "dcmCustomAttribute1", filter.getCustomAttribute1());
   storeNotNull(attrs, "dcmCustomAttribute2", filter.getCustomAttribute2());
   storeNotNull(attrs, "dcmCustomAttribute3", filter.getCustomAttribute3());
   return attrs;
 }
  /* Return all groups for principal == null or all groups for which principal
   * is a member
   *
   */
  private Collection<BwGroup> getGroups(
      final DirConfigProperties dirProps, final BwPrincipal principal) throws CalFacadeException {
    LdapConfigProperties props = (LdapConfigProperties) dirProps;
    InitialLdapContext ctx = null;
    String member = null;

    if (principal != null) {
      if (principal.getKind() == WhoDefs.whoTypeUser) {
        member = getUserEntryValue(props, principal);
      } else if (principal.getKind() == WhoDefs.whoTypeGroup) {
        member = getGroupEntryValue(props, principal);
      }
    }

    try {
      ctx = createLdapInitContext(props);

      BasicAttributes matchAttrs = new BasicAttributes(true);

      if (member != null) {
        matchAttrs.put(props.getGroupMemberAttr(), member);
      }

      String[] idAttr = {props.getGroupIdAttr()};

      ArrayList<BwGroup> groups = new ArrayList<BwGroup>();
      NamingEnumeration response = ctx.search(props.getGroupContextDn(), matchAttrs, idAttr);
      while (response.hasMore()) {
        SearchResult sr = (SearchResult) response.next();
        Attributes attrs = sr.getAttributes();

        Attribute nmAttr = attrs.get(props.getGroupIdAttr());
        if (nmAttr.size() != 1) {
          throw new CalFacadeException("org.bedework.ldap.groups.multiple.result");
        }

        BwGroup group = new BwGroup();
        group.setAccount(nmAttr.get(0).toString());
        group.setPrincipalRef(makePrincipalUri(group.getAccount(), WhoDefs.whoTypeGroup));

        groups.add(group);
      }

      return groups;
    } catch (Throwable t) {
      if (debug) {
        error(t);
      }
      throw new CalFacadeException(t);
    } finally {
      // Close the context to release the connection
      if (ctx != null) {
        closeContext(ctx);
      }
    }
  }
Esempio n. 5
0
  private static Attributes getRootPartitionAttributes(String defaultPartitionName) {
    BasicAttributes attributes = new BasicAttributes();
    BasicAttribute objectClassAttribute = new BasicAttribute("objectClass");
    objectClassAttribute.add("top");
    objectClassAttribute.add("domain");
    objectClassAttribute.add("extensibleObject");
    attributes.put(objectClassAttribute);
    attributes.put("dc", defaultPartitionName);

    return attributes;
  }
Esempio n. 6
0
 @Override
 public void createUser(LdapUser user, String parentDn) {
   try {
     String cn = buildCn(user.getFirstName(), user.getLastName());
     BasicAttributes attrs = getBasicAttributesForUser(user, cn);
     attrs.put("forward", user.getForwardAddress());
     DirContext ctxt = connect();
     System.err.println(attrs);
     ctxt.bind("cn=" + cn + "," + parentDn, null, attrs);
   } catch (NamingException e) {
     log.error("Error createing User", e);
     throw new RuntimeException(e);
   }
 }
  public void testGetObjectInstance_ObjectNotContext() throws Exception {
    BasicAttributes expectedAttributes = new BasicAttributes();
    expectedAttributes.put("someAttribute", "someValue");

    replay();

    DirContextAdapter adapter =
        (DirContextAdapter)
            tested.getObjectInstance(new Object(), DN, null, new Hashtable(), expectedAttributes);

    verify();

    assertEquals(DN, adapter.getDn());
    assertEquals(expectedAttributes, adapter.getAttributes());
  }
Esempio n. 8
0
  public void testCollectAttributeValues() {
    String expectedAttributeName = "someAttribute";
    BasicAttribute expectedAttribute = new BasicAttribute(expectedAttributeName);
    expectedAttribute.add("value1");
    expectedAttribute.add("value2");

    BasicAttributes attributes = new BasicAttributes();
    attributes.put(expectedAttribute);

    LinkedList list = new LinkedList();
    LdapUtils.collectAttributeValues(attributes, expectedAttributeName, list);

    assertEquals(2, list.size());
    assertEquals("value1", list.get(0));
    assertEquals("value2", list.get(1));
  }
 private static Attributes storeTo(RejectionNote ac, BasicAttributes attrs) {
   attrs.put("objectclass", "dcmRejectionNote");
   storeNotNull(attrs, "dcmCodeValue", ac.getCodeValue());
   storeNotNull(attrs, "dcmCodingSchemeDesignator", ac.getCodingSchemeDesignator());
   storeNotNull(attrs, "dcmCodingSchemeVersion", ac.getCodingSchemeVersion());
   storeNotNull(attrs, "dcmCodeMeaning", ac.getCodeMeaning());
   storeNotEmpty(attrs, "dcmRejectionAction", ac.getActions().toArray());
   return attrs;
 }
 private static Attributes storeTo(AttributeCoercion ac, BasicAttributes attrs) {
   attrs.put("objectclass", "dcmAttributeCoercion");
   storeNotNull(attrs, "dcmDIMSE", ac.getDimse());
   storeNotNull(attrs, "dicomTransferRole", ac.getRole());
   storeNotNull(attrs, "dicomAETitle", ac.getAETitle());
   storeNotNull(attrs, "dicomSOPClass", ac.getSopClass());
   storeNotNull(attrs, "labeledURI", ac.getURI());
   return attrs;
 }
  @Override
  public final Attributes getCollectedAttributes() {
    BasicAttributes attributes = new BasicAttributes();

    Set<String> attributeNames = stateMap.keySet();
    for (String attributeName : attributeNames) {
      BasicAttribute oneAttribute = new BasicAttribute(attributeName);
      List<Object> values = getValues(attributeName);
      if (values != null) {
        for (Object oneValue : values) {
          oneAttribute.add(oneValue);
        }
      }

      attributes.put(oneAttribute);
    }

    return attributes;
  }
  /* Search for a group to ensure it exists
   *
   */
  private BwGroup findGroup(final DirConfigProperties dirProps, final String groupName)
      throws CalFacadeException {
    LdapConfigProperties props = (LdapConfigProperties) dirProps;
    InitialLdapContext ctx = null;

    try {
      ctx = createLdapInitContext(props);

      BasicAttributes matchAttrs = new BasicAttributes(true);

      matchAttrs.put(props.getGroupIdAttr(), groupName);

      String[] idAttr = {props.getGroupIdAttr()};

      BwGroup group = null;
      NamingEnumeration response = ctx.search(props.getGroupContextDn(), matchAttrs, idAttr);
      while (response.hasMore()) {
        //        SearchResult sr = (SearchResult)response.next();
        //        Attributes attrs = sr.getAttributes();

        if (group != null) {
          throw new CalFacadeException("org.bedework.ldap.groups.multiple.result");
        }

        group = new BwGroup();
        group.setAccount(groupName);
        group.setPrincipalRef(makePrincipalUri(groupName, WhoDefs.whoTypeGroup));
      }

      return group;
    } catch (Throwable t) {
      if (debug) {
        error(t);
      }
      throw new CalFacadeException(t);
    } finally {
      // Close the context to release the connection
      if (ctx != null) {
        closeContext(ctx);
      }
    }
  }
  public void testGetObjectInstance_CompositeName() throws Exception {
    BasicAttributes expectedAttributes = new BasicAttributes();
    expectedAttributes.put("someAttribute", "someValue");

    contextMock.close();

    replay();

    CompositeName name = new CompositeName();
    name.add(DN_STRING);

    DirContextAdapter adapter =
        (DirContextAdapter)
            tested.getObjectInstance(contextMock, name, null, new Hashtable(), expectedAttributes);

    verify();

    assertEquals(DN, adapter.getDn());
    assertEquals(expectedAttributes, adapter.getAttributes());
  }
Esempio n. 14
0
 private BasicAttributes getBasicAttributesForUser(LdapUser user, String cn) {
   BasicAttributes attrs = new BasicAttributes();
   BasicAttribute oclass = new BasicAttribute("objectclass");
   oclass.add("mailAccount");
   oclass.add("inetOrgPerson");
   oclass.add("person");
   oclass.add("top");
   user.setCn(cn);
   attrs.put(oclass);
   attrs.put("cn", cn);
   attrs.put("givenname", user.getFirstName());
   attrs.put("privateMail", user.getPrivateMailAdress());
   attrs.put("mail", user.getMailAdress());
   attrs.put("sn", user.getLastName());
   attrs.put("userpassword", digestSha1(user.getPassword()));
   return attrs;
 }
  /**
   * Make sure that the base suffix is stripped off from the DN.
   *
   * @throws Exception
   */
  public void testGetObjectInstance_BaseSet() throws Exception {
    BasicAttributes expectedAttributes = new BasicAttributes();
    expectedAttributes.put("someAttribute", "someValue");

    contextControl2.expectAndReturn(contextMock2.getNameInNamespace(), "dc=jayway, dc=se");
    contextMock.close();

    replay();

    DirContextAdapter adapter =
        (DirContextAdapter)
            tested.getObjectInstance(
                contextMock,
                new DistinguishedName("ou=some unit"),
                contextMock2,
                new Hashtable(),
                expectedAttributes);

    verify();

    assertEquals("ou=some unit", adapter.getDn().toString());
    assertEquals("ou=some unit,dc=jayway,dc=se", adapter.getNameInNamespace());
    assertEquals(expectedAttributes, adapter.getAttributes());
  }
Esempio n. 16
0
 @Override
 public void createImapUser(LdapUser user, String parentDn) {
   String cn = buildCn(user.getFirstName(), user.getLastName());
   int uid = getMaxUid() + 1;
   BasicAttributes attrs = getBasicAttributesForUser(user, cn);
   attrs.get("objectclass").add("posixAccount");
   attrs.put("gidnumber", props.getLdapGidNumber());
   attrs.put(props.getLdapUidAttribute(), uid + "");
   attrs.put("homedirectory", props.getHomeDirBase() + "/" + cn);
   attrs.put("uid", cn);
   attrs.put("forward", cn + "@localhost");
   try {
     DirContext ctxt = connect();
     ctxt.bind("cn=" + cn + "," + parentDn, null, attrs);
   } catch (NamingException e) {
     log.error("Error creating user", e);
     throw new RuntimeException(e);
   }
 }
  /* Find members for given group
   *
   */
  private void getGroupMembers(final DirConfigProperties dirProps, final BwGroup group)
      throws CalFacadeException {
    LdapConfigProperties props = (LdapConfigProperties) dirProps;
    InitialLdapContext ctx = null;

    try {
      ctx = createLdapInitContext(props);

      BasicAttributes matchAttrs = new BasicAttributes(true);

      matchAttrs.put(props.getGroupIdAttr(), group.getAccount());

      String[] memberAttr = {props.getGroupMemberAttr()};

      ArrayList<String> mbrs = null;

      boolean beenHere = false;

      NamingEnumeration response = ctx.search(props.getGroupContextDn(), matchAttrs, memberAttr);
      while (response.hasMore()) {
        SearchResult sr = (SearchResult) response.next();
        Attributes attrs = sr.getAttributes();

        if (beenHere) {
          throw new CalFacadeException("org.bedework.ldap.groups.multiple.result");
        }

        beenHere = true;

        Attribute membersAttr = attrs.get(props.getGroupMemberAttr());
        mbrs = new ArrayList<String>();

        for (int m = 0; m < membersAttr.size(); m++) {
          mbrs.add(membersAttr.get(m).toString());
        }
      }
      // LDAP We need a way to search recursively for groups.

      /* Search for each user in the group */
      String memberContext = props.getGroupMemberContextDn();
      String memberSearchAttr = props.getGroupMemberSearchAttr();
      String[] idAttr = {
        props.getGroupMemberUserIdAttr(), props.getGroupMemberGroupIdAttr(), "objectclass"
      };

      for (String mbr : mbrs) {
        if (memberContext != null) {
          matchAttrs = new BasicAttributes(true);

          matchAttrs.put(memberSearchAttr, mbr);

          response = ctx.search(memberContext, matchAttrs, idAttr);
        } else {
          response = ctx.search(memberContext, null, idAttr);
        }

        if (response.hasMore()) {
          SearchResult sr = (SearchResult) response.next();
          Attributes attrs = sr.getAttributes();

          Attribute ocsAttr = attrs.get("objectclass");
          String userOc = props.getUserObjectClass();
          String groupOc = props.getGroupObjectClass();
          boolean isGroup = false;

          for (int oci = 0; oci < ocsAttr.size(); oci++) {
            String oc = ocsAttr.get(oci).toString();
            if (userOc.equals(oc)) {
              break;
            }

            if (groupOc.equals(oc)) {
              isGroup = true;
              break;
            }
          }

          BwPrincipal p = null;
          Attribute attr;

          if (isGroup) {
            p = BwPrincipal.makeGroupPrincipal();

            attr = attrs.get(props.getGroupMemberGroupIdAttr());
          } else {
            p = BwPrincipal.makeUserPrincipal();

            attr = attrs.get(props.getGroupMemberUserIdAttr());
          }

          if (attr.size() != 1) {
            throw new CalFacadeException("org.bedework.ldap.groups.multiple.result");
          }

          p.setAccount(attr.get(0).toString());
          p.setPrincipalRef(makePrincipalUri(p.getAccount(), p.getKind()));
          group.addGroupMember(p);
        }
      }
    } catch (Throwable t) {
      if (debug) {
        error(t);
      }
      throw new CalFacadeException(t);
    } finally {
      // Close the context to release the connection
      if (ctx != null) {
        closeContext(ctx);
      }
    }

    /* Recursively fetch members of groups that are members. */

    for (BwGroup g : group.getGroups()) {
      getGroupMembers(props, g);
    }
  }
Esempio n. 18
0
  /**
   * Register instance key-pair public-key certificate provided in serverProperties: generate a
   * key-id attribute if one is not provided (as expected); add an instance key public-key
   * certificate entry for the key certificate; and associate the certificate entry with the server
   * entry via the key ID attribute.
   *
   * @param ctx the InitialLdapContext on the server we want to update.
   * @param serverProperties Properties of the server being registered to which the instance key
   *     entry belongs.
   * @param serverEntryDn The server's ADS entry DN.
   * @throws ADSContextException In case some JNDI operation fails or there is a problem getting the
   *     instance public key certificate ID.
   */
  void registerInstanceKeyCertificate(
      InitialLdapContext ctx, Map<ServerProperty, Object> serverProperties, LdapName serverEntryDn)
      throws ADSContextException {
    assert serverProperties.containsKey(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE);
    if (!serverProperties.containsKey(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE)) {
      return;
    }

    // the key ID might be supplied in serverProperties (although, I am unaware of any such case).
    String keyID = (String) serverProperties.get(ServerProperty.INSTANCE_KEY_ID);

    /* these attributes are used both to search for an existing certificate
    entry and, if one does not exist, add a new certificate entry */
    final BasicAttributes keyAttrs = new BasicAttributes();
    final Attribute oc = new BasicAttribute("objectclass");
    oc.add("top");
    oc.add("ds-cfg-instance-key");
    keyAttrs.put(oc);
    if (null != keyID) {
      keyAttrs.put(new BasicAttribute(ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyID));
    }
    keyAttrs.put(
        new BasicAttribute(
            ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE.getAttributeName() + ";binary",
            serverProperties.get(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE)));

    /* search for public-key certificate entry in ADS DIT */
    final String attrIDs[] = {"ds-cfg-key-id"};
    NamingEnumeration<SearchResult> results = null;
    try {
      results = ctx.search(ADSContext.getInstanceKeysContainerDN(), keyAttrs, attrIDs);
      boolean found = false;
      while (results.hasMore()) {
        final Attribute keyIdAttr = results.next().getAttributes().get(attrIDs[0]);
        if (null != keyIdAttr) {
          /* attribute ds-cfg-key-id is the entry is a MUST in the schema */
          keyID = (String) keyIdAttr.get();
        }
        found = true;
      }
      /* TODO: It is possible (but unexpected) that the caller specifies a
      ds-cfg-key-id value for which there is a certificate entry in ADS, but
      the certificate value does not match that supplied by the caller. The
      above search would not return the entry, but the below attempt to add
      an new entry with the supplied ds-cfg-key-id will fail (throw a
      NameAlreadyBoundException) */
      if (!found) {
        /* create key ID, if it was not supplied in serverProperties */
        if (null == keyID) {
          keyID =
              CryptoManagerImpl.getInstanceKeyID(
                  (byte[]) serverProperties.get(ServerProperty.INSTANCE_PUBLIC_KEY_CERTIFICATE));
          keyAttrs.put(
              new BasicAttribute(ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyID));
        }

        /* add public-key certificate entry */
        final LdapName keyDn =
            new LdapName(
                ServerProperty.INSTANCE_KEY_ID.getAttributeName()
                    + "="
                    + Rdn.escapeValue(keyID)
                    + ","
                    + ADSContext.getInstanceKeysContainerDN());
        ctx.createSubcontext(keyDn, keyAttrs).close();
      }

      if (serverEntryDn != null) {
        /* associate server entry with certificate entry via key ID attribute */
        ctx.modifyAttributes(
            serverEntryDn,
            InitialLdapContext.REPLACE_ATTRIBUTE,
            new BasicAttributes(ServerProperty.INSTANCE_KEY_ID.getAttributeName(), keyID));
      }
    } catch (NamingException | CryptoManagerException ne) {
      throw new ADSContextException(ErrorType.ERROR_UNEXPECTED, ne);
    } finally {
      handleCloseNamingEnumeration(results);
    }
  }
 private Attributes storeTo(StoreDuplicate sd, BasicAttributes attrs) {
   attrs.put("objectclass", "dcmStoreDuplicate");
   storeNotNull(attrs, "dcmStoreDuplicateCondition", sd.getCondition());
   storeNotNull(attrs, "dcmStoreDuplicateAction", sd.getAction());
   return attrs;
 }