Esempio n. 1
0
DWORD LWPrintException(FILE *dest, const LWException *print, BOOLEAN showTrace)
{
    DWORD ceError = ERROR_SUCCESS;
    PSTR string = NULL;
    PSTR wrapped = NULL;
    int columns;

    ceError = LWExceptionToString(print, "Error: ", FALSE, showTrace, &string);
    GCE(ceError);
    //Don't word wrap if the terminal width can't be determined
    if (CTGetTerminalWidth(fileno(dest), &columns))
        columns = -1;
    ceError = CTWordWrap(string, &wrapped, 4, columns);
    GCE(ceError);
    fprintf(dest, "%s\n", wrapped);

cleanup:
    if(ceError)
    {
        fprintf(dest, "Error %x occurred while trying to print exception\n", ceError);
    }
    CT_SAFE_FREE_STRING(string);
    CT_SAFE_FREE_STRING(wrapped);
    return ceError;
}
Esempio n. 2
0
DWORD
DJFixLoginConfigFile(
    PCSTR pszPath
    )
{
    DWORD ceError = ERROR_SUCCESS;
    PCSTR pszFilePath = NULL;
    PSTR pszTmpPath = NULL;
    PSTR pszFinalPath = NULL;
    BOOLEAN bFileExists = FALSE;
    FILE* fp = NULL;
    FILE* fp_new = NULL;
    DynamicArray lines;
    PSTR currentSystem = NULL;

    memset(&lines, 0, sizeof(lines));
    if (IsNullOrEmptyString(pszPath))
        pszFilePath = LOGIN_CONFIG_PATH;
    else
        pszFilePath = pszPath;

    GCE(ceError = CTGetFileTempPath(
                        pszFilePath,
                        &pszFinalPath,
                        &pszTmpPath));

    GCE(ceError = CTCheckFileExists(pszFinalPath, &bFileExists));

    if (!bFileExists)
        goto cleanup;

    GCE(ceError = CTOpenFile(pszFinalPath, "r", &fp));
    GCE(ceError = CTReadLines(fp, &lines));
    GCE(ceError = CTSafeCloseFile(&fp));

    GCE(ceError = GetAuthType(&lines, &currentSystem));
    if(!strcmp(currentSystem, "PAM_AUTH"))
        goto cleanup;

    GCE(ceError = SetAuthType(&lines, "PAM_AUTH"));

    GCE(ceError = CTOpenFile(pszTmpPath, "w", &fp_new));
    GCE(ceError = CTWriteLines(fp_new, &lines));
    GCE(ceError = CTSafeCloseFile(&fp_new));

    GCE(ceError = CTSafeReplaceFile(pszFilePath, pszTmpPath));

cleanup:
    CTSafeCloseFile(&fp);
    CTSafeCloseFile(&fp_new);

    CT_SAFE_FREE_STRING(currentSystem);
    CT_SAFE_FREE_STRING(pszTmpPath);
    CT_SAFE_FREE_STRING(pszFinalPath);
    CTFreeLines(&lines);

    return ceError;
}
Esempio n. 3
0
static void FreeNsswitchEntryContents(NsswitchEntry *entry)
{
    size_t i;
    for(i = 0; i < entry->modules.size; i++)
    {
        CTFreeParseTokenContents(GetEntryModule(entry, i));
    }
    CTArrayFree(&entry->modules);
    CT_SAFE_FREE_STRING(entry->leadingWhiteSpace);
    CT_SAFE_FREE_STRING(entry->comment);
    CTFreeParseTokenContents(&entry->name);
}
Esempio n. 4
0
static DWORD WriteNsswitchConfiguration(const char *rootPrefix, NsswitchConf *conf)
{
    DWORD ceError = ERROR_SUCCESS;
    DynamicArray printedLine;
    int i;
    char *tempName = NULL;
    char *finalName = NULL;
    char *prefixedPath = NULL;
    FILE *file = NULL;
    memset(&printedLine, 0, sizeof(printedLine));

    GCE(ceError = CTAllocateStringPrintf(&prefixedPath, "%s%s", rootPrefix, conf->filename));

    GCE(ceError = CTGetFileTempPath(
                        prefixedPath,
                        &finalName,
                        &tempName));

    DJ_LOG_INFO("Writing nsswitch configuration for %s", finalName);

    ceError = CTOpenFile(tempName, "w", &file);
    if(ceError)
    {
        DJ_LOG_ERROR("Unable to open '%s' for writing", tempName);
        GCE(ceError);
    }

    for(i = 0; i < conf->lines.size; i++)
    {
        GCE(ceError = GetPrintedLine(&printedLine, conf, i));
        GCE(ceError = CTFilePrintf(file, "%s\n", printedLine.data));
    }

    GCE(ceError = CTCloseFile(file));
    file = NULL;

    GCE(ceError = CTSafeReplaceFile(
            finalName,
            tempName));
    DJ_LOG_INFO("File moved into place");

cleanup:
    if(file != NULL)
        CTCloseFile(file);
    CTArrayFree(&printedLine);
    CT_SAFE_FREE_STRING(tempName);
    CT_SAFE_FREE_STRING(finalName);
    CT_SAFE_FREE_STRING(prefixedPath);
    return ceError;
}
Esempio n. 5
0
DWORD LWExceptionToString(const LWException *conv, PCSTR titlePrefix, BOOLEAN showSymbolicCode, BOOLEAN showTrace, PSTR *result)
{
    DWORD ceError;
    PSTR ret = NULL;
    PSTR temp = NULL;
    PCSTR codeName = NULL;

    if(titlePrefix == NULL)
        titlePrefix = "";
    
    if(showSymbolicCode)
        codeName = LwWin32ExtErrorToName(conv->code);

    if(codeName != NULL)
    {
        GCE(ceError = CTAllocateStringPrintf(
            &ret, "%s%s [%s]\n\n%s", titlePrefix, conv->shortMsg, codeName, conv->longMsg));
    }
    else
    {
        GCE(ceError = CTAllocateStringPrintf(
            &ret, "%s%s [code 0x%.8x]\n\n%s", titlePrefix, conv->shortMsg, conv->code, conv->longMsg));
    }
    if(showTrace)
    {
        const LWStackFrame *frame = &conv->stack;

        temp = ret;
        GCE(ceError = CTAllocateStringPrintf(
                &ret, "%s\n\nStack Trace:", temp));
        CT_SAFE_FREE_STRING(temp);
        while(frame != NULL)
        {
            temp = ret;
            GCE(ceError = CTAllocateStringPrintf(
                    &ret, "%s\n%s:%d", temp, frame->file, frame->line));
            CT_SAFE_FREE_STRING(temp);
            frame = frame->down;
        }
    }
    *result = ret;
    ret = NULL;

cleanup:
    CT_SAFE_FREE_STRING(temp);
    CT_SAFE_FREE_STRING(ret);
    return ceError;
}
Esempio n. 6
0
static DWORD RemoveModule(NsswitchConf *conf,
        int line, int moduleIndex)
{
    DWORD ceError = ERROR_SUCCESS;
    NsswitchEntry *lineObj = (NsswitchEntry *)GetEntry(conf, line);
    CTParseToken *beforeModule = NULL, *afterModule = NULL;
    CTParseToken *removeModule;

    removeModule = (CTParseToken *)lineObj->modules.data + moduleIndex;

    if(moduleIndex - 1 >= 0)
        beforeModule = (CTParseToken *)lineObj->modules.data + moduleIndex - 1;
    if(moduleIndex + 1 < lineObj->modules.size)
        afterModule = (CTParseToken *)lineObj->modules.data + moduleIndex + 1;

    if(afterModule == NULL && beforeModule != NULL)
    {
        /* Since the last module is being removed, move the trailingSeparator
         * to the previous module */
        CT_SAFE_FREE_STRING(beforeModule->trailingSeparator);
        beforeModule->trailingSeparator = removeModule->trailingSeparator;
        removeModule->trailingSeparator = NULL;
    }
    CTFreeParseTokenContents(removeModule);

    GCE(ceError = CTArrayRemove(&lineObj->modules, moduleIndex, sizeof(CTParseToken), 1));
    conf->modified = 1;

cleanup:
    return ceError;
}
Esempio n. 7
0
void
DJManageDaemonsDescription(
    BOOLEAN bStart,
    PSTR *description,
    LWException **exc
    )
{
    BOOLEAN bFileExists = TRUE;
    LWException *innerExc = NULL;
    StringBuffer buffer;
    PSTR daemonDescription = NULL;

    LW_CLEANUP_CTERR(exc, CTStringBufferConstruct(&buffer));

    LW_CLEANUP_CTERR(exc, CTCheckFileExists(PWGRD, &bFileExists));
    if(bFileExists && bStart)
    {
        LW_CLEANUP_CTERR(exc, CTStringBufferAppend(&buffer, "Shutdown pwgrd because it only handles usernames up to 8 characters long. This is done by running '/sbin/init.d/pwgr stop' and setting PWGR=0 in "PWGRD"."));
    }

    *description = CTStringBufferFreeze(&buffer);

cleanup:
    CT_SAFE_FREE_STRING(daemonDescription);
    LW_HANDLE(&innerExc);
    CTStringBufferDestroy(&buffer);
}
Esempio n. 8
0
DWORD
DJIsAppleADPluginInUse(BOOLEAN* pExists)
{
    DWORD ceError = ERROR_SUCCESS;
    PSTR value = NULL;
    PSTR valueStart = NULL;
    BOOLEAN bInUse = FALSE;

    DJ_LOG_INFO("Testing to see if Apple AD plugin is already in use");

    ceError = CTCaptureOutput("/usr/bin/dscl localhost -list / | grep \"^Active Directory\"", &value);
    if (ceError)
    {
        ceError = ERROR_SUCCESS;
        goto error;
    }

    CTStripWhitespace(value);
    valueStart = strstr(value, "Active Directory");
    if (valueStart != NULL)
    {
        bInUse = TRUE;
    }

error:

    CT_SAFE_FREE_STRING(value);

    *pExists = bInUse;

    return ceError;
}
Esempio n. 9
0
void PrintJoinHeader(const JoinProcessOptions *options, LWException **exc)
{
    PSTR fqdn = NULL;
    PDOMAINJOININFO pDomainJoinInfo = NULL;
    PCSTR domain;

    if(options->joiningDomain)
    {
        LW_CLEANUP_CTERR(exc, DJGetFinalFqdn(options, &fqdn));
        fprintf(stdout,
                "Joining to AD Domain:   %s\n"
                "With Computer DNS Name: %s\n\n",
                options->domainName,
                fqdn);
    }
    else
    {
        if (options->domainName)
        {
            domain = options->domainName;
        }
        else
        {
            LW_TRY(exc, QueryInformation(&pDomainJoinInfo, &LW_EXC));
            domain = pDomainJoinInfo->pszDomainName;
        }
        if(domain == NULL)
            domain = "(unknown)";
        fprintf(stdout, "Leaving AD Domain:   %s\n", domain);
    }

cleanup:
    CT_SAFE_FREE_STRING(fqdn);
}
Esempio n. 10
0
static DWORD ReadNsswitchFile(NsswitchConf *conf, const char *rootPrefix, const char *filename)
{
    DWORD ceError = ERROR_SUCCESS;
    FILE *file = NULL;
    PSTR buffer = NULL;
    char *fullPath = NULL;
    BOOLEAN endOfFile = FALSE;
    BOOLEAN exists;

    if(rootPrefix == NULL)
        rootPrefix = "";

    GCE(ceError = CTAllocateStringPrintf(
            &fullPath, "%s%s", rootPrefix, filename));
    DJ_LOG_INFO("Reading nsswitch file %s", fullPath);
    GCE(ceError = CTCheckFileOrLinkExists(fullPath, &exists));
    if(!exists)
    {
        DJ_LOG_INFO("File %s does not exist", fullPath);
        ceError = ERROR_FILE_NOT_FOUND;
        goto cleanup;
    }

    GCE(ceError = CTStrdup(filename,
        &conf->filename));
    GCE(ceError = CTOpenFile(fullPath, "r", &file));
    CT_SAFE_FREE_STRING(fullPath);
    while(TRUE)
    {
        CT_SAFE_FREE_STRING(buffer);
        GCE(ceError = CTReadNextLine(file, &buffer, &endOfFile));
        if(endOfFile)
            break;
        GCE(ceError = AddFormattedLine(conf, filename, buffer, NULL));
    }

    conf->modified = FALSE;

cleanup:
    CT_SAFE_FREE_STRING(buffer);
    if(file != NULL)
        CTCloseFile(file);
    CT_SAFE_FREE_STRING(fullPath);
    if(ceError)
        FreeNsswitchConfContents(conf);
    return ceError;
}
Esempio n. 11
0
static DWORD ReadSshFile(struct SshConf *conf, const char *rootPrefix, const char *filename)
{
    DWORD ceError = ERROR_SUCCESS;
    FILE *file = NULL;
    PSTR buffer = NULL;
    char *fullPath = NULL;
    BOOLEAN endOfFile = FALSE;
    BOOLEAN exists;

    BAIL_ON_CENTERIS_ERROR(ceError = CTAllocateStringPrintf(
            &fullPath, "%s%s", rootPrefix, filename));
    DJ_LOG_INFO("Reading ssh file %s", fullPath);
    BAIL_ON_CENTERIS_ERROR(ceError = CTCheckFileOrLinkExists(fullPath, &exists));
    if(!exists)
    {
        DJ_LOG_INFO("File %s does not exist", fullPath);
        ceError = ERROR_FILE_NOT_FOUND;
        goto error;
    }

    BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(filename,
        &conf->filename));
    BAIL_ON_CENTERIS_ERROR(ceError = CTOpenFile(fullPath, "r", &file));
    CT_SAFE_FREE_STRING(fullPath);
    while(TRUE)
    {
        CT_SAFE_FREE_STRING(buffer);
        BAIL_ON_CENTERIS_ERROR(ceError = CTReadNextLine(file, &buffer, &endOfFile));
        if(endOfFile)
            break;
        BAIL_ON_CENTERIS_ERROR(ceError = AddFormattedLine(conf, filename, buffer, NULL));
    }
	CT_SAFE_FREE_STRING(buffer);
    BAIL_ON_CENTERIS_ERROR(ceError = CTCloseFile(file));
    file = NULL;

    return ceError;

error:
    if(file != NULL)
        CTCloseFile(file);
    CT_SAFE_FREE_STRING(fullPath);
    FreeSshConfContents(conf);
    CT_SAFE_FREE_STRING(buffer);
    return ceError;
}
Esempio n. 12
0
static void FreeNsswitchConfContents(NsswitchConf *conf)
{
    size_t i;
    for(i = 0; i < conf->lines.size; i++)
    {
        FreeNsswitchEntryContents(((NsswitchEntry *)conf->lines.data) + i);
    }
	CT_SAFE_FREE_STRING(conf->filename);
    CTArrayFree(&conf->lines);
}
Esempio n. 13
0
static void FreeSshConfContents(struct SshConf *conf)
{
    int i;
    for(i = 0; i < conf->lineCount; i++)
    {
        FreeSshLineContents(&conf->lines[i]);
    }
    CTArrayFree(&conf->private_data);
    UpdatePublicLines(conf);
    CT_SAFE_FREE_STRING(conf->filename);
}
Esempio n. 14
0
static void FreeSshLineContents(struct SshLine *line)
{
    char **strings[5];
    int stringCount = 5;
    int i;

    GetLineStrings(strings, line, &stringCount);
    for(i = 0; i < stringCount; i++)
    {
        CT_SAFE_FREE_STRING(*strings[i]);
    }
}
Esempio n. 15
0
DWORD
DJQueryJoinInformation(
    PSTR* ppszComputerName,
    PSTR* ppszDomainName,
    PSTR* ppszComputerDN
    )
{
    DWORD dwError = 0;
    LWException *exc = NULL;
    PSTR  pszComputerName = NULL;
    PSTR  pszDomainName = NULL;
    PSTR  pszComputerDN = NULL;

    LW_TRY(&exc, DJQuery(&pszComputerName, &pszDomainName, NULL, &LW_EXC));

    if (!IsNullOrEmptyString(pszDomainName))
    {
       LW_TRY(&exc, DJGetComputerDN(&pszComputerDN, &LW_EXC));
    }

    *ppszComputerName = pszComputerName;
    *ppszDomainName = pszDomainName;
    *ppszComputerDN = pszComputerDN;

cleanup:

    if (!LW_IS_OK(exc))
    {
        CT_SAFE_FREE_STRING(pszComputerName);
        CT_SAFE_FREE_STRING(pszDomainName);
        CT_SAFE_FREE_STRING(pszComputerDN);

        dwError = exc->code;
        LWHandle(&exc);
    }

    return dwError;
}
Esempio n. 16
0
void DoGetDistroInfo(int argc, char **argv, LWException **exc)
{
    PSTR str = NULL;
    PCSTR requestType = argv[0];
    PCSTR testPrefix = NULL;
    LwDistroInfo distro = {0};

    argc--;
    argv++;

    if(argc > 0 && !strcmp(argv[0], "--testprefix"))
    {
        testPrefix = argv[1];
        argv += 2;
        argc -= 2;
    }
    if(argc > 0)
    {
        LW_RAISE(exc, LW_ERROR_SHOW_USAGE);
        goto cleanup;
    }

    LW_CLEANUP_CTERR(exc, DJGetDistroInfo(testPrefix, &distro));
    if(!strcmp(requestType, "get_os_type"))
    {
        LW_CLEANUP_CTERR(exc, DJGetOSString(distro.os, &str));
    }
    else if(!strcmp(requestType, "get_arch"))
    {
        LW_CLEANUP_CTERR(exc, DJGetArchString(distro.arch, &str));
    }
    else if(!strcmp(requestType, "get_distro"))
    {
        LW_CLEANUP_CTERR(exc, DJGetDistroString(distro.distro, &str));
    }
    else if(!strcmp(requestType, "get_distro_version"))
    {
        LW_CLEANUP_CTERR(exc, CTStrdup(distro.version, &str));
    }
    else
    {
        LW_RAISE(exc, LW_ERROR_SHOW_USAGE);
        goto cleanup;
    }
    fprintf(stdout, "%s\n", str);

cleanup:
    DJFreeDistroInfo(&distro);
    CT_SAFE_FREE_STRING(str);
}
Esempio n. 17
0
void PrintWarning(const JoinProcessOptions *options, const char *title, const char *message)
{
    PSTR      wrapped = NULL;
    int columns;
    if(CTGetTerminalWidth(fileno(stdout), &columns))
        columns = -1;

    //This function doesn't return a DWORD, so we have to recover as much
    //as possible.
    if(!CTWordWrap(message, &wrapped, 4, columns))
        fprintf(stdout, "Warning: %s\n%s\n\n", title, wrapped);
    else
        fprintf(stdout, "Warning: %s\n%s\n\n", title, message);
    CT_SAFE_FREE_STRING(wrapped);
    DJ_LOG_WARNING("%s\n%s", title, message);
}
Esempio n. 18
0
DWORD DJGetOptionValue(const DynamicArray *lines, PCSTR stanza, PCSTR name, PSTR *value)
{
    DWORD ceError = ERROR_SUCCESS;
    ssize_t i = DJFindLine(lines, stanza, name);
    PCSTR line;
    PSTR _value = NULL;

    *value = NULL;
    
    if(i == -1)
        GCE(ceError = ERROR_NOT_FOUND);

    line = *(PCSTR *)CTArrayGetItem((DynamicArray*)lines, i,
            sizeof(PCSTR));

    while (*line != '\0' && isspace((int)*line))
        line++;

    line += strlen(name);
   
    while (*line != '\0' && isspace((int)*line))
        line++;

    if(*line != '=')
    {
        GCE(ceError = ERROR_BAD_FORMAT);
    }
    line++;

    GCE(ceError = CTStrdup(line, &_value));
    CTStripWhitespace(_value);
    /* Remove the quotes around the value, if they exist */
    if(CTStrStartsWith(_value, "\"") && CTStrEndsWith(_value, "\""))
    {
        size_t len = strlen(_value);
        memmove(_value, _value + 1, len - 2 );
        _value[len - 2 ] = '\0';
    }

    *value = _value;
    _value = NULL;

cleanup:
    CT_SAFE_FREE_STRING(_value);
    return ceError;
}
Esempio n. 19
0
static QueryResult QueryPamMode(const JoinProcessOptions *options, LWException **exc)
{
    BOOLEAN bFileExists = FALSE;
    DistroInfo distro;
    QueryResult result = NotApplicable;
    FILE* fp = NULL;
    DynamicArray lines;
    PCSTR pszFilePath = LOGIN_CONFIG_PATH;
    PSTR currentSystem = NULL;

    memset(&lines, 0, sizeof(lines));
    memset(&distro, 0, sizeof(distro));

    if(!options->joiningDomain || options->enableMultipleJoins)
        goto cleanup;

    LW_CLEANUP_CTERR(exc, DJGetDistroInfo(NULL, &distro));
    if(distro.os != OS_AIX || strcmp(distro.version, "5.3"))
        goto cleanup;

    LW_CLEANUP_CTERR(exc, CTCheckFileExists(pszFilePath, &bFileExists));

    if (!bFileExists)
        goto cleanup;

    result = SufficientlyConfigured;

    LW_CLEANUP_CTERR(exc, CTOpenFile(pszFilePath, "r", &fp));
    LW_CLEANUP_CTERR(exc, CTReadLines(fp, &lines));
    LW_CLEANUP_CTERR(exc, CTSafeCloseFile(&fp));

    LW_CLEANUP_CTERR(exc, GetAuthType(&lines, &currentSystem));
    if(strcmp(currentSystem, "PAM_AUTH"))
        goto cleanup;

    result = FullyConfigured;

cleanup:
    CT_SAFE_FREE_STRING(currentSystem);
    DJFreeDistroInfo(&distro);
    CTSafeCloseFile(&fp);
    CTFreeLines(&lines);
    return result;
}
Esempio n. 20
0
DWORD
DJSetOptionValue(DynamicArray *lines, PCSTR stanza, PCSTR name, PCSTR value)
{
    ssize_t index;
    PSTR newLine = NULL;
    DWORD ceError = ERROR_SUCCESS;

    if(strchr(value, ' '))
    {
        /* Fixes bug 5564 */
        GCE(ceError = CTAllocateStringPrintf(&newLine, "\t%s = \"%s\"\n", name, value));
    }
    else
        GCE(ceError = CTAllocateStringPrintf(&newLine, "\t%s = %s\n", name, value));

    index = DJFindLine(lines, stanza, name);

    if(index == -1)
    {
        index = DJFindStanza(lines, stanza);
        if(index == -1)
            GCE(ceError = ERROR_INVALID_OPERATION);
        index++;
    }
    else
    {
        CT_SAFE_FREE_STRING(*(PSTR *)CTArrayGetItem((DynamicArray*)lines,
                    index, sizeof(PSTR)));
        GCE(ceError = CTArrayRemove((DynamicArray *)lines, index,
                    sizeof(PSTR), 1));
    }

    GCE(ceError = CTArrayInsert((DynamicArray *)lines, index,
                sizeof(PSTR), &newLine, 1));

cleanup:
    return ceError;
}
Esempio n. 21
0
static void GetSshVersion(PCSTR rootPrefix, SshdVersion *version, PCSTR binaryPath, LWException **exc)
{
    DWORD ceError = ERROR_SUCCESS;
    PSTR command = NULL;
    PSTR commandOutput = NULL;
    PCSTR versionStart;
    PSTR intEnd;

    version->isOpenSsh = FALSE;
    version->major = -1;
    version->minor = -1;
    version->secondMinor = -1;
    version->patch = -1;

    if(rootPrefix == NULL)
        rootPrefix = "";

    LW_CLEANUP_CTERR(exc, CTAllocateStringPrintf(
        &command, "%s%s -v 2>&1",
        rootPrefix, binaryPath));

    ceError = CTCaptureOutput(command, &commandOutput);
    if(ceError == ERROR_BAD_COMMAND)
        ceError = ERROR_SUCCESS;
    LW_CLEANUP_CTERR(exc, ceError);

    // The version string is in the form OpenSSH_4.6p1
    // or OpenSSH_3.6.1p1
    versionStart = strstr(commandOutput, "OpenSSH_");
    if(versionStart == NULL)
    {
        goto cleanup;
    }
    version->isOpenSsh = TRUE;

    versionStart += strlen("OpenSSH_");
    version->major = strtoul(versionStart, &intEnd, 10);
    if(intEnd == versionStart)
        version->major = -1;
    if(intEnd == NULL || *intEnd != '.')
        goto cleanup;
    versionStart = intEnd + 1;

    version->minor = strtoul(versionStart, &intEnd, 10);
    if(intEnd == versionStart)
        version->minor = -1;
    if(intEnd == NULL || (*intEnd != '.' && *intEnd != 'p'))
        goto cleanup;
    versionStart = intEnd + 1;

    if(*intEnd == '.')
    {
        version->secondMinor = strtoul(versionStart, &intEnd, 10);
        if(intEnd == versionStart)
            version->secondMinor = -1;
        if(intEnd == NULL || *intEnd != 'p')
            goto cleanup;
        versionStart = intEnd + 1;
    }

    version->patch = strtoul(versionStart, &intEnd, 10);
    if(intEnd == versionStart)
        version->patch = -1;

cleanup:

    if(version->isOpenSsh)
    {
        DJ_LOG_INFO("Found open sshd version %d.%d.%dp%d", version->major,
                version->minor, version->secondMinor, version->patch);
    }
    else
    {
        DJ_LOG_INFO("Found non-openssh version of ssh");
    }

    CT_SAFE_FREE_STRING(command);
    CT_SAFE_FREE_STRING(commandOutput);
}
Esempio n. 22
0
static BOOLEAN TestOption(PCSTR rootPrefix, struct SshConf *conf, PCSTR binary, PCSTR testFlag, PCSTR optionName, LWException **exc)
{
    DWORD ceError = ERROR_SUCCESS;
    BOOLEAN result = FALSE;
    PSTR command = NULL;
    PSTR commandOutput = NULL;
    int existingLine;

    if(rootPrefix == NULL)
        rootPrefix = "";
    DJ_LOG_INFO("Testing option %s", optionName);

    existingLine = FindOption(conf, 0, optionName);
    if(existingLine != -1)
    {
        if(!strcmp(conf->lines[existingLine].value.value, "yes"))
        {
            //The option is already enabled, so it must be supported
            result = TRUE;
            goto cleanup;
        }
    }

    /* Most versions of sshd support the -t option which runs it in test
       mode. Test mode is used to verify that a config file is correct, or
       in our case that the passed options are valid.

       The only version of sshd known to not support -t is the version that
       comes with Solaris 9. However, this version does not support the -o
       option, and it will error out if the -o option is used. The Solaris
       9 version of sshd does not support any of the options we'd like to
       enable, so it will correctly fail all of the option tests.

       Sshd will either complain about the first invalid option that is
       passed with -o, or it will complain about all invalid options. -o
       BadOption=yes is passed to verify that sshd understands -o, and to
       make doubly sure that it will not start listening on a port.

       The -v option can be used to test whether ssh (the client) supports
       given options.  Passing -v to ssh will cause it to print out its
       version number and not attempt to connect to a machine. All versions of
       ssh seem to parse the options passed with -o even when -v is passed.

       Ssh will either complain about the first invalid option that is
       passed with -o, or it will complain about all invalid options. -o
       BadOption=yes is passed to verify that ssh understands -o.
     */
    LW_CLEANUP_CTERR(exc, CTAllocateStringPrintf(
        &command, "%s%s %s -o %s=yes -o BadOption=yes 2>&1",
        rootPrefix, binary, testFlag, optionName));

    ceError = CTCaptureOutput(command, &commandOutput);
    /* Some versions of sshd will return an error code because an invalid
       option was passed, but not all will. */
    if(ceError == ERROR_BAD_COMMAND)
        ceError = ERROR_SUCCESS;
    LW_CLEANUP_CTERR(exc, ceError);

    if(strstr(commandOutput, optionName) != NULL)
    {
        DJ_LOG_INFO("Option %s not supported", optionName);
        goto cleanup;
    }

    if(strstr(commandOutput, "BadOption") == NULL)
    {
        DJ_LOG_INFO("Sshd does not support -o");
        goto cleanup;
    }

    DJ_LOG_INFO("Option %s supported", optionName);
    result = TRUE;

cleanup:
    CT_SAFE_FREE_STRING(command);
    CT_SAFE_FREE_STRING(commandOutput);
    return result;
}
Esempio n. 23
0
/* Copy a ssh configuration line and add it below the old line. */
static DWORD SetOption(struct SshConf *conf, const char *name, const char *value)
{
    DWORD ceError = ERROR_SUCCESS;
    int line = -1;
    DynamicArray printedLine;
    struct SshLine lineObj;
    int found = 0;

    memset(&lineObj, 0, sizeof(struct SshLine));
    memset(&printedLine, 0, sizeof(printedLine));

    for(line = 0; line < conf->lineCount; line++)
    {
        line = FindOption(conf, line, name);
        if(line == -1)
            break;
        found++;
        if(!strcmp(conf->lines[line].value.value, value))
            continue;

        //Insert a commented out version of the line
        BAIL_ON_CENTERIS_ERROR(ceError = GetPrintedLine(&printedLine, conf, line));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.leadingWhiteSpace));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.name.value));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.name.trailingSeparator));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.value.value));
        BAIL_ON_CENTERIS_ERROR(ceError = CTAllocateStringPrintf(
            &lineObj.value.trailingSeparator,
            "#Overwritten by lwidentity: %s",
            printedLine.data));
        BAIL_ON_CENTERIS_ERROR(ceError = CTArrayInsert(&conf->private_data,
                    line, sizeof(struct SshLine), &lineObj, 1));
        memset(&lineObj, 0, sizeof(lineObj));
        UpdatePublicLines(conf);
        conf->modified = 1;
        line++;

        //Change the option value of the line
        CT_SAFE_FREE_STRING(conf->lines[line].value.value);
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(value,
            &conf->lines[line].value.value));
    }

    /*If the option wasn't already in the file, search for comments that
      mention the option, and insert the line after the comment*/
    for(line = 0; !found && line < conf->lineCount; line++)
    {
        if(strstr(conf->lines[line].value.trailingSeparator, name) == NULL)
            continue;

        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.leadingWhiteSpace));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(name,
            &lineObj.name.value));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(" ",
            &lineObj.name.trailingSeparator));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(value,
            &lineObj.value.value));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.value.trailingSeparator));
        BAIL_ON_CENTERIS_ERROR(ceError = CTArrayInsert(&conf->private_data,
                    line + 1, sizeof(struct SshLine), &lineObj, 1));
        memset(&lineObj, 0, sizeof(lineObj));
        conf->modified = 1;
        found++;
    }

    /*If the option wasn't even in a comment, just add the option at the
      end of the file
      */
    if(!found)
    {
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.leadingWhiteSpace));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(name,
            &lineObj.name.value));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(" ",
            &lineObj.name.trailingSeparator));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup(value,
            &lineObj.value.value));
        BAIL_ON_CENTERIS_ERROR(ceError = CTStrdup("",
            &lineObj.value.trailingSeparator));
        BAIL_ON_CENTERIS_ERROR(ceError = CTArrayAppend(&conf->private_data,
                    sizeof(struct SshLine), &lineObj, 1));
        memset(&lineObj, 0, sizeof(lineObj));
        conf->modified = 1;
    }

error:
    UpdatePublicLines(conf);
    FreeSshLineContents(&lineObj);
    CTArrayFree(&printedLine);
    return ceError;
}
Esempio n. 24
0
static
DWORD
DJConfigureDHCPService(
    PSTR pszComputerName
    )
{
    DWORD ceError = ERROR_SUCCESS;
    int EE = 0;
    BOOLEAN bFileExists = FALSE;
    PSTR dhcpFilePath = "/etc/sysconfig/network/dhcp";
    PSTR  ppszArgs[] =
        { "/bin/sed",
          "s/^.*\\(DHCLIENT_SET_HOSTNAME\\).*=.*$/\\1=\\\"no\\\"/",
          dhcpFilePath,
          NULL
        };
#if !defined(HAVE_SETHOSTNAME) || !HAVE_DECL_SETHOSTNAME
    PSTR  ppszNetArgs[] =
        {
#if defined(_AIX)
            "/etc/rc.d/init.d/network",
#else
            "/etc/init.d/network",
#endif
            "restart",
            NULL
        };
#endif
    PPROCINFO pProcInfo = NULL;
    LONG status = 0;
    PSTR pszFinalPath = NULL;
    PSTR pszTmpPath = NULL;

    ceError = CTCheckFileExists(dhcpFilePath, &bFileExists);
    CLEANUP_ON_DWORD_EE(ceError, EE);

    if (bFileExists)
    {
        ceError = CTGetFileTempPath(
                            dhcpFilePath,
                            &pszFinalPath,
                            &pszTmpPath);
        CLEANUP_ON_DWORD_EE(ceError, EE);

        ppszArgs[2] = pszFinalPath;
        ceError = DJSpawnProcessOutputToFile(ppszArgs[0], ppszArgs, pszTmpPath, &pProcInfo);
        CLEANUP_ON_DWORD_EE(ceError, EE);

        ceError = DJGetProcessStatus(pProcInfo, &status);
        CLEANUP_ON_DWORD_EE(ceError, EE);

        if (status != 0) {
            ceError = ERROR_FAIL_RESTART;
            CLEANUP_ON_DWORD_EE(ceError, EE);
        }

        ceError = CTSafeReplaceFile(pszFinalPath, pszTmpPath);
        CLEANUP_ON_DWORD_EE(ceError, EE);
    }

    if (pProcInfo) {
        FreeProcInfo(pProcInfo);
        pProcInfo = NULL;
    }

#if defined(HAVE_SETHOSTNAME) && HAVE_DECL_SETHOSTNAME
    if (sethostname(pszComputerName, strlen(pszComputerName)) < 0)
    {
        ceError = LwMapErrnoToLwError(errno);
        CLEANUP_ON_DWORD_EE(ceError, EE);
    }
#else
    ceError = DJFixNetworkManagerOnlineTimeout();
    CLEANUP_ON_DWORD_EE(ceError, EE);

    /* Restart network */

    ceError = DJSpawnProcess(ppszNetArgs[0], ppszNetArgs, &pProcInfo);
    CLEANUP_ON_DWORD_EE(ceError, EE);

    ceError = DJGetProcessStatus(pProcInfo, &status);
    CLEANUP_ON_DWORD_EE(ceError, EE);

    if (status != 0) {
        ceError = ERROR_BAD_COMMAND;
        CLEANUP_ON_DWORD_EE(ceError, EE);
    }
#endif

cleanup:

    if (pProcInfo)
        FreeProcInfo(pProcInfo);

    DJ_LOG_VERBOSE("DJRestartDHCPService LEAVE -> 0x%08x (EE = %d)", ceError, EE);

    CT_SAFE_FREE_STRING(pszFinalPath);
    CT_SAFE_FREE_STRING(pszTmpPath);

    return ceError;
}
Esempio n. 25
0
static
DWORD
DJFixNetworkManagerOnlineTimeout(
    )
{
    DWORD ceError = ERROR_SUCCESS;
    PSTR pszFilePath = "/etc/sysconfig/network/config";
    DWORD dwTimeout = 60;
    int EE = 0;
    BOOLEAN bFileExists = FALSE;
    char *isEnabled = NULL;
    char *currentTimeout = NULL;
    char *sedExpression = NULL;
    long currentTimeoutLong;
    char *conversionEnd;

    ceError = CTCheckFileExists(pszFilePath, &bFileExists);
    CLEANUP_ON_DWORD_EE(ceError, EE);
    if(!bFileExists)
        goto cleanup;

    ceError = CTShell(". %pszFilePath; echo \"$NETWORKMANAGER\" >%enabled; echo \"$NM_ONLINE_TIMEOUT\" >%timeout",
            CTSHELL_STRING (pszFilePath, pszFilePath),
            CTSHELL_BUFFER (enabled, &isEnabled),
            CTSHELL_BUFFER (timeout, &currentTimeout));
    CLEANUP_ON_DWORD_EE(ceError, EE);
    CTStripTrailingWhitespace(isEnabled);
    CTStripTrailingWhitespace(currentTimeout);

    DJ_LOG_VERBOSE("Network manager enabled [%s] network manager timeout [%s]", isEnabled, currentTimeout);

    if(strcasecmp(isEnabled, "yes"))
    {
        DJ_LOG_INFO("Network manager is not enabled");
        goto cleanup;
    }

    currentTimeoutLong = strtol(currentTimeout, &conversionEnd, 10);
    if(*conversionEnd != '\0')
    {
        DJ_LOG_INFO("Unable to convert network manager timeout to long");
        currentTimeoutLong = 0;
    }

    if(currentTimeoutLong < dwTimeout)
    {
        DJ_LOG_INFO("Setting network manager timeout to %d", dwTimeout);
        ceError = CTAllocateStringPrintf(&sedExpression,
                "s/^\\([ \t]*NM_ONLINE_TIMEOUT[ \t]*=[ \t]*\\).*$/\\1%d/",
                dwTimeout);
        CLEANUP_ON_DWORD_EE(ceError, EE);
        ceError = CTRunSedOnFile(pszFilePath, pszFilePath, FALSE, sedExpression);
        CLEANUP_ON_DWORD_EE(ceError, EE);
    }

cleanup:
    DJ_LOG_VERBOSE("DJFixNetworkManagerOnlineTimeout LEAVE -> 0x%08x (EE = %d)", ceError, EE);

    CT_SAFE_FREE_STRING(isEnabled);
    CT_SAFE_FREE_STRING(currentTimeout);
    CT_SAFE_FREE_STRING(sedExpression);

    return ceError;
}
Esempio n. 26
0
DWORD
CTEscapeString(
    PCSTR pszOrig,
    PSTR * ppszEscapedString
    )
{
    DWORD ceError = ERROR_SUCCESS;
    int nQuotes = 0;
    PCSTR pszTmp = pszOrig;
    PSTR pszNew = NULL;
    PSTR pszNewTmp = NULL;

    if ( !ppszEscapedString || !pszOrig ) {
        ceError = ERROR_INVALID_PARAMETER;
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    while(pszTmp && *pszTmp)
    {
        if (*pszTmp=='\'') {
            nQuotes++;
        }
        pszTmp++;
    }

    if (!nQuotes) {
        ceError = CTAllocateString(pszOrig, &pszNew);
        BAIL_ON_CENTERIS_ERROR(ceError);
    } else {
        /*
         * We are going to escape each single quote and enclose it in two other
         * single-quotes
         */
        ceError = CTAllocateMemory( strlen(pszOrig)+3*nQuotes+1, (PVOID*)&pszNew );
        BAIL_ON_CENTERIS_ERROR(ceError);

        pszTmp = pszOrig;
        pszNewTmp = pszNew;

        while(pszTmp && *pszTmp)
        {
            if (*pszTmp=='\'') {
                *pszNewTmp++='\'';
                *pszNewTmp++='\\';
                *pszNewTmp++='\'';
                *pszNewTmp++='\'';
                pszTmp++;
            }
            else {
                *pszNewTmp++ = *pszTmp++;
            }
        }
        *pszNewTmp = '\0';
    }

    *ppszEscapedString = pszNew;
    pszNew = NULL;

error:

    CT_SAFE_FREE_STRING(pszNew);

    return ceError;
}
Esempio n. 27
0
static QueryResult UpdateSshdConf(struct SshConf *conf, PCSTR testPrefix,
        PCSTR binaryPath, BOOLEAN enable, PSTR *changeDescription,
        const JoinProcessOptions *options, LWException **exc)
{
    size_t i;
    BOOLEAN modified = conf->modified;
    PSTR requiredOptions = NULL;
    PSTR optionalOptions = NULL;
    BOOLEAN supported;
    PSTR temp = NULL;
    QueryResult result = NotConfigured;
    const char *requiredSshdOptions[] = {
        "ChallengeResponseAuthentication",
        "UsePAM", "PAMAuthenticationViaKBDInt",
        "KbdInteractiveAuthentication", NULL};
    const char *optionalSshdOptions[] = {"GSSAPIAuthentication",
        "GSSAPICleanupCredentials", NULL};
    SshdVersion version;
    BOOLEAN compromisedOptions = FALSE;

    if(changeDescription != NULL)
        *changeDescription = NULL;

    LW_TRY(exc, GetSshVersion("", &version, binaryPath, &LW_EXC));

    if(enable)
    {
        LW_CLEANUP_CTERR(exc, CTStrdup("", &requiredOptions));
        LW_CLEANUP_CTERR(exc, CTStrdup("", &optionalOptions));
        for(i = 0; requiredSshdOptions[i] != NULL; i++)
        {
            PCSTR option = requiredSshdOptions[i];
            LW_TRY(exc, supported = TestOption(testPrefix, conf, binaryPath, "-t", option, &LW_EXC));
            if(supported)
            {
                PCSTR value = "yes";

                if(IsNewerThanOrEq(&version, 2, 3, 1, -1) &&
                        IsOlderThanOrEq(&version, 3, 3, -1, -1) &&
                        (!strcmp(option, "ChallengeResponseAuthentication") ||
                         !strcmp(option, "PAMAuthenticationViaKBDInt")))
                {
                    value = "no";
                    compromisedOptions = TRUE;
                }
                conf->modified = FALSE;
                LW_CLEANUP_CTERR(exc, SetOption(conf, option, value));
                if(conf->modified)
                {
                    modified = TRUE;
                    temp = requiredOptions;
                    requiredOptions = NULL;
                    CTAllocateStringPrintf(&requiredOptions, "%s\t%s\n", temp, option);
                    CT_SAFE_FREE_STRING(temp);
                }
            }
        }
        for(i = 0; optionalSshdOptions[i] != NULL; i++)
        {
            PCSTR option = optionalSshdOptions[i];
            LW_TRY(exc, supported = TestOption(testPrefix, conf, binaryPath, "-t", option, &LW_EXC));
            if(supported)
            {
                conf->modified = FALSE;
                LW_CLEANUP_CTERR(exc, SetOption(conf, option, "yes"));
                if(conf->modified)
                {
                    modified = TRUE;
                    temp = optionalOptions;
                    optionalOptions = NULL;
                    LW_CLEANUP_CTERR(exc, CTAllocateStringPrintf(&optionalOptions, "%s\t%s\n", temp, option));
                    CT_SAFE_FREE_STRING(temp);
                }
            }
        }
        result = FullyConfigured;
        if(strlen(optionalOptions) > 0)
        {
            temp = optionalOptions;
            optionalOptions = NULL;
            LW_CLEANUP_CTERR(exc, CTAllocateStringPrintf(
                        &optionalOptions,
                        "The following options will be enabled in %s to provide a better user experience:\n%s",
                        conf->filename, temp));
            CT_SAFE_FREE_STRING(temp);
            result = SufficientlyConfigured;
        }
        if(strlen(requiredOptions) > 0)
        {
            temp = requiredOptions;
            requiredOptions = NULL;
            LW_CLEANUP_CTERR(exc, CTAllocateStringPrintf(
                        &requiredOptions,
                        "The following options must be enabled in %s:\n%s",
                        conf->filename, temp));
            CT_SAFE_FREE_STRING(temp);
            result = NotConfigured;
        }
        if(changeDescription != NULL)
        {
            LW_CLEANUP_CTERR(exc, CTAllocateStringPrintf(
                        changeDescription,
                        "%s%s",
                        requiredOptions, optionalOptions));
        }
    }
    else
    {
        conf->modified = FALSE;
        LW_CLEANUP_CTERR(exc, RemoveOption(conf, "GSSAPIAuthentication"));
        if(conf->modified)
        {
            if(changeDescription != NULL)
            {
                LW_CLEANUP_CTERR(exc, CTAllocateStringPrintf(
                            changeDescription,
                            "In %s, GSSAPIAuthentication may optionally be removed.\n",
                            conf->filename));
            }
            result = SufficientlyConfigured;
        }
        else
            result = FullyConfigured;
    }
    if(changeDescription != NULL && *changeDescription == NULL)
        LW_CLEANUP_CTERR(exc, CTStrdup("", changeDescription));

    if(options != NULL)
    {
        ModuleState *state = DJGetModuleStateByName(options, "ssh");
        if(state->moduleData == (void *)-1)
        {
            //We already showed a warning
        }
        else if(compromisedOptions)
        {
            state->moduleData = (void *)-1;
            if (options->warningCallback != NULL)
            {
                options->warningCallback(options, "Unpatched version of SSH",
                        "The version of your sshd daemon indicates that it is susceptible to the remote exploit described at http://www.openssh.com/txt/preauth.adv . To avoid exposing your system to this exploit, the 'ChallengeResponseAuthentication' and 'PAMAuthenticationViaKBDInt' options will be set to 'no' instead of 'yes'. As a side effect, all login error messages will appear as 'permission denied' instead of more detailed messages like 'account disabled'. Additionally, password changes on login may not work.\n\
\n\
Even when those options are disabled, your system is still vulnerable to http://www.cert.org/advisories/CA-2003-24.html . We recommend upgrading your version of SSH.");
            }
        }
Esempio n. 28
0
static
DWORD
WriteHostnameToSunFiles(
    PCSTR pOldShortHostname,
    PCSTR pNewShortHostname,
    PCSTR pDnsDomainName,
    PCSTR pOldFqdnHostname,
    PCSTR pNewFqdnHostname
    )
{
    DWORD ceError = ERROR_SUCCESS;
    FILE* fp = NULL;
    PSTR* ppszHostfilePaths = NULL;
    DWORD nPaths = 0;
    DWORD iPath = 0;
    PSTR pRealPath = NULL;
    PSTR pTempPath = NULL;
    PSTR pOldEscapedShortHostname = NULL;
    PSTR pOldEscapedFqdnHostname = NULL;
    PSTR pOldSedExpression = NULL;
    PSTR pSedExpression = NULL;
    BOOLEAN isSame = FALSE;

    DJ_LOG_INFO("Setting hostname to [%s]", pNewShortHostname);

    ceError = CTGetFileTempPath(
                        "/etc/nodename",
                        &pRealPath,
                        &pTempPath);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = CTOpenFile(
            pTempPath,
            "w",
            &fp);
    BAIL_ON_CENTERIS_ERROR(ceError);

    if (fprintf(fp, "%s\n", pNewShortHostname) < 0)
    {
        ceError = LwMapErrnoToLwError(errno);
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    ceError = CTSafeCloseFile(&fp);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = CTFileContentsSame(
                    pTempPath,
                    pRealPath,
                    &isSame);
    BAIL_ON_CENTERIS_ERROR(ceError);
    if (isSame)
    {
        BAIL_ON_CENTERIS_ERROR(ceError = CTRemoveFile(pTempPath));
    }
    else
    {
        ceError = CTSafeReplaceFile(pRealPath, pTempPath);
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    CT_SAFE_FREE_STRING(pRealPath);
    CT_SAFE_FREE_STRING(pTempPath);

    ceError = CTGetFileTempPath(
                        "/etc/defaultdomain",
                        &pRealPath,
                        &pTempPath);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = CTOpenFile(
            pTempPath,
            "w",
            &fp);
    BAIL_ON_CENTERIS_ERROR(ceError);

    fprintf(fp, "%s\n", pDnsDomainName);

    ceError = CTSafeCloseFile(&fp);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = CTFileContentsSame(
                    pTempPath,
                    pRealPath,
                    &isSame);
    BAIL_ON_CENTERIS_ERROR(ceError);
    if (isSame)
    {
        BAIL_ON_CENTERIS_ERROR(ceError = CTRemoveFile(pTempPath));
    }
    else
    {
        ceError = CTSafeReplaceFile(pRealPath, pTempPath);
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    /* The first column of the /etc/hostname.<interface> files is the IP
     * address of the interface. It may either be specified directly in the
     * file, or the file may refer to an entry in /etc/hosts. This program is
     * editing /etc/hosts, any old entries in the hostname files need to be
     * fixed. */
    ceError = CTGetMatchingFilePathsInFolder("/etc",
                                             "hostname.*",
                                             &ppszHostfilePaths,
                                             &nPaths);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = SedEscapeLiteral(
                pOldShortHostname,
                &pOldEscapedShortHostname);
    BAIL_ON_CENTERIS_ERROR(ceError);

    ceError = LwAllocateStringPrintf(
                &pSedExpression,
                "s/^%s\\([ ].*\\)\\{0,1\\}$/%s\\1/",
                pOldEscapedShortHostname,
                pNewShortHostname);
    BAIL_ON_CENTERIS_ERROR(ceError);

    if (pOldFqdnHostname != NULL)
    {
        ceError = SedEscapeLiteral(
                    pOldFqdnHostname,
                    &pOldEscapedFqdnHostname);
        BAIL_ON_CENTERIS_ERROR(ceError);

        pOldSedExpression = pSedExpression;
        pSedExpression = NULL;

        ceError = LwAllocateStringPrintf(
                    &pSedExpression,
                    "%s;s/^%s\\([ ].*\\)\\{0,1\\}$/%s\\1/",
                    pOldSedExpression,
                    pOldEscapedFqdnHostname,
                    pNewFqdnHostname);
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    for (iPath = 0; iPath < nPaths; iPath++)
    {
        if (!CTStrEndsWith(ppszHostfilePaths[iPath], ".lwidentity.bak") &&
            !CTStrEndsWith(ppszHostfilePaths[iPath], ".lwidentity.orig"))
        {
            ceError = CTRunSedOnFile(
                            ppszHostfilePaths[iPath],
                            ppszHostfilePaths[iPath],
                            FALSE,
                            pSedExpression);
            BAIL_ON_CENTERIS_ERROR(ceError);
        }
    }

error:

    if (ppszHostfilePaths)
        CTFreeStringArray(ppszHostfilePaths, nPaths);

    if (fp) {
        fclose(fp);
    }

    CT_SAFE_FREE_STRING(pRealPath);
    CT_SAFE_FREE_STRING(pTempPath);
    CT_SAFE_FREE_STRING(pOldEscapedShortHostname);
    CT_SAFE_FREE_STRING(pOldEscapedFqdnHostname);
    CT_SAFE_FREE_STRING(pOldSedExpression);
    CT_SAFE_FREE_STRING(pSedExpression);

    return ceError;
}
Esempio n. 29
0
void CTFreeParseTokenContents(CTParseToken *token)
{
    CT_SAFE_FREE_STRING(token->value);
    CT_SAFE_FREE_STRING(token->trailingSeparator);
}
Esempio n. 30
0
static
DWORD
DJReplaceNameValuePair(
    PSTR pszFilePath,
    PSTR pszName,
    PSTR pszValue
    )
{
    DWORD ceError = ERROR_SUCCESS;
    PSTR pszTmpPath = NULL;
    PSTR pszFinalPath = NULL;
    FILE* fpSrc = NULL;
    FILE* fpDst = NULL;
    regex_t rx;
    CHAR szRegExp[256];
    CHAR szBuf[1024+1];
    BOOLEAN bRemoveFile = FALSE;

    memset(&rx, 0, sizeof(rx));

    ceError = CTGetFileTempPath(
                        pszFilePath,
                        &pszFinalPath,
                        &pszTmpPath);
    BAIL_ON_CENTERIS_ERROR(ceError);

    sprintf(szRegExp, "^[[:space:]]*%s[[:space:]]*=.*$", pszName);

    if (regcomp(&rx, szRegExp, REG_EXTENDED) < 0) {
        ceError = LW_ERROR_REGEX_COMPILE_FAILED;
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    if ((fpSrc = fopen(pszFinalPath, "r")) == NULL) {
        ceError = LwMapErrnoToLwError(errno);
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    if ((fpDst = fopen(pszTmpPath, "w")) == NULL) {
        ceError = LwMapErrnoToLwError(errno);
        BAIL_ON_CENTERIS_ERROR(ceError);
    }

    bRemoveFile = TRUE;

    while (1) {

        if (fgets(szBuf, 1024, fpSrc) == NULL) {
            if (feof(fpSrc)) {
                break;
            } else {
                ceError = LwMapErrnoToLwError(errno);
                BAIL_ON_CENTERIS_ERROR(ceError);
            }
        }

        if (!IsComment(szBuf) &&
            !regexec(&rx, szBuf, (size_t)0, NULL, 0)) {

            if (fprintf(fpDst, "%s=%s\n", pszName, pszValue) < 0) {
                ceError = LwMapErrnoToLwError(errno);
                BAIL_ON_CENTERIS_ERROR(ceError);
            }

        } else {

            if (fputs(szBuf, fpDst) == EOF) {
                ceError = LwMapErrnoToLwError(errno);
                BAIL_ON_CENTERIS_ERROR(ceError);
            }

        }

    }

    fclose(fpSrc); fpSrc = NULL;
    fclose(fpDst); fpDst = NULL;

    ceError = CTSafeReplaceFile(pszFinalPath, pszTmpPath);
    BAIL_ON_CENTERIS_ERROR(ceError);

    bRemoveFile = FALSE;

error:

    if (fpSrc)
        fclose(fpSrc);

    if (fpDst)
        fclose(fpDst);

    regfree(&rx);

    if (bRemoveFile)
        CTRemoveFile(pszTmpPath);

    CT_SAFE_FREE_STRING(pszTmpPath);
    CT_SAFE_FREE_STRING(pszFinalPath);

    return ceError;
}