Search in sources :

Example 1 with DomainValidator

use of org.apache.commons.validator.routines.DomainValidator in project ozone by apache.

the class TestRootCertificate method testCACert.

@Test
public void testCACert() throws SCMSecurityException, NoSuchProviderException, NoSuchAlgorithmException, IOException, CertificateException {
    LocalDate notBefore = LocalDate.now();
    LocalDate notAfter = notBefore.plus(365, ChronoUnit.DAYS);
    String clusterID = UUID.randomUUID().toString();
    String scmID = UUID.randomUUID().toString();
    String subject = "testRootCert";
    HDDSKeyGenerator keyGen = new HDDSKeyGenerator(securityConfig.getConfiguration());
    KeyPair keyPair = keyGen.generateKey();
    SelfSignedCertificate.Builder builder = SelfSignedCertificate.newBuilder().setBeginDate(notBefore).setEndDate(notAfter).setClusterID(clusterID).setScmID(scmID).setSubject(subject).setKey(keyPair).setConfiguration(conf).makeCA();
    try {
        DomainValidator validator = DomainValidator.getInstance();
        // Add all valid ips.
        OzoneSecurityUtil.getValidInetsForCurrentHost().forEach(ip -> {
            builder.addIpAddress(ip.getHostAddress());
            if (validator.isValid(ip.getCanonicalHostName())) {
                builder.addDnsName(ip.getCanonicalHostName());
            }
        });
    } catch (IOException e) {
        throw new org.apache.hadoop.hdds.security.x509.exceptions.CertificateException("Error while adding ip to CA self signed certificate", e, CSR_ERROR);
    }
    X509CertificateHolder certificateHolder = builder.build();
    // This time we asked for a CertificateServer Certificate, make sure that
    // extension is
    // present and valid.
    Extension basicExt = certificateHolder.getExtension(Extension.basicConstraints);
    Assert.assertNotNull(basicExt);
    Assert.assertTrue(basicExt.isCritical());
    // Since this code assigns ONE for the root certificate, we check if the
    // serial number is the expected number.
    Assert.assertEquals(certificateHolder.getSerialNumber(), BigInteger.ONE);
    CertificateCodec codec = new CertificateCodec(securityConfig, "scm");
    String pemString = codec.getPEMEncodedString(certificateHolder);
    File basePath = temporaryFolder.newFolder();
    if (!basePath.exists()) {
        Assert.assertTrue(basePath.mkdirs());
    }
    codec.writeCertificate(basePath.toPath(), "pemcertificate.crt", pemString, false);
    X509CertificateHolder loadedCert = codec.readCertificate(basePath.toPath(), "pemcertificate.crt");
    assertNotNull(loadedCert);
    assertEquals(certificateHolder.getSerialNumber(), loadedCert.getSerialNumber());
}
Also used : KeyPair(java.security.KeyPair) HDDSKeyGenerator(org.apache.hadoop.hdds.security.x509.keys.HDDSKeyGenerator) SelfSignedCertificate(org.apache.hadoop.hdds.security.x509.certificates.utils.SelfSignedCertificate) CertificateCodec(org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateCodec) IOException(java.io.IOException) LocalDate(java.time.LocalDate) Extension(org.bouncycastle.asn1.x509.Extension) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DomainValidator(org.apache.commons.validator.routines.DomainValidator) File(java.io.File) Test(org.junit.Test)

Example 2 with DomainValidator

use of org.apache.commons.validator.routines.DomainValidator in project ozone by apache.

the class DefaultCertificateClient method getCSRBuilder.

/**
 * Returns a CSR builder that can be used to creates a Certificate signing
 * request.
 *
 * @return CertificateSignRequest.Builder
 */
@Override
public CertificateSignRequest.Builder getCSRBuilder() throws CertificateException {
    CertificateSignRequest.Builder builder = new CertificateSignRequest.Builder().setConfiguration(securityConfig.getConfiguration());
    try {
        DomainValidator validator = DomainValidator.getInstance();
        // Add all valid ips.
        OzoneSecurityUtil.getValidInetsForCurrentHost().forEach(ip -> {
            builder.addIpAddress(ip.getHostAddress());
            if (validator.isValid(ip.getCanonicalHostName())) {
                builder.addDnsName(ip.getCanonicalHostName());
            } else {
                getLogger().error("Invalid domain {}", ip.getCanonicalHostName());
            }
        });
    } catch (IOException e) {
        throw new CertificateException("Error while adding ip to CSR builder", e, CSR_ERROR);
    }
    return builder;
}
Also used : DomainValidator(org.apache.commons.validator.routines.DomainValidator) CertificateException(org.apache.hadoop.hdds.security.x509.exceptions.CertificateException) IOException(java.io.IOException) CertificateSignRequest(org.apache.hadoop.hdds.security.x509.certificates.utils.CertificateSignRequest)

Example 3 with DomainValidator

use of org.apache.commons.validator.routines.DomainValidator in project ozone by apache.

the class DefaultCAServer method generateRootCertificate.

/**
 * Generates a self-signed Root Certificate for CA.
 *
 * @param securityConfig - SecurityConfig
 * @param key - KeyPair.
 * @throws IOException          - on Error.
 * @throws SCMSecurityException - on Error.
 */
private void generateRootCertificate(SecurityConfig securityConfig, KeyPair key) throws IOException, SCMSecurityException {
    Preconditions.checkNotNull(this.config);
    LocalDate beginDate = LocalDate.now().atStartOfDay().toLocalDate();
    LocalDateTime temp = LocalDateTime.of(beginDate, LocalTime.MIDNIGHT);
    LocalDate endDate = temp.plus(securityConfig.getMaxCertificateDuration()).toLocalDate();
    SelfSignedCertificate.Builder builder = SelfSignedCertificate.newBuilder().setSubject(this.subject).setScmID(this.scmID).setClusterID(this.clusterID).setBeginDate(beginDate).setEndDate(endDate).makeCA().setConfiguration(securityConfig.getConfiguration()).setKey(key);
    try {
        DomainValidator validator = DomainValidator.getInstance();
        // Add all valid ips.
        OzoneSecurityUtil.getValidInetsForCurrentHost().forEach(ip -> {
            builder.addIpAddress(ip.getHostAddress());
            if (validator.isValid(ip.getCanonicalHostName())) {
                builder.addDnsName(ip.getCanonicalHostName());
            }
        });
    } catch (IOException e) {
        throw new org.apache.hadoop.hdds.security.x509.exceptions.CertificateException("Error while adding ip to CA self signed certificate", e, CSR_ERROR);
    }
    X509CertificateHolder selfSignedCertificate = builder.build();
    CertificateCodec certCodec = new CertificateCodec(config, componentName);
    certCodec.writeCertificate(selfSignedCertificate);
}
Also used : LocalDateTime(java.time.LocalDateTime) SelfSignedCertificate(org.apache.hadoop.hdds.security.x509.certificates.utils.SelfSignedCertificate) CertificateCodec(org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateCodec) IOException(java.io.IOException) LocalDate(java.time.LocalDate) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DomainValidator(org.apache.commons.validator.routines.DomainValidator)

Example 4 with DomainValidator

use of org.apache.commons.validator.routines.DomainValidator in project SimpleProtocolPlayer by kaytat.

the class MainActivity method onClick.

public void onClick(View target) {
    // button that was clicked
    if (target == playButton) {
        switch(getNetworkConnection()) {
            case NOT_CONNECTED:
                Toast.makeText(getApplicationContext(), "No network connectivity.", Toast.LENGTH_SHORT).show();
                return;
            case NON_WIFI_CONNECTED:
                Toast.makeText(getApplicationContext(), "WARNING: wifi not connected.", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        hideKb();
        // Get the IP address and port and put it in the intent
        Intent i = new Intent(MusicService.ACTION_PLAY);
        i.setPackage(getPackageName());
        String ipAddr = ipAddrText.getText().toString();
        String portStr = audioPortText.getText().toString();
        // Check address string against domain, IPv4, and IPv6
        DomainValidator domainValidator = DomainValidator.getInstance();
        InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
        if (!domainValidator.isValid(ipAddr) && !inetAddressValidator.isValidInet4Address(ipAddr) && !inetAddressValidator.isValidInet6Address(ipAddr)) {
            Toast.makeText(getApplicationContext(), "Invalid address", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.d(TAG, "ip:" + ipAddr);
        i.putExtra(MusicService.DATA_IP_ADDRESS, ipAddr);
        int audioPort;
        try {
            audioPort = Integer.parseInt(portStr);
        } catch (NumberFormatException nfe) {
            Log.e(TAG, "Invalid port:" + nfe);
            Toast.makeText(getApplicationContext(), "Invalid port", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.d(TAG, "port:" + audioPort);
        i.putExtra(MusicService.DATA_AUDIO_PORT, audioPort);
        // Extract sample rate
        Spinner sampleRateSpinner = findViewById(R.id.spinnerSampleRate);
        String rateStr = String.valueOf(sampleRateSpinner.getSelectedItem());
        String[] rateSplit = rateStr.split(" ");
        try {
            sampleRate = Integer.parseInt(rateSplit[0]);
            Log.i(TAG, "rate:" + sampleRate);
            i.putExtra(MusicService.DATA_SAMPLE_RATE, sampleRate);
        } catch (NumberFormatException nfe) {
            Log.e(TAG, "Invalid rate:" + nfe);
            Toast.makeText(getApplicationContext(), "Invalid rate", Toast.LENGTH_SHORT).show();
            return;
        }
        // Extract stereo/mono setting
        Spinner stereoSpinner = findViewById(R.id.stereo);
        String stereoSettingString = String.valueOf(stereoSpinner.getSelectedItem());
        String stereoKey = getResources().getString(R.string.stereoKey);
        stereo = stereoSettingString.contains(stereoKey);
        i.putExtra(MusicService.DATA_STEREO, stereo);
        Log.i(TAG, "stereo:" + stereo);
        // Get the latest buffer entry
        EditText e = findViewById(R.id.editTextBufferSize);
        String bufferMsString = e.getText().toString();
        try {
            bufferMs = Integer.parseInt(bufferMsString);
            Log.d(TAG, "buffer ms:" + bufferMs);
            i.putExtra(MusicService.DATA_BUFFER_MS, bufferMs);
        } catch (NumberFormatException nfe) {
            Log.e(TAG, "Invalid buffer ms:" + nfe);
            Toast.makeText(getApplicationContext(), "Invalid buffer ms", Toast.LENGTH_SHORT).show();
            return;
        }
        // Get the retry checkbox
        retry = ((CheckBox) findViewById(R.id.checkBoxRetry)).isChecked();
        Log.d(TAG, "retry:" + retry);
        i.putExtra(MusicService.DATA_RETRY, retry);
        // Get the usePerformanceMode checkbox
        usePerformanceMode = ((CheckBox) findViewById(R.id.checkBoxUsePerformanceMode)).isChecked();
        Log.d(TAG, "usePerformanceMode:" + usePerformanceMode);
        i.putExtra(MusicService.DATA_USE_PERFORMANCE_MODE, usePerformanceMode);
        // Get the useMinBuffer checkbox
        useMinBuffer = ((CheckBox) findViewById(R.id.checkBoxUseMinBuffer)).isChecked();
        Log.d(TAG, "useMinBuffer:" + useMinBuffer);
        i.putExtra(MusicService.DATA_USE_MIN_BUFFER, useMinBuffer);
        // Save current settings
        savePrefs();
        startService(i);
    } else if (target == stopButton) {
        hideKb();
        Intent i = new Intent(MusicService.ACTION_STOP);
        i.setPackage(getPackageName());
        startService(i);
    }
}
Also used : EditText(android.widget.EditText) Spinner(android.widget.Spinner) Intent(android.content.Intent) DomainValidator(org.apache.commons.validator.routines.DomainValidator) InetAddressValidator(org.apache.commons.validator.routines.InetAddressValidator) SuppressLint(android.annotation.SuppressLint)

Example 5 with DomainValidator

use of org.apache.commons.validator.routines.DomainValidator in project openvidu by OpenVidu.

the class OpenviduConfig method asOptionalInetAddress.

/*
	 * This method checks all types of Internet addresses (IPv4, IPv6 and Domains)
	 */
protected String asOptionalInetAddress(String property) {
    String inetAddress = getValue(property);
    if (inetAddress != null && !inetAddress.isEmpty()) {
        DomainValidator domainValidator = DomainValidator.getInstance();
        if (domainValidator.isValid(inetAddress)) {
            return inetAddress;
        }
        InetAddressValidator ipValidator = InetAddressValidator.getInstance();
        if (ipValidator.isValid(inetAddress)) {
            return inetAddress;
        }
        try {
            Inet6Address.getByName(inetAddress).getHostAddress();
            return inetAddress;
        } catch (UnknownHostException e) {
            addError(property, "Is not a valid Internet Address (IP or Domain Name): " + e.getMessage());
        }
    }
    return inetAddress;
}
Also used : UnknownHostException(java.net.UnknownHostException) DomainValidator(org.apache.commons.validator.routines.DomainValidator) InetAddressValidator(org.apache.commons.validator.routines.InetAddressValidator)

Aggregations

DomainValidator (org.apache.commons.validator.routines.DomainValidator)5 IOException (java.io.IOException)3 LocalDate (java.time.LocalDate)2 InetAddressValidator (org.apache.commons.validator.routines.InetAddressValidator)2 CertificateCodec (org.apache.hadoop.hdds.security.x509.certificate.utils.CertificateCodec)2 SelfSignedCertificate (org.apache.hadoop.hdds.security.x509.certificates.utils.SelfSignedCertificate)2 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)2 SuppressLint (android.annotation.SuppressLint)1 Intent (android.content.Intent)1 EditText (android.widget.EditText)1 Spinner (android.widget.Spinner)1 File (java.io.File)1 UnknownHostException (java.net.UnknownHostException)1 KeyPair (java.security.KeyPair)1 LocalDateTime (java.time.LocalDateTime)1 CertificateSignRequest (org.apache.hadoop.hdds.security.x509.certificates.utils.CertificateSignRequest)1 CertificateException (org.apache.hadoop.hdds.security.x509.exceptions.CertificateException)1 HDDSKeyGenerator (org.apache.hadoop.hdds.security.x509.keys.HDDSKeyGenerator)1 Extension (org.bouncycastle.asn1.x509.Extension)1 Test (org.junit.Test)1