public static boolean putProxyCredentialsIntoServerFile(
      @NotNull final File configDir,
      @NotNull final String host,
      @NotNull final PasswordAuthentication authentication) {
    final IdeaSVNConfigFile configFile =
        new IdeaSVNConfigFile(new File(configDir, SERVERS_FILE_NAME));
    configFile.updateGroups();

    String groupName = SvnAuthenticationManager.getGroupForHost(host, configFile);
    // no proxy defined in group -> no sense in password
    if (StringUtil.isEmptyOrSpaces(groupName)) return false;
    final Map<String, String> properties = configFile.getAllGroups().get(groupName).getProperties();
    if (StringUtil.isEmptyOrSpaces(properties.get(SvnAuthenticationManager.HTTP_PROXY_HOST)))
      return false;
    if (StringUtil.isEmptyOrSpaces(properties.get(SvnAuthenticationManager.HTTP_PROXY_PORT)))
      return false;

    configFile.setValue(
        groupName, SvnAuthenticationManager.HTTP_PROXY_USERNAME, authentication.getUserName());
    configFile.setValue(
        groupName,
        SvnAuthenticationManager.HTTP_PROXY_PASSWORD,
        String.valueOf(authentication.getPassword()));
    configFile.save();
    return true;
  }
示例#2
0
  /**
   * Create the ftpClient and authenticate with the resource.
   *
   * @throws FileResourceException if an exception occurs during the resource start-up
   */
  public void start()
      throws InvalidSecurityContextException, IllegalHostException, FileResourceException {

    ServiceContact serviceContact = getAndCheckServiceContact();

    String host = getServiceContact().getHost();
    int port = getServiceContact().getPort();
    if (port == -1) {
      port = 21;
    }

    if (getName() == null) {
      setName(host + ":" + port);
    }

    try {
      SecurityContext securityContext = getOrCreateSecurityContext("ftp", serviceContact);

      PasswordAuthentication credentials = getCredentialsAsPasswordAuthentication(securityContext);

      ftpClient = new FTPClient(host, port);

      String username = credentials.getUserName();
      String password = String.valueOf(credentials.getPassword());

      ftpClient.authorize(username, password);
      ftpClient.setType(Session.TYPE_IMAGE);
      setStarted(true);
    } catch (Exception e) {
      throw translateException("Error connecting to the FTP server at " + host + ":" + port, e);
    }
  }
 private void init(PasswordAuthentication pw) {
   String username;
   String ntdomain;
   char[] password;
   this.pw = pw;
   String s = pw.getUserName();
   int i = s.indexOf('\\');
   if (i == -1) {
     username = s;
     ntdomain = defaultDomain;
   } else {
     ntdomain = s.substring(0, i).toUpperCase();
     username = s.substring(i + 1);
   }
   password = pw.getPassword();
   init0();
   try {
     client =
         new Client(System.getProperty("ntlm.version"), hostname, username, ntdomain, password);
   } catch (NTLMException ne) {
     try {
       client = new Client(null, hostname, username, ntdomain, password);
     } catch (NTLMException ne2) {
       // Will never happen
       throw new AssertionError("Really?");
     }
   }
 }
  /**
   * Returns the authorization credentials on the base of provided authorization challenge
   *
   * @param challenge
   * @return authorization credentials
   * @throws IOException
   */
  private String getAuthorizationCredentials(String challenge) throws IOException {

    int idx = challenge.indexOf(" "); // $NON-NLS-1$
    String scheme = challenge.substring(0, idx);
    int realm = challenge.indexOf("realm=\"") + 7; // $NON-NLS-1$
    String prompt = null;
    if (realm != -1) {
      int end = challenge.indexOf('"', realm);
      if (end != -1) {
        prompt = challenge.substring(realm, end);
      }
    }
    // The following will use the user-defined authenticator to get
    // the password
    PasswordAuthentication pa =
        Authenticator.requestPasswordAuthentication(
            getHostAddress(), getHostPort(), url.getProtocol(), prompt, scheme);
    if (pa == null) {
      // could not retrieve the credentials
      return null;
    }
    // base64 encode the username and password
    byte[] bytes =
        (pa.getUserName() + ":" + new String(pa.getPassword())) // $NON-NLS-1$
            .getBytes("ISO8859_1"); // $NON-NLS-1$
    String encoded = Base64.encode(bytes, "ISO8859_1"); // $NON-NLS-1$
    return scheme + " " + encoded; // $NON-NLS-1$
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(LinkedList<String> dataLinkedList) throws Throwable {
    String data = dataLinkedList.remove(2);

    if (data != null) {
      /* POTENTIAL FLAW: data used as password in PasswordAuthentication() */
      PasswordAuthentication credentials = new PasswordAuthentication("user", data.toCharArray());
      IO.writeLine(credentials.toString());
    }
  }
  private void badSink() throws Throwable {
    String password = passwordBad;

    if (password != null) {
      /* POTENTIAL FLAW: Use password directly in PasswordAuthentication() */
      PasswordAuthentication credentials =
          new PasswordAuthentication("user", password.toCharArray());
      IO.writeLine(credentials.toString());
    }
  }
 /** @see CredentialsAgent#store */
 @Override
 public void store(RequestorType requestorType, String host, PasswordAuthentication credentials)
     throws CredentialsAgentException {
   if (requestorType == null) return;
   switch (requestorType) {
     case SERVER:
       if (Objects.equals(OsmApi.getOsmApi().getHost(), host)) {
         Main.pref.put("osm-server.username", credentials.getUserName());
         if (credentials.getPassword() == null) {
           Main.pref.put("osm-server.password", null);
         } else {
           Main.pref.put("osm-server.password", String.valueOf(credentials.getPassword()));
         }
       } else if (host != null) {
         Main.pref.put("server.username." + host, credentials.getUserName());
         if (credentials.getPassword() == null) {
           Main.pref.put("server.password." + host, null);
         } else {
           Main.pref.put("server.password." + host, String.valueOf(credentials.getPassword()));
         }
       }
       break;
     case PROXY:
       Main.pref.put(ProxyPreferencesPanel.PROXY_USER, credentials.getUserName());
       if (credentials.getPassword() == null) {
         Main.pref.put(ProxyPreferencesPanel.PROXY_PASS, null);
       } else {
         Main.pref.put(
             ProxyPreferencesPanel.PROXY_PASS, String.valueOf(credentials.getPassword()));
       }
       break;
   }
 }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */
    PasswordAuthentication credentials =
        new PasswordAuthentication("user", "BP@ssw0rd".toCharArray());

    /* POTENTIAL FLAW: Set data to credentials (without hashing or encryption) */
    data = credentials.getUserName() + ":" + (new String(credentials.getPassword()));

    (new CWE315_Plaintext_Storage_in_Cookie__Servlet_53b()).goodB2GSink(data, request, response);
  }
示例#9
0
 private void init(PasswordAuthentication pw) {
   this.pw = pw;
   String s = pw.getUserName();
   int i = s.indexOf('\\');
   if (i == -1) {
     username = s;
     ntdomain = defaultDomain;
   } else {
     ntdomain = s.substring(0, i).toUpperCase();
     username = s.substring(i + 1);
   }
   password = new String(pw.getPassword());
   init0();
 }
示例#10
0
  /**
   * Returns the authorization credentials that may satisfy the challenge. Returns null if a
   * challenge header was not provided or if credentials were not available.
   */
  private static String getCredentials(
      RawHeaders responseHeaders, String challengeHeader, Proxy proxy, URL url) throws IOException {
    List<Challenge> challenges = parseChallenges(responseHeaders, challengeHeader);
    if (challenges.isEmpty()) {
      return null;
    }

    for (Challenge challenge : challenges) {
      // Use the global authenticator to get the password.
      PasswordAuthentication auth;
      if (responseHeaders.getResponseCode() == HTTP_PROXY_AUTH) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        auth =
            Authenticator.requestPasswordAuthentication(
                proxyAddress.getHostName(),
                getConnectToInetAddress(proxy, url),
                proxyAddress.getPort(),
                url.getProtocol(),
                challenge.realm,
                challenge.scheme,
                url,
                Authenticator.RequestorType.PROXY);
      } else {
        auth =
            Authenticator.requestPasswordAuthentication(
                url.getHost(),
                getConnectToInetAddress(proxy, url),
                url.getPort(),
                url.getProtocol(),
                challenge.realm,
                challenge.scheme,
                url,
                Authenticator.RequestorType.SERVER);
      }
      if (auth == null) {
        continue;
      }

      // Use base64 to encode the username and password.
      String usernameAndPassword = auth.getUserName() + ":" + new String(auth.getPassword());
      byte[] bytes = usernameAndPassword.getBytes("ISO-8859-1");
      String encoded = Base64.encode(bytes);
      return challenge.scheme + " " + encoded;
    }

    return null;
  }
 public Credentials getCredentials(final AuthScope authscope) {
   Args.notNull(authscope, "Auth scope");
   final Credentials localcreds = internal.getCredentials(authscope);
   if (localcreds != null) {
     return localcreds;
   }
   if (authscope.getHost() != null) {
     PasswordAuthentication systemcreds =
         getSystemCreds(authscope, Authenticator.RequestorType.SERVER);
     if (systemcreds == null) {
       systemcreds = getSystemCreds(authscope, Authenticator.RequestorType.PROXY);
     }
     if (systemcreds != null) {
       final String domain = System.getProperty("http.auth.ntlm.domain");
       if (domain != null) {
         return new NTCredentials(
             systemcreds.getUserName(), new String(systemcreds.getPassword()), null, domain);
       } else {
         if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) {
           // Domian may be specified in a fully qualified user name
           return new NTCredentials(
               systemcreds.getUserName(), new String(systemcreds.getPassword()), null, null);
         } else {
           return new UsernamePasswordCredentials(
               systemcreds.getUserName(), new String(systemcreds.getPassword()));
         }
       }
     }
   }
   return null;
 }
  private void goodB2GSink() throws Throwable {
    String password = passwordGoodB2G;

    if (password != null) {
      /* FIX: Decrypt password before using in PasswordAuthentication() */
      {
        Cipher aesCipher = Cipher.getInstance("AES");
        /* INCIDENTAL: CWE-321: Use of Hard-coded Cryptographic Key */
        SecretKeySpec secretKeySpec =
            new SecretKeySpec("ABCDEFGHABCDEFGH".getBytes("UTF-8"), "AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        password = new String(aesCipher.doFinal(password.getBytes("UTF-8")), "UTF-8");
      }
      PasswordAuthentication credentials =
          new PasswordAuthentication("user", password.toCharArray());
      IO.writeLine(credentials.toString());
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;

    /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */
    PasswordAuthentication credentials =
        new PasswordAuthentication("user", "GP@ssw0rd".toCharArray());

    /* FIX: Set data to a hash of credentials */
    {
      String salt = "ThisIsMySalt";
      MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
      messageDigest.reset();
      String credentialsToHash =
          credentials.getUserName() + ":" + (new String(credentials.getPassword()));
      byte[] hashedCredsAsBytes =
          messageDigest.digest((salt + credentialsToHash).getBytes("UTF-8"));
      data = IO.toHex(hashedCredsAsBytes);
    }

    (new CWE315_Plaintext_Storage_in_Cookie__Servlet_53b()).goodG2BSink(data, request, response);
  }
 public void initFromPreferences() {
   CredentialsAgent cm = CredentialsManager.getInstance();
   try {
     decorationPanel.removeAll();
     decorationPanel.add(cm.getPreferencesDecorationPanel(), BorderLayout.CENTER);
     PasswordAuthentication pa = cm.lookup(RequestorType.SERVER);
     if (pa == null) {
       tfOsmUserName.setText("");
       tfOsmPassword.setText("");
     } else {
       tfOsmUserName.setText(pa.getUserName() == null ? "" : pa.getUserName());
       tfOsmPassword.setText(pa.getPassword() == null ? "" : String.valueOf(pa.getPassword()));
     }
   } catch (CredentialsAgentException e) {
     e.printStackTrace();
     System.err.println(
         tr("Warning: failed to retrieve OSM credentials from credential manager."));
     System.err.println(
         tr("Current credential manager is of type ''{0}''", cm.getClass().getName()));
     tfOsmUserName.setText("");
     tfOsmPassword.setText("");
   }
 }
 String createAuthenticationHeader() {
   PasswordAuthentication credentials = getCredentialsForRealm();
   return getAuthenticationStrategy()
       .createAuthenticationHeader(
           this, credentials.getUserName(), new String(credentials.getPassword()));
 }
示例#16
0
  /**
   * Similar to connect(host, user, password) except a specific port can be specified.
   *
   * @param host the host to connect to
   * @param port the port to connect to (-1 means the default port)
   * @param user the user name
   * @param password this user's password
   * @exception AuthenticationFailedException for authentication failures
   * @exception MessagingException for other failures
   * @exception IllegalStateException if the service is already connected
   * @see #connect(java.lang.String, java.lang.String, java.lang.String)
   * @see javax.mail.event.ConnectionEvent
   */
  public synchronized void connect(String host, int port, String user, String password)
      throws MessagingException {

    // see if the service is already connected
    if (isConnected()) throw new IllegalStateException("already connected");

    PasswordAuthentication pw;
    boolean connected = false;
    boolean save = false;
    String protocol = null;
    String file = null;

    // get whatever information we can from the URL
    // XXX - url should always be non-null here, Session
    //       passes it into the constructor
    if (url != null) {
      protocol = url.getProtocol();
      if (host == null) host = url.getHost();
      if (port == -1) port = url.getPort();

      if (user == null) {
        user = url.getUsername();
        if (password == null) // get password too if we need it
        password = url.getPassword();
      } else {
        if (password == null && user.equals(url.getUsername()))
          // only get the password if it matches the username
          password = url.getPassword();
      }

      file = url.getFile();
    }

    // try to get protocol-specific default properties
    if (protocol != null) {
      if (host == null) host = session.getProperty("mail." + protocol + ".host");
      if (user == null) user = session.getProperty("mail." + protocol + ".user");
    }

    // try to get mail-wide default properties
    if (host == null) host = session.getProperty("mail.host");

    if (user == null) user = session.getProperty("mail.user");

    // try using the system username
    if (user == null) {
      try {
        user = System.getProperty("user.name");
      } catch (SecurityException sex) {
        // XXX - it's not worth creating a MailLogger just for this
        // logger.log(Level.CONFIG, "Can't get user.name property", sex);
      }
    }

    // if we don't have a password, look for saved authentication info
    if (password == null && url != null) {
      // canonicalize the URLName
      setURLName(new URLName(protocol, host, port, file, user, null));
      pw = session.getPasswordAuthentication(getURLName());
      if (pw != null) {
        if (user == null) {
          user = pw.getUserName();
          password = pw.getPassword();
        } else if (user.equals(pw.getUserName())) {
          password = pw.getPassword();
        }
      } else save = true;
    }

    // try connecting, if the protocol needs some missing
    // information (user, password) it will not connect.
    // if it tries to connect and fails, remember why for later.
    AuthenticationFailedException authEx = null;
    try {
      connected = protocolConnect(host, port, user, password);
    } catch (AuthenticationFailedException ex) {
      authEx = ex;
    }

    // if not connected, ask the user and try again
    if (!connected) {
      InetAddress addr;
      try {
        addr = InetAddress.getByName(host);
      } catch (UnknownHostException e) {
        addr = null;
      }
      pw = session.requestPasswordAuthentication(addr, port, protocol, null, user);
      if (pw != null) {
        user = pw.getUserName();
        password = pw.getPassword();

        // have the service connect again
        connected = protocolConnect(host, port, user, password);
      }
    }

    // if we're not connected by now, we give up
    if (!connected) {
      if (authEx != null) throw authEx;
      else if (user == null)
        throw new AuthenticationFailedException("failed to connect, no user name specified?");
      else if (password == null)
        throw new AuthenticationFailedException("failed to connect, no password specified?");
      else throw new AuthenticationFailedException("failed to connect");
    }

    setURLName(new URLName(protocol, host, port, file, user, password));

    if (save)
      session.setPasswordAuthentication(getURLName(), new PasswordAuthentication(user, password));

    // set our connected state
    setConnected(true);

    // finally, deliver the connection event
    notifyConnectionListeners(ConnectionEvent.OPENED);
  }