std::string
CommandEventHandler::cd(std::vector<std::string>& args)
{
  std::string path(args.size() ? args[0] : "");
  if (path.compare("") == 0)
    path = "/";
  const char *p = path.c_str();

  // check if path exists and it is a dir
  std::string ret = isDir(path);
  if (ret.compare("TRUE") != 0)
  {
    if (ret.compare("FALSE") == 0)
      return agentWarn("path is not a dir");
    return ret;
  }

  // check for read permissions
  PRStatus success = PR_Access(p, PR_ACCESS_READ_OK);
  if (success == PR_SUCCESS)
  {
    // update the cwd
    int s = chdir(p);
    if (s == 0)
      return "";
  }
  return agentWarn("no permissions");
}
Exemple #2
0
/***************************************************************************
 *
 * m a k e _ d i r s
 *
 * Ensure that the directory portion of the path exists.  This may require
 * making the directory, and its parent, and its parent's parent, etc.
 */
static int
make_dirs(char *path, int file_perms)
{
    char *Path;
    char *start;
    char *sep;
    int ret = 0;
    PRFileInfo info;

    if (!path) {
        return 0;
    }

    Path = PR_Strdup(path);
    start = strpbrk(Path, "/\\");
    if (!start) {
        return 0;
    }
    start++; /* start right after first slash */

    /* Each time through the loop add one more directory. */
    while ((sep = strpbrk(start, "/\\"))) {
        *sep = '\0';

        if (PR_GetFileInfo(Path, &info) != PR_SUCCESS) {
            /* No such dir, we have to create it */
            if (PR_MkDir(Path, dir_perms(file_perms)) != PR_SUCCESS) {
                error(PK11_INSTALL_CREATE_DIR, Path);
                ret = PK11_INSTALL_CREATE_DIR;
                goto loser;
            }
        } else {
            /* something exists by this name, make sure it's a directory */
            if (info.type != PR_FILE_DIRECTORY) {
                error(PK11_INSTALL_CREATE_DIR, Path);
                ret = PK11_INSTALL_CREATE_DIR;
                goto loser;
            }
        }

        /* If this is the lowest directory level, make sure it is writeable */
        if (!strpbrk(sep + 1, "/\\")) {
            if (PR_Access(Path, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
                error(PK11_INSTALL_DIR_NOT_WRITEABLE, Path);
                ret = PK11_INSTALL_DIR_NOT_WRITEABLE;
                goto loser;
            }
        }

        start = sep + 1; /* start after the next slash */
        *sep = '/';
    }

loser:
    PR_Free(Path);
    return ret;
}
std::string
CommandEventHandler::dirw(std::vector<std::string>& args)
{
  std::string path(args.size() ? args[0] : "");
  std::string ret = isDir(path);
  if (ret.compare("TRUE") != 0)
  {
    if (ret.compare("FALSE") == 0)
      return agentWarn("path is not a dir");
    return ret;
  }
  if (PR_Access(path.c_str(), PR_ACCESS_WRITE_OK) == PR_SUCCESS)
    return std::string(path + " is writable");
  return std::string(path + " is not writable");
}
Exemple #4
0
int32
CallPRWriteAccessFileUsingFileURL(char *fileURL)
{
	int32 result = -1;
	const char *path;
	char *escapedPath = unescapeURL(fileURL);
	path = convertFileURLToNSPRCopaceticPath(escapedPath);

	if (path != NULL)	{
		result = PR_Access(path, PR_ACCESS_WRITE_OK);
	}

	if (escapedPath != NULL)	freeMem(escapedPath);

	return result;
}
std::string
CommandEventHandler::hash(std::vector<std::string>& args)
{
  if (args.size() < 1)
    return agentWarnInvalidNumArgs(1);
  std::string path = args[0];

  if (PR_Access(path.c_str(), PR_ACCESS_READ_OK) != PR_SUCCESS)
  {
    std::ostringstream err;
    err << "Couldn't calculate hash for file " << path << ": cannot open file for reading";
    return agentWarn(err.str());
  }

  return fileHash(path);
}
Exemple #6
0
/*********************************************************************
 *
 * m a i n
 */
int
main(int argc, char *argv[])
{
    PRBool readOnly;
    int retval = 0;

    outputFD = PR_STDOUT;
    errorFD = PR_STDERR;

    progName = argv[0];

    if (argc < 2) {
        Usage();
    }

    excludeDirs = PL_NewHashTable(10, PL_HashString, PL_CompareStrings,
                                  PL_CompareStrings, NULL, NULL);
    extensions = PL_NewHashTable(10, PL_HashString, PL_CompareStrings,
                                 PL_CompareStrings, NULL, NULL);

    if (parse_args(argc, argv)) {
        retval = -1;
        goto cleanup;
    }

    /* Parse the command file if one was given */
    if (cmdFile) {
        if (ProcessCommandFile()) {
            retval = -1;
            goto cleanup;
        }
    }

    /* Set up output redirection */
    if (outfile) {
        if (PR_Access(outfile, PR_ACCESS_EXISTS) == PR_SUCCESS) {
            /* delete the file if it is already present */
            PR_fprintf(errorFD,
                       "warning: %s already exists and will be overwritten.\n",
                       outfile);
            warningCount++;
            if (PR_Delete(outfile) != PR_SUCCESS) {
                PR_fprintf(errorFD, "ERROR: unable to delete %s.\n", outfile);
                errorCount++;
                exit(ERRX);
            }
        }
        outputFD = PR_Open(outfile,
                           PR_WRONLY |
                               PR_CREATE_FILE | PR_TRUNCATE,
                           0777);
        if (!outputFD) {
            PR_fprintf(errorFD, "ERROR: Unable to create %s.\n",
                       outfile);
            errorCount++;
            exit(ERRX);
        }
        errorFD = outputFD;
    }

    /* This seems to be a fairly common user error */

    if (verify && list_certs > 0) {
        PR_fprintf(errorFD, "%s: Can't use -l and -v at the same time\n",
                   PROGRAM_NAME);
        errorCount++;
        retval = -1;
        goto cleanup;
    }

    /* -J assumes -Z now */

    if (javascript && zipfile) {
        PR_fprintf(errorFD, "%s: Can't use -J and -Z at the same time\n",
                   PROGRAM_NAME);
        PR_fprintf(errorFD, "%s: -J option will create the jar files for you\n",
                   PROGRAM_NAME);
        errorCount++;
        retval = -1;
        goto cleanup;
    }

    /* -X needs -Z */

    if (xpi_arc && !zipfile) {
        PR_fprintf(errorFD, "%s: option XPI (-X) requires option jarfile (-Z)\n",
                   PROGRAM_NAME);
        errorCount++;
        retval = -1;
        goto cleanup;
    }

    /* Less common mixing of -L with various options */

    if (list_certs > 0 &&
        (tell_who || zipfile || javascript ||
         scriptdir || extensionsGiven || exclusionsGiven || install_script)) {
        PR_fprintf(errorFD, "%s: Can't use -l or -L with that option\n",
                   PROGRAM_NAME);
        errorCount++;
        retval = -1;
        goto cleanup;
    }

    if (!cert_dir)
        cert_dir = get_default_cert_dir();

    VerifyCertDir(cert_dir, keyName);

    if (compression_level < MIN_COMPRESSION_LEVEL ||
        compression_level > MAX_COMPRESSION_LEVEL) {
        PR_fprintf(errorFD, "Compression level must be between %d and %d.\n",
                   MIN_COMPRESSION_LEVEL, MAX_COMPRESSION_LEVEL);
        errorCount++;
        retval = -1;
        goto cleanup;
    }

    if (jartree && !keyName) {
        PR_fprintf(errorFD, "You must specify a key with which to sign.\n");
        errorCount++;
        retval = -1;
        goto cleanup;
    }

    readOnly = (genkey == NULL); /* only key generation requires write */
    if (InitCrypto(cert_dir, readOnly)) {
        PR_fprintf(errorFD, "ERROR: Cryptographic initialization failed.\n");
        errorCount++;
        retval = -1;
        goto cleanup;
    }

    if (enableOCSP) {
        SECStatus rv = CERT_EnableOCSPChecking(CERT_GetDefaultCertDB());
        if (rv != SECSuccess) {
            PR_fprintf(errorFD, "ERROR: Attempt to enable OCSP Checking failed.\n");
            errorCount++;
            retval = -1;
        }
    }

    if (verify) {
        if (VerifyJar(verify)) {
            errorCount++;
            retval = -1;
            goto cleanup;
        }
    } else if (list_certs) {
        if (ListCerts(keyName, list_certs)) {
            errorCount++;
            retval = -1;
            goto cleanup;
        }
    } else if (list_modules) {
        JarListModules();
    } else if (genkey) {
        if (GenerateCert(genkey, keySize, token)) {
            errorCount++;
            retval = -1;
            goto cleanup;
        }
    } else if (tell_who) {
        if (JarWho(tell_who)) {
            errorCount++;
            retval = -1;
            goto cleanup;
        }
    } else if (javascript && jartree) {
        /* make sure directory exists */
        PRDir *dir;
        dir = PR_OpenDir(jartree);
        if (!dir) {
            PR_fprintf(errorFD, "ERROR: unable to open directory %s.\n",
                       jartree);
            errorCount++;
            retval = -1;
            goto cleanup;
        } else {
            PR_CloseDir(dir);
        }

        /* undo junk from prior runs of signtool*/
        if (RemoveAllArc(jartree)) {
            PR_fprintf(errorFD, "Error removing archive directories under %s\n",
                       jartree);
            errorCount++;
            retval = -1;
            goto cleanup;
        }

        /* traverse all the htm|html files in the directory */
        if (InlineJavaScript(jartree, !noRecurse)) {
            retval = -1;
            goto cleanup;
        }

        /* sign any resultant .arc directories created in above step */
        if (SignAllArc(jartree, keyName, javascript, metafile, install_script,
                       optimize, !noRecurse)) {
            retval = -1;
            goto cleanup;
        }

        if (!leaveArc) {
            RemoveAllArc(jartree);
        }

        if (errorCount > 0 || warningCount > 0) {
            PR_fprintf(outputFD, "%d error%s, %d warning%s.\n",
                       errorCount,
                       errorCount == 1 ? "" : "s", warningCount, warningCount == 1 ? "" : "s");
        } else {
            PR_fprintf(outputFD, "Directory %s signed successfully.\n",
                       jartree);
        }
    } else if (jartree) {
        SignArchive(jartree, keyName, zipfile, javascript, metafile,
                    install_script, optimize, !noRecurse);
    } else
        Usage();

cleanup:
    if (extensions) {
        PL_HashTableDestroy(extensions);
        extensions = NULL;
    }
    if (excludeDirs) {
        PL_HashTableDestroy(excludeDirs);
        excludeDirs = NULL;
    }
    if (outputFD != PR_STDOUT) {
        PR_Close(outputFD);
    }
    rm_dash_r(TMP_OUTPUT);
    if (retval == 0) {
        if (NSS_Shutdown() != SECSuccess) {
            exit(1);
        }
    }
    return retval;
}
Exemple #7
0
bool Log::setAuditLogFile(const std::string& name,
     bool localAuditLogRotate,
     long localAuditFileSize)
throw () {
    bool okay = true;
    std::string newName;
    FILE *newAuditLogFile = NULL;
    int retValue = 0;

    if (name.size() > 0) {
        if (localAuditLogRotate) {
            char hdr[100];
            PRUint32 len;
            int counter = 1;
            bool fileExists = true;

            if (auditLogFile == stderr) {
                // Open the log file for the first time
                newAuditLogFile = std::fopen(name.c_str(), "a");
                if (newAuditLogFile != NULL) {
                    auditLogFile = newAuditLogFile;
                } else {
                    okay = false;
                }
            } else {
                // Start the process of log rotation
                while (fileExists) {
                    len = PR_snprintf(hdr, sizeof (hdr), "%d", counter);
                    if (len > 0) {
                        std::string appendString(hdr);
                        newName = name + "-" + appendString;
                    }
                    if ((PR_Access(newName.c_str(), PR_ACCESS_EXISTS)) == 
                            PR_SUCCESS) {
                        counter++;
                    } else {
                        fileExists = false;
                    }
                }
                std::fflush(auditLogFile);
                std::fclose(auditLogFile);
                retValue = rename(name.c_str(), newName.c_str());
                if (retValue != -1) {
                    newAuditLogFile = std::fopen(name.c_str(), "a");
                    if (newAuditLogFile != NULL) {
                        auditLogFile = newAuditLogFile;
                        currentAuditLogFileSize = 0;
                    } else {
                        auditLogFile = stderr;
                    }
                } else {
                    auditLogFile = stderr;
                }
            }
        } else {
            // localAuditLogRotate is false, just create one log file and write to it
            newAuditLogFile = std::fopen(name.c_str(), "a");
            if (newAuditLogFile != NULL) {
                auditLogFile = newAuditLogFile;
            } else {
                okay = false;
            }
        }
    } else {
        okay = false;
    }

    return okay;
}
Exemple #8
0
/*
/////////////////////////////////////////////////////////////////////////
// actually run the installation, copying files to and fro
*/
static Pk11Install_Error
DoInstall(JAR *jar, const char *installDir, const char *tempDir,
          Pk11Install_Platform *platform, PRFileDesc *feedback, PRBool noverify)
{
    Pk11Install_File *file;
    Pk11Install_Error ret;
    char *reldir;
    char *dest;
    char *modDest;
    char *cp;
    int i;
    int status;
    char *tempname, *temp;
    StringList executables;
    StringNode *execNode;
    PRProcessAttr *attr;
    PRProcess *proc;
    char *argv[2];
    char *envp[1];
    int errcode;

    ret = PK11_INSTALL_UNSPECIFIED;
    reldir = NULL;
    dest = NULL;
    modDest = NULL;
    tempname = NULL;

    StringList_new(&executables);
    /*
    // Create Temporary directory
    */
    tempname = PR_smprintf("%s/%s", tempDir, TEMPORARY_DIRECTORY_NAME);
    if (PR_Access(tempname, PR_ACCESS_EXISTS) == PR_SUCCESS) {
        /* Left over from previous run?  Delete it. */
        rm_dash_r(tempname);
    }
    if (PR_MkDir(tempname, 0700) != PR_SUCCESS) {
        error(PK11_INSTALL_CREATE_DIR, tempname);
        ret = PK11_INSTALL_CREATE_DIR;
        goto loser;
    }

    /*
    // Install all the files
    */
    for (i = 0; i < platform->numFiles; i++) {
        file = &platform->files[i];

        if (file->relativePath) {
            PRBool foundMarker = PR_FALSE;
            reldir = PR_Strdup(file->relativePath);

            /* Replace all the markers with the directories for which they stand */
            while (1) {
                if ((cp = PL_strcasestr(reldir, ROOT_MARKER))) {
                    /* Has a %root% marker  */
                    *cp = '\0';
                    temp = PR_smprintf("%s%s%s", reldir, installDir,
                                       cp + strlen(ROOT_MARKER));
                    PR_Free(reldir);
                    reldir = temp;
                    foundMarker = PR_TRUE;
                } else if ((cp = PL_strcasestr(reldir, TEMP_MARKER))) {
                    /* Has a %temp% marker */
                    *cp = '\0';
                    temp = PR_smprintf("%s%s%s", reldir, tempname,
                                       cp + strlen(TEMP_MARKER));
                    PR_Free(reldir);
                    reldir = temp;
                    foundMarker = PR_TRUE;
                } else {
                    break;
                }
            }
            if (!foundMarker) {
                /* Has no markers...this isn't really a relative directory */
                error(PK11_INSTALL_BOGUS_REL_DIR, file->relativePath);
                ret = PK11_INSTALL_BOGUS_REL_DIR;
                goto loser;
            }
            dest = reldir;
            reldir = NULL;
        } else if (file->absolutePath) {
            dest = PR_Strdup(file->absolutePath);
        }

        /* Remember if this is the module file, we'll need to add it later */
        if (i == platform->modFile) {
            modDest = PR_Strdup(dest);
        }

        /* Remember is this is an executable, we'll need to run it later */
        if (file->executable) {
            StringList_Append(&executables, dest);
            /*executables.Append(dest);*/
        }

        /* Make sure the directory we are targetting exists */
        if (make_dirs(dest, file->permissions)) {
            ret = PK11_INSTALL_CREATE_DIR;
            goto loser;
        }

        /* Actually extract the file onto the filesystem */
        if (noverify) {
            status = JAR_extract(jar, (char *)file->jarPath, dest);
        } else {
            status = JAR_verified_extract(jar, (char *)file->jarPath, dest);
        }
        if (status) {
            if (status >= JAR_BASE && status <= JAR_BASE_END) {
                error(PK11_INSTALL_JAR_EXTRACT, file->jarPath,
                      JAR_get_error(status));
            } else {
                error(PK11_INSTALL_JAR_EXTRACT, file->jarPath,
                      mySECU_ErrorString(PORT_GetError()));
            }
            ret = PK11_INSTALL_JAR_EXTRACT;
            goto loser;
        }
        if (feedback) {
            PR_fprintf(feedback, msgStrings[INSTALLED_FILE_MSG],
                       file->jarPath, dest);
        }

/* no NSPR command to change permissions? */
#ifdef XP_UNIX
        chmod(dest, file->permissions);
#endif

        /* Memory clean-up tasks */
        if (reldir) {
            PR_Free(reldir);
            reldir = NULL;
        }
        if (dest) {
            PR_Free(dest);
            dest = NULL;
        }
    }
    /* Make sure we found the module file */
    if (!modDest) {
        /* Internal problem here, since every platform is supposed to have
           a module file */
        error(PK11_INSTALL_NO_MOD_FILE, platform->moduleName);
        ret = PK11_INSTALL_NO_MOD_FILE;
        goto loser;
    }

    /*
    // Execute any executable files
    */
    {
        argv[1] = NULL;
        envp[0] = NULL;
        for (execNode = executables.head; execNode; execNode = execNode->next) {
            attr = PR_NewProcessAttr();
            argv[0] = PR_Strdup(execNode->str);

            /* Announce our intentions */
            if (feedback) {
                PR_fprintf(feedback, msgStrings[EXEC_FILE_MSG], execNode->str);
            }

            /* start the process */
            if (!(proc = PR_CreateProcess(execNode->str, argv, envp, attr))) {
                PR_Free(argv[0]);
                PR_DestroyProcessAttr(attr);
                error(PK11_INSTALL_EXEC_FILE, execNode->str);
                ret = PK11_INSTALL_EXEC_FILE;
                goto loser;
            }

            /* wait for it to finish */
            if (PR_WaitProcess(proc, &errcode) != PR_SUCCESS) {
                PR_Free(argv[0]);
                PR_DestroyProcessAttr(attr);
                error(PK11_INSTALL_WAIT_PROCESS, execNode->str);
                ret = PK11_INSTALL_WAIT_PROCESS;
                goto loser;
            }

            /* What happened? */
            if (errcode) {
                /* process returned an error */
                error(PK11_INSTALL_PROC_ERROR, execNode->str, errcode);
            } else if (feedback) {
                /* process ran successfully */
                PR_fprintf(feedback, msgStrings[EXEC_SUCCESS], execNode->str);
            }

            PR_Free(argv[0]);
            PR_DestroyProcessAttr(attr);
        }
    }

    /*
    // Add the module
    */
    status = Pk11Install_AddNewModule((char *)platform->moduleName,
                                      (char *)modDest, platform->mechFlags, platform->cipherFlags);

    if (status != SECSuccess) {
        error(PK11_INSTALL_ADD_MODULE, platform->moduleName);
        ret = PK11_INSTALL_ADD_MODULE;
        goto loser;
    }
    if (feedback) {
        PR_fprintf(feedback, msgStrings[INSTALLED_MODULE_MSG],
                   platform->moduleName);
    }

    if (feedback) {
        PR_fprintf(feedback, msgStrings[INSTALLATION_COMPLETE_MSG]);
    }

    ret = PK11_INSTALL_SUCCESS;

loser:
    if (reldir) {
        PR_Free(reldir);
    }
    if (dest) {
        PR_Free(dest);
    }
    if (modDest) {
        PR_Free(modDest);
    }
    if (tempname) {
        PRFileInfo info;
        if (PR_GetFileInfo(tempname, &info) == PR_SUCCESS) {
            if (info.type == PR_FILE_DIRECTORY) {
                /* Recursively remove temporary directory */
                if (rm_dash_r(tempname)) {
                    error(PK11_INSTALL_REMOVE_DIR,
                          tempname);
                    ret = PK11_INSTALL_REMOVE_DIR;
                }
            }
        }
        PR_Free(tempname);
    }
    StringList_delete(&executables);
    return ret;
}
Exemple #9
0
/*************************************************************************
 *
 * P k 1 1 I n s t a l l _ D o I n s t a l l
 *
 * jarFile is the path of a JAR in the PKCS #11 module JAR format.
 * installDir is the directory relative to which files will be
 *   installed.
 */
Pk11Install_Error
Pk11Install_DoInstall(char *jarFile, const char *installDir,
                      const char *tempDir, PRFileDesc *feedback, short force, PRBool noverify)
{
    JAR *jar;
    char *installer;
    unsigned long installer_len;
    int status;
    Pk11Install_Error ret;
    PRBool made_temp_file;
    Pk11Install_Info installInfo;
    Pk11Install_Platform *platform;
    char *errMsg;
    char sysname[SYS_INFO_BUFFER_LENGTH], release[SYS_INFO_BUFFER_LENGTH],
        arch[SYS_INFO_BUFFER_LENGTH];
    char *myPlatform;

    jar = NULL;
    ret = PK11_INSTALL_UNSPECIFIED;
    made_temp_file = PR_FALSE;
    errMsg = NULL;
    Pk11Install_Info_init(&installInfo);

    /*
    printf("Inside DoInstall, jarFile=%s, installDir=%s, tempDir=%s\n",
        jarFile, installDir, tempDir);
    */

    /*
     * Check out jarFile and installDir for validity
     */
    if (PR_Access(installDir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
        error(PK11_INSTALL_DIR_DOESNT_EXIST, installDir);
        return PK11_INSTALL_DIR_DOESNT_EXIST;
    }
    if (!tempDir) {
        tempDir = ".";
    }
    if (PR_Access(tempDir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
        error(PK11_INSTALL_DIR_DOESNT_EXIST, tempDir);
        return PK11_INSTALL_DIR_DOESNT_EXIST;
    }
    if (PR_Access(tempDir, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
        error(PK11_INSTALL_DIR_NOT_WRITEABLE, tempDir);
        return PK11_INSTALL_DIR_NOT_WRITEABLE;
    }
    if ((PR_Access(jarFile, PR_ACCESS_EXISTS) != PR_SUCCESS)) {
        error(PK11_INSTALL_FILE_DOESNT_EXIST, jarFile);
        return PK11_INSTALL_FILE_DOESNT_EXIST;
    }
    if (PR_Access(jarFile, PR_ACCESS_READ_OK) != PR_SUCCESS) {
        error(PK11_INSTALL_FILE_NOT_READABLE, jarFile);
        return PK11_INSTALL_FILE_NOT_READABLE;
    }

    /*
     * Extract the JAR file
     */
    jar = JAR_new();
    JAR_set_callback(JAR_CB_SIGNAL, jar, jar_callback);

    if (noverify) {
        status = JAR_pass_archive_unverified(jar, jarArchGuess, jarFile, "url");
    } else {
        status = JAR_pass_archive(jar, jarArchGuess, jarFile, "url");
    }
    if ((status < 0) || (jar->valid < 0)) {
        if (status >= JAR_BASE && status <= JAR_BASE_END) {
            error(PK11_INSTALL_JAR_ERROR, jarFile, JAR_get_error(status));
        } else {
            error(PK11_INSTALL_JAR_ERROR, jarFile,
                  mySECU_ErrorString(PORT_GetError()));
        }
        ret = PK11_INSTALL_JAR_ERROR;
        goto loser;
    }
    /*printf("passed the archive\n");*/

    /*
     * Show the user security information, allow them to abort or continue
     */
    if (Pk11Install_UserVerifyJar(jar, PR_STDOUT,
                                  force ?
                                        PR_FALSE
                                        :
                                        PR_TRUE) &&
        !force) {
        if (feedback) {
            PR_fprintf(feedback, msgStrings[USER_ABORT]);
        }
        ret = PK11_INSTALL_USER_ABORT;
        goto loser;
    }

    /*
     * Get the name of the installation file
     */
    if (JAR_get_metainfo(jar, NULL, INSTALL_METAINFO_TAG, (void **)&installer,
                         (unsigned long *)&installer_len)) {
        error(PK11_INSTALL_NO_INSTALLER_SCRIPT);
        ret = PK11_INSTALL_NO_INSTALLER_SCRIPT;
        goto loser;
    }
    if (feedback) {
        PR_fprintf(feedback, msgStrings[INSTALLER_SCRIPT_NAME], installer);
    }

    /*
     * Extract the installation file
     */
    if (PR_Access(SCRIPT_TEMP_FILE, PR_ACCESS_EXISTS) == PR_SUCCESS) {
        if (PR_Delete(SCRIPT_TEMP_FILE) != PR_SUCCESS) {
            error(PK11_INSTALL_DELETE_TEMP_FILE, SCRIPT_TEMP_FILE);
            ret = PK11_INSTALL_DELETE_TEMP_FILE;
            goto loser;
        }
    }
    if (noverify) {
        status = JAR_extract(jar, installer, SCRIPT_TEMP_FILE);
    } else {
        status = JAR_verified_extract(jar, installer, SCRIPT_TEMP_FILE);
    }
    if (status) {
        if (status >= JAR_BASE && status <= JAR_BASE_END) {
            error(PK11_INSTALL_JAR_EXTRACT, installer, JAR_get_error(status));
        } else {
            error(PK11_INSTALL_JAR_EXTRACT, installer,
                  mySECU_ErrorString(PORT_GetError()));
        }
        ret = PK11_INSTALL_JAR_EXTRACT;
        goto loser;
    } else {
        made_temp_file = PR_TRUE;
    }

    /*
     * Parse the installation file into a syntax tree
     */
    Pk11Install_FD = PR_Open(SCRIPT_TEMP_FILE, PR_RDONLY, 0);
    if (!Pk11Install_FD) {
        error(PK11_INSTALL_OPEN_SCRIPT_FILE, SCRIPT_TEMP_FILE);
        ret = PK11_INSTALL_OPEN_SCRIPT_FILE;
        goto loser;
    }
    if (Pk11Install_yyparse()) {
        error(PK11_INSTALL_SCRIPT_PARSE, installer,
              Pk11Install_yyerrstr ? Pk11Install_yyerrstr : "");
        ret = PK11_INSTALL_SCRIPT_PARSE;
        goto loser;
    }

#if 0
    /* for debugging */
    Pk11Install_valueList->Print(0);
#endif

    /*
     * From the syntax tree, build a semantic structure
     */
    errMsg = Pk11Install_Info_Generate(&installInfo, Pk11Install_valueList);
    if (errMsg) {
        error(PK11_INSTALL_SEMANTIC, errMsg);
        ret = PK11_INSTALL_SEMANTIC;
        goto loser;
    }
#if 0
    installInfo.Print(0);
#endif

    if (feedback) {
        PR_fprintf(feedback, msgStrings[PARSED_INSTALL_SCRIPT]);
    }

    /*
     * Figure out which platform to use
     */
    {
        sysname[0] = release[0] = arch[0] = '\0';

        if ((PR_GetSystemInfo(PR_SI_SYSNAME, sysname, SYS_INFO_BUFFER_LENGTH) !=
             PR_SUCCESS) ||
            (PR_GetSystemInfo(PR_SI_RELEASE, release, SYS_INFO_BUFFER_LENGTH) !=
             PR_SUCCESS) ||
            (PR_GetSystemInfo(PR_SI_ARCHITECTURE, arch, SYS_INFO_BUFFER_LENGTH) !=
             PR_SUCCESS)) {
            error(PK11_INSTALL_SYSINFO);
            ret = PK11_INSTALL_SYSINFO;
            goto loser;
        }
        myPlatform = PR_smprintf("%s:%s:%s", sysname, release, arch);
        platform = Pk11Install_Info_GetBestPlatform(&installInfo, myPlatform);
        if (!platform) {
            error(PK11_INSTALL_NO_PLATFORM, myPlatform);
            PR_smprintf_free(myPlatform);
            ret = PK11_INSTALL_NO_PLATFORM;
            goto loser;
        }
        if (feedback) {
            PR_fprintf(feedback, msgStrings[MY_PLATFORM_IS], myPlatform);
            PR_fprintf(feedback, msgStrings[USING_PLATFORM],
                       Pk11Install_PlatformName_GetString(&platform->name));
        }
        PR_smprintf_free(myPlatform);
    }

    /* Run the install for that platform */
    ret = DoInstall(jar, installDir, tempDir, platform, feedback, noverify);
    if (ret) {
        goto loser;
    }

    ret = PK11_INSTALL_SUCCESS;
loser:
    if (Pk11Install_valueList) {
        Pk11Install_ValueList_delete(Pk11Install_valueList);
        PR_Free(Pk11Install_valueList);
        Pk11Install_valueList = NULL;
    }
    if (jar) {
        JAR_destroy(jar);
    }
    if (made_temp_file) {
        PR_Delete(SCRIPT_TEMP_FILE);
    }
    if (errMsg) {
        PR_smprintf_free(errMsg);
    }
    return ret;
}
Exemple #10
0
/**
 * Commits changes to the config file
 */
TPS_PUBLIC int ConfigStore::Commit(const bool backup, char *error_msg, int len)
{
    char name_tmp[256], cdate[256], name_bak[256], bak_dir[256];
    char basename[256], dirname[256];
    PRFileDesc *ftmp  = NULL;
    PRExplodedTime time;
    PRTime now;
    PRStatus status;

    if (m_cfg_file_path == NULL) {
        PR_snprintf(error_msg, len, "ConfigStore::Commit(): m_cfg_file_path is NULL!");
        return 1;
    }

    if (strrchr(m_cfg_file_path, '/') != NULL) {
        PR_snprintf((char *) basename, 256, "%s", strrchr(m_cfg_file_path, '/') +1);
        PR_snprintf((char *) dirname, PL_strlen(m_cfg_file_path) - PL_strlen(basename), "%s", m_cfg_file_path);
        PL_strcat(dirname, '\0');
    } else {
        PR_snprintf((char *) basename, 256, "%s", m_cfg_file_path);
        PR_snprintf((char *) dirname, 256, ".");
    }
    PR_snprintf(bak_dir, 256, "%s/bak", dirname); 

    now = PR_Now();
    PR_ExplodeTime(now, PR_LocalTimeParameters, &time);
    PR_snprintf(cdate, 16, "%04d%02d%02d%02d%02d%02dZ",
        time.tm_year, (time.tm_month + 1), time.tm_mday,
        time.tm_hour, time.tm_min, time.tm_sec);
    PR_snprintf(name_tmp, 256, "%s.%s.tmp", m_cfg_file_path,cdate);
    PR_snprintf(name_bak, 256, "%s/%s.%s", bak_dir, basename, cdate);

    ftmp = PR_Open(name_tmp, PR_WRONLY| PR_CREATE_FILE, 00400|00200);
    if (ftmp == NULL) {
        // unable to create temporary config file 
        PR_snprintf(error_msg, len, "ConfigStore::Commit(): unable to create temporary config file");
        return 1;
    }

    PRCList order_list;
    PR_INIT_CLIST(&order_list);

    PR_Lock(m_lock);
    PL_HashTableEnumerateEntries(m_root->getSet(), &OrderLoop, &order_list);
    PR_Unlock(m_lock);

    PRCList *current = PR_LIST_HEAD(&order_list);
    PRCList *next;

    while (current != &order_list) {
        OrderedEntry_t *entry = (OrderedEntry_t *) current;
        PR_Write(ftmp, entry->key, PL_strlen(entry->key));
        PR_Write(ftmp, "=", 1);
        const char *value = GetConfigAsString(entry->key, "");
        PR_Write(ftmp, value, PL_strlen(value));
        PR_Write(ftmp, "\n", 1);

        // free the memory for the Ordered Entry
        if (entry->key != NULL)  PL_strfree(entry->key);

        next = PR_NEXT_LINK(current);
        PR_REMOVE_AND_INIT_LINK(current);
        if (current != NULL) {
            PR_Free(current);
        }
        current = next;
    }

    PR_Close(ftmp);

    if (backup) { 
        // create the backup directory if it does not exist
        if (PR_Access(bak_dir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
            PR_MkDir(bak_dir, 00770);
        } 
        status = PR_Rename(m_cfg_file_path, name_bak);
        if (status != PR_SUCCESS) {
            // failed to back up CS.cfg
        }
    } 
    if (PR_Access(m_cfg_file_path, PR_ACCESS_EXISTS) == PR_SUCCESS) {
        // backup is false, or backup failed
        status = PR_Delete(m_cfg_file_path);
        if (status != PR_SUCCESS) {
            // failed to delete old CS.cfg file
            PR_snprintf(error_msg, len, "ConfigStore::Commit(): unable to delete old CS.cfg file");
            return 1;
        }
    }

    status = PR_Rename(name_tmp, m_cfg_file_path);
    if (status != PR_SUCCESS) {
        // failed to move tmp to CS.cfg 
        // major badness - we now have only tmp file, no CS.cfg
        PR_snprintf(error_msg, len, "ConfigStore::Commit(): failed to move tmp file to CS.cfg");
        return 1;
    }

    return 0;
}
Exemple #11
0
/********************************************************************
 *
 * i n i t _ c r y p t o
 *
 * Does crypto initialization that all commands will require.
 * If -nocertdb option is specified, don't open key or cert db (we don't
 * need them if we aren't going to be verifying signatures).  This is
 * because serverland doesn't always have cert and key database files
 * available.
 *
 * This function is ill advised. Names and locations of databases are
 * private to NSS proper. Such functions only confuse other users.
 *
 */
static Error
check_crypto(PRBool create, PRBool readOnly)
{
    char* dir;
    char* moddbname = NULL;
    Error retval;
    static const char multiaccess[] = { "multiaccess:" };

    dir = SECU_ConfigDirectory(dbdir); /* dir is never NULL */
    if (dir[0] == '\0') {
        PR_fprintf(PR_STDERR, errStrings[NO_DBDIR_ERR]);
        retval = NO_DBDIR_ERR;
        goto loser;
    }
    if (strncmp(dir, multiaccess, sizeof multiaccess - 1) == 0) {
        /* won't attempt to handle the multiaccess case. */
        return SUCCESS;
    }
#ifdef notdef
    /* Make sure db directory exists and is readable */
    if (PR_Access(dir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_DOESNT_EXIST_ERR], dir);
        retval = DIR_DOESNT_EXIST_ERR;
        goto loser;
    } else if (PR_Access(dir, PR_ACCESS_READ_OK) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_NOT_READABLE_ERR], dir);
        retval = DIR_NOT_READABLE_ERR;
        goto loser;
    }

    if (secmodName == NULL) {
        secmodName = "secmod.db";
    }

    moddbname = PR_smprintf("%s/%s", dir, secmodName);
    if (!moddbname)
        return OUT_OF_MEM_ERR;

    /* Check for the proper permissions on databases */
    if (create) {
        /* Make sure dbs don't already exist, and the directory is
            writeable */
        if (PR_Access(moddbname, PR_ACCESS_EXISTS) == PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[FILE_ALREADY_EXISTS_ERR],
                       moddbname);
            retval = FILE_ALREADY_EXISTS_ERR;
            goto loser;
        } else if (PR_Access(dir, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[DIR_NOT_WRITEABLE_ERR], dir);
            retval = DIR_NOT_WRITEABLE_ERR;
            goto loser;
        }
    } else {
        /* Make sure dbs are readable and writeable */
        if (PR_Access(moddbname, PR_ACCESS_READ_OK) != PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[FILE_NOT_READABLE_ERR], moddbname);
            retval = FILE_NOT_READABLE_ERR;
            goto loser;
        }

        /* Check for write access if we'll be making changes */
        if (!readOnly) {
            if (PR_Access(moddbname, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
                PR_fprintf(PR_STDERR, errStrings[FILE_NOT_WRITEABLE_ERR],
                           moddbname);
                retval = FILE_NOT_WRITEABLE_ERR;
                goto loser;
            }
        }
        PR_fprintf(PR_STDOUT, msgStrings[USING_DBDIR_MSG],
                   SECU_ConfigDirectory(NULL));
    }
#endif
    retval = SUCCESS;
loser:
    if (moddbname) {
        PR_Free(moddbname);
    }
    return retval;
}
Exemple #12
0
/*
 *  m a n i f e s t o
 *
 *  Run once for every subdirectory in which a 
 *  manifest is to be created -- usually exactly once.
 *
 */
static int	
manifesto (char *dirname, char *install_script, PRBool recurse)
{
    char	metadir [FNSIZE], sfname [FNSIZE];

    /* Create the META-INF directory to hold signing info */

    if (PR_Access (dirname, PR_ACCESS_READ_OK)) {
	PR_fprintf(errorFD, "%s: unable to read your directory: %s\n",
	     PROGRAM_NAME, dirname);
	errorCount++;
	perror (dirname);
	exit (ERRX);
    }

    if (PR_Access (dirname, PR_ACCESS_WRITE_OK)) {
	PR_fprintf(errorFD, "%s: unable to write to your directory: %s\n",
	     			PROGRAM_NAME, dirname);
	errorCount++;
	perror(dirname);
	exit(ERRX);
    }

    sprintf (metadir, "%s/META-INF", dirname);

    strcpy (sfname, metadir);

    PR_MkDir (metadir, 0777);

    strcat (metadir, "/");
    strcat (metadir, MANIFEST);

    if ((mf = fopen (metadir, "wb")) == NULL) {
	perror (MANIFEST);
	PR_fprintf(errorFD, "%s: Probably, the directory you are trying to"
			    " sign has\n", PROGRAM_NAME);
	PR_fprintf(errorFD, "%s: permissions problems or may not exist.\n",
	     		PROGRAM_NAME);
	errorCount++;
	exit (ERRX);
    }

    if (verbosity >= 0) {
	PR_fprintf(outputFD, "Generating %s file..\n", metadir);
    }

    fprintf(mf, "Manifest-Version: 1.0\n");
    fprintf (mf, "Created-By: %s\n", CREATOR);
    fprintf (mf, "Comments: %s\n", BREAKAGE);

    if (scriptdir) {
	fprintf (mf, "Comments: --\n");
	fprintf (mf, "Comments: --\n");
	fprintf (mf, "Comments: -- This archive signs Javascripts which may not necessarily\n");
	fprintf (mf, "Comments: -- be included in the physical jar file.\n");
	fprintf (mf, "Comments: --\n");
	fprintf (mf, "Comments: --\n");
    }

    if (install_script)
	fprintf (mf, "Install-Script: %s\n", install_script);

    if (metafile)
	add_meta (mf, "+");

    /* Loop through all files & subdirectories */
    foreach (dirname, "", manifesto_fn, recurse, PR_FALSE /*include dirs */,
         		(void * )NULL);

    fclose (mf);

    strcat (sfname, "/");
    strcat (sfname, base);
    strcat (sfname, ".sf");

    if (verbosity >= 0) {
	PR_fprintf(outputFD, "Generating %s.sf file..\n", base);
    }
    generate_SF_file (metadir, sfname);

    return 0;
}
Exemple #13
0
int
main(int argc, char **argv)
{
    PLOptState *optstate;
    PLOptStatus optstatus;

    PRUint32 flags = 0;
    Error ret;
    SECStatus rv;
    char *dbString = NULL;
    PRBool doInitTest = PR_FALSE;
    int i;

    progName = strrchr(argv[0], '/');
    if (!progName)
        progName = strrchr(argv[0], '\\');
    progName = progName ? progName + 1 : argv[0];

    optstate = PL_CreateOptState(argc, argv, "rfip:d:h");

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
        switch (optstate->option) {
            case 'h':
            default:
                Usage(progName);
                break;

            case 'r':
                flags |= NSS_INIT_READONLY;
                break;

            case 'f':
                flags |= NSS_INIT_FORCEOPEN;
                break;

            case 'i':
                doInitTest = PR_TRUE;
                break;

            case 'p':
                userPassword = PORT_Strdup(optstate->value);
                break;

            case 'd':
                dbDir = PORT_Strdup(optstate->value);
                break;
        }
    }
    if (optstatus == PL_OPT_BAD)
        Usage(progName);

    if (!dbDir) {
        dbDir = SECU_DefaultSSLDir(); /* Look in $SSL_DIR */
    }
    dbDir = SECU_ConfigDirectory(dbDir);
    PR_fprintf(PR_STDERR, "dbdir selected is %s\n\n", dbDir);

    if (dbDir[0] == '\0') {
        PR_fprintf(PR_STDERR, errStrings[DIR_DOESNT_EXIST_ERR], dbDir);
        ret = DIR_DOESNT_EXIST_ERR;
        goto loser;
    }

    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);

    /* get the status of the directory and databases and output message */
    if (PR_Access(dbDir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_DOESNT_EXIST_ERR], dbDir);
    } else if (PR_Access(dbDir, PR_ACCESS_READ_OK) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_NOT_READABLE_ERR], dbDir);
    } else {
        if (!(flags & NSS_INIT_READONLY) &&
            PR_Access(dbDir, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[DIR_NOT_WRITEABLE_ERR], dbDir);
        }
        if (!doInitTest) {
            for (i = 0; i < 3; i++) {
                dbString = PR_smprintf("%s/%s", dbDir, dbName[i]);
                PR_fprintf(PR_STDOUT, "database checked is %s\n", dbString);
                if (PR_Access(dbString, PR_ACCESS_EXISTS) != PR_SUCCESS) {
                    PR_fprintf(PR_STDERR, errStrings[FILE_DOESNT_EXIST_ERR],
                               dbString);
                } else if (PR_Access(dbString, PR_ACCESS_READ_OK) != PR_SUCCESS) {
                    PR_fprintf(PR_STDERR, errStrings[FILE_NOT_READABLE_ERR],
                               dbString);
                } else if (!(flags & NSS_INIT_READONLY) &&
                           PR_Access(dbString, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
                    PR_fprintf(PR_STDERR, errStrings[FILE_NOT_WRITEABLE_ERR],
                               dbString);
                }
            }
        }
    }

    rv = NSS_Initialize(SECU_ConfigDirectory(dbDir), dbprefix, dbprefix,
                        secmodName, flags);
    if (rv != SECSuccess) {
        SECU_PrintPRandOSError(progName);
        ret = NSS_INITIALIZE_FAILED_ERR;
    } else {
        ret = SUCCESS;
        if (doInitTest) {
            PK11SlotInfo *slot = PK11_GetInternalKeySlot();
            SECStatus rv;
            int passwordSuccess = 0;
            int type = CKM_DES3_CBC;
            SECItem keyid = { 0, NULL, 0 };
            unsigned char keyIdData[] = { 0xff, 0xfe };
            PK11SymKey *key = NULL;

            keyid.data = keyIdData;
            keyid.len = sizeof(keyIdData);

            PK11_SetPasswordFunc(getPassword);
            rv = PK11_InitPin(slot, (char *)NULL, userPassword);
            if (rv != SECSuccess) {
                PR_fprintf(PR_STDERR, "Failed to Init DB: %s\n",
                           SECU_Strerror(PORT_GetError()));
                ret = CHANGEPW_FAILED_ERR;
            }
            if (*userPassword && !PK11_IsLoggedIn(slot, &passwordSuccess)) {
                PR_fprintf(PR_STDERR, "New DB did not log in after init\n");
                ret = AUTHENTICATION_FAILED_ERR;
            }
            /* generate a symetric key */
            key = PK11_TokenKeyGen(slot, type, NULL, 0, &keyid,
                                   PR_TRUE, &passwordSuccess);

            if (!key) {
                PR_fprintf(PR_STDERR, "Could not generated symetric key: %s\n",
                           SECU_Strerror(PORT_GetError()));
                exit(UNSPECIFIED_ERR);
            }
            PK11_FreeSymKey(key);
            PK11_Logout(slot);

            PK11_Authenticate(slot, PR_TRUE, &passwordSuccess);

            if (*userPassword && !passwordSuccess) {
                PR_fprintf(PR_STDERR, "New DB Did not initalize\n");
                ret = AUTHENTICATION_FAILED_ERR;
            }
            key = PK11_FindFixedKey(slot, type, &keyid, &passwordSuccess);

            if (!key) {
                PR_fprintf(PR_STDERR, "Could not find generated key: %s\n",
                           SECU_Strerror(PORT_GetError()));
                ret = UNSPECIFIED_ERR;
            } else {
                PK11_FreeSymKey(key);
            }
            PK11_FreeSlot(slot);
        }

        if (NSS_Shutdown() != SECSuccess) {
            PR_fprintf(PR_STDERR, "Could not find generated key: %s\n",
                       SECU_Strerror(PORT_GetError()));
            exit(1);
        }
    }

loser:
    return ret;
}