public ImportImageBuilder withBucketUploadPolicy(final String bucket, final String prefix) {
      try {
        final AccessKey adminAccessKey = Accounts.lookupSystemAdmin().getKeys().get(0);
        this.importDisk.setAccessKey(adminAccessKey.getAccessKey());
        final Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, 48); // IMPORT_TASK_EXPIRATION_HOURS=48
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        final String expiration = sdf.format(c.getTime());
        // based on
        // http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-BundleInstance.html
        final String policy =
            String.format(
                "{\"expiration\":\"%s\",\"conditions\":[{\"bucket\": \"%s\"},"
                    + "[\"starts-with\", \"$key\", \"%s\"],{\"acl\":\"aws-exec-read\"}]}",
                expiration, bucket, prefix);
        this.importDisk.setUploadPolicy(B64.standard.encString(policy));

        final Mac hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(adminAccessKey.getSecretKey().getBytes("UTF-8"), "HmacSHA1"));

        this.importDisk.setUploadPolicySignature(
            B64.standard.encString(hmac.doFinal(B64.standard.encString(policy).getBytes("UTF-8"))));
      } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
      }
      return this;
    }
예제 #2
0
 public SnapshotObjectOps() {
   try {
     Account system = Accounts.lookupAccountByName(Account.SYSTEM_ACCOUNT);
     for (User user : system.getUsers()) {
       if (StorageProperties.BLOCKSTORAGE_ACCOUNT.equals(user.getName())) {
         List<AccessKey> keys = user.getKeys();
         if (!keys.isEmpty()) {
           AccessKey key = keys.get(0);
           s3Client =
               new S3Client(
                   new BasicAWSCredentials(key.getAccessKey(), key.getSecretKey()), false);
           s3Client.setUsePathStyle(true);
           s3Client.setS3Endpoint(StorageProperties.WALRUS_URL);
         } else {
           LOG.error(
               "Something went really wrong. Block storage account does not have an associated access key.");
         }
       }
     }
   } catch (Exception ex) {
     LOG.error(ex, ex);
   }
 }
 @Override
 public boolean authenticate(HmacCredentials credentials) throws Exception {
   String sig = credentials.getSignature();
   checkForReplay(sig);
   AccessKey accessKey = lookupAccessKey(credentials);
   User user = accessKey.getUser();
   String secretKey = accessKey.getSecretKey();
   String canonicalString =
       this.makeSubjectString(
           credentials.getVerb(),
           credentials.getHeaderHost(),
           credentials.getServicePath(),
           credentials.getParameters());
   String canonicalStringWithPort =
       this.makeSubjectString(
           credentials.getVerb(),
           credentials.getHeaderHost() + ":" + credentials.getHeaderPort(),
           credentials.getServicePath(),
           credentials.getParameters());
   String canonicalStringWithAwsCliPath =
       this.makeSubjectString(
           credentials.getVerb(),
           credentials.getHeaderHost() + ":" + credentials.getHeaderPort(),
           convertForAwsCli(credentials.getServicePath()),
           credentials.getParameters());
   String computedSig =
       this.getSignature(secretKey, canonicalString, credentials.getSignatureMethod());
   String computedSigWithPort =
       this.getSignature(secretKey, canonicalStringWithPort, credentials.getSignatureMethod());
   String computedSigWithAwsCliPath =
       this.getSignature(
           secretKey, canonicalStringWithAwsCliPath, credentials.getSignatureMethod());
   if (!computedSig.equals(sig)
       && !computedSigWithPort.equals(sig)
       && !computedSigWithAwsCliPath.equals(sig)) {
     sig = sanitize(urldecode(sig));
     computedSig =
         this.getSignature(
                 secretKey,
                 canonicalString.replaceAll("\\+", "%2B"),
                 credentials.getSignatureMethod())
             .replaceAll("\\+", " ");
     computedSigWithPort =
         this.getSignature(
                 secretKey,
                 canonicalStringWithPort.replaceAll("\\+", "%2B"),
                 credentials.getSignatureMethod())
             .replaceAll("\\+", " ");
     computedSigWithAwsCliPath =
         this.getSignature(
                 secretKey,
                 canonicalStringWithAwsCliPath.replaceAll("\\+", "%2B"),
                 credentials.getSignatureMethod())
             .replaceAll("\\+", " ");
     if (!computedSig.equals(sig)
         && !computedSigWithPort.equals(sig)
         && !computedSigWithAwsCliPath.equals(sig)) {
       computedSig =
           this.getSignature(
                   secretKey,
                   canonicalString.replaceAll("\\+", "%20"),
                   credentials.getSignatureMethod())
               .replaceAll("\\+", " ");
       computedSigWithPort =
           this.getSignature(
                   secretKey,
                   canonicalStringWithPort.replaceAll("\\+", "%20"),
                   credentials.getSignatureMethod())
               .replaceAll("\\+", " ");
       computedSigWithAwsCliPath =
           this.getSignature(
                   secretKey,
                   canonicalStringWithAwsCliPath.replaceAll("\\+", "%20"),
                   credentials.getSignatureMethod())
               .replaceAll("\\+", " ");
       if (!computedSig.equals(sig)
           && !computedSigWithPort.equals(sig)
           && !computedSigWithAwsCliPath.equals(sig)) {
         computedSig =
             this.getSignature(
                     secretKey,
                     canonicalString.replaceAll("\\*", "%2A"),
                     credentials.getSignatureMethod())
                 .replaceAll("\\+", " ");
         computedSigWithPort =
             this.getSignature(
                     secretKey,
                     canonicalStringWithPort.replaceAll("\\*", "%2A"),
                     credentials.getSignatureMethod())
                 .replaceAll("\\+", " ");
         computedSigWithAwsCliPath =
             this.getSignature(
                     secretKey,
                     canonicalStringWithAwsCliPath.replaceAll("\\*", "%2A"),
                     credentials.getSignatureMethod())
                 .replaceAll("\\+", " ");
         if (!computedSig.equals(sig)
             && !computedSigWithPort.equals(sig)
             && !computedSigWithAwsCliPath.equals(sig)) {
           return false;
         }
       }
     }
   }
   super.setCredential(credentials.getQueryIdCredential(AccessKeys.getKeyType(accessKey)));
   super.setPrincipal(user);
   // super.getGroups( ).addAll( Groups.lookupUserGroups( super.getPrincipal( ) ) );
   return true;
 }
예제 #4
0
  private static byte[] getX509Zip(User u) throws Exception {
    X509Certificate cloudCert = null;
    final X509Certificate x509;
    String userAccessKey = null;
    String userSecretKey = null;
    KeyPair keyPair = null;
    try {
      for (AccessKey k : u.getKeys()) {
        if (k.isActive()) {
          userAccessKey = k.getAccessKey();
          userSecretKey = k.getSecretKey();
        }
      }
      if (userAccessKey == null) {
        AccessKey k = u.createKey();
        userAccessKey = k.getAccessKey();
        userSecretKey = k.getSecretKey();
      }
      keyPair = Certs.generateKeyPair();
      x509 = Certs.generateCertificate(keyPair, u.getName());
      x509.checkValidity();
      u.addCertificate(x509);
      cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate();
    } catch (Exception e) {
      LOG.fatal(e, e);
      throw e;
    }
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut);
    ZipArchiveEntry entry = null;
    String fingerPrint = Certs.getFingerPrint(keyPair.getPublic());
    if (fingerPrint != null) {
      String baseName =
          X509Download.NAME_SHORT
              + "-"
              + u.getName()
              + "-"
              + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8);

      zipOut.setComment("To setup the environment run: source /path/to/eucarc");
      StringBuilder sb = new StringBuilder();
      // TODO:GRZE:FIXME velocity
      String userNumber = u.getAccount().getAccountNumber();
      sb.append("EUCA_KEY_DIR=$(dirname $(readlink -f ${BASH_SOURCE}))");
      if (Topology.isEnabled(Eucalyptus.class)) { // GRZE:NOTE: this is temporary
        sb.append(
            "\nexport EC2_URL=" + ServiceUris.remotePublicify(Topology.lookup(Eucalyptus.class)));
      } else {
        sb.append("\necho WARN:  Eucalyptus URL is not configured. >&2");
        ServiceBuilder<? extends ServiceConfiguration> builder =
            ServiceBuilders.lookup(Eucalyptus.class);
        ServiceConfiguration localConfig =
            builder.newInstance(
                Internets.localHostAddress(),
                Internets.localHostAddress(),
                Internets.localHostAddress(),
                Eucalyptus.INSTANCE.getPort());
        sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig));
      }
      if (Topology.isEnabled(Walrus.class)) {
        ServiceConfiguration walrusConfig = Topology.lookup(Walrus.class);
        try {
          String uri = ServiceUris.remotePublicify(walrusConfig).toASCIIString();
          LOG.debug("Found walrus uri/configuration: uri=" + uri + " config=" + walrusConfig);
          sb.append("\nexport S3_URL=" + uri);
        } catch (Exception e) {
          LOG.error("Failed to set Walrus URL: " + walrusConfig, e);
        }
      } else {
        sb.append("\necho WARN:  Walrus URL is not configured. >&2");
      }
      // Disable notifications for now
      // sb.append( "\nexport AWS_SNS_URL=" + ServiceUris.remote( Notifications.class ) );
      if (Topology.isEnabled(Euare.class)) { // GRZE:NOTE: this is temporary
        sb.append("\nexport EUARE_URL=" + ServiceUris.remotePublicify(Euare.class));
      } else {
        sb.append("\necho WARN:  EUARE URL is not configured. >&2");
      }
      sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem");
      sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem");
      sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts");
      sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem");
      sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'");
      sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'");
      sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'");
      sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc");
      sb.append("\nexport EC2_USER_ID='" + userNumber + "'");
      sb.append(
          "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\"");
      sb.append(
          "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\"");
      sb.append("\n");
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc"));
      entry.setUnixMode(0600);
      zipOut.write(sb.toString().getBytes("UTF-8"));
      zipOut.closeArchiveEntry();

      sb = new StringBuilder();
      sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n');
      sb.append("AWSSecretKey=").append(userSecretKey);
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc"));
      entry.setUnixMode(0600);
      zipOut.write(sb.toString().getBytes("UTF-8"));
      zipOut.closeArchiveEntry();

      /** write the private key to the zip stream * */
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem"));
      entry.setUnixMode(0600);
      zipOut.write(PEMFiles.getBytes(cloudCert));
      zipOut.closeArchiveEntry();

      zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts"));
      entry.setUnixMode(0600);
      KeyStore tempKs = KeyStore.getInstance("jks");
      tempKs.load(null);
      tempKs.setCertificateEntry("eucalyptus", cloudCert);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      tempKs.store(bos, "changeit".toCharArray());
      zipOut.write(bos.toByteArray());
      zipOut.closeArchiveEntry();

      /** write the private key to the zip stream * */
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem"));
      entry.setUnixMode(0600);
      zipOut.write(PEMFiles.getBytes(keyPair.getPrivate()));
      zipOut.closeArchiveEntry();

      /** write the X509 certificate to the zip stream * */
      zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem"));
      entry.setUnixMode(0600);
      zipOut.write(PEMFiles.getBytes(x509));
      zipOut.closeArchiveEntry();
    }
    /** close the zip output stream and return the bytes * */
    zipOut.close();
    return byteOut.toByteArray();
  }