import * as fs from 'fs' ; import * as path from 'path' ; import { promisify } from 'util' ; import { Shell } from "../../shell" ; import { Dictionary } from '../../utils/dictionary' ; import { baseInstallFolder } from "./installationlayout" ; const MITIGATIONS_FILE = 'mitigations.json' ; export async function fixOldInstalledBinaryPermissions ( shell ) { if ( ! shell . isUnix ( ) ) { return ; } if ( isMitigated ( shell ) ) { return ; } try { await fixAllBinaryPermissions ( baseInstallFolder ( shell ) ) ; recordMitigated ( shell ) ; } catch ( e ) { console . warn ( `Error trying to update permissions to installed binaries: ${ e }` ) ; } } const chmod = promisify ( fs . chmod ) ; const readdir = promisify ( fs . readdir ) ; const stat = promisify ( fs . stat ) ; async function fixAllBinaryPermissions ( folder ) { const entries = ( await readdir ( folder ) ) . map ( ( e ) => path . join ( folder , e ) ) ; for ( const entry of entries ) { const info = await stat ( entry ) ; if ( info . isDirectory ( ) ) { await fixAllBinaryPermissions ( entry ) ; } else if ( info . isFile ( ) ) { if ( ( info . mode & 0o777 ) === 0o777 ) { await chmod ( entry , 0o755 ) ; } } } } function readMitigations ( shell ) { const mitigationsFile = path . join ( baseInstallFolder ( shell ) , MITIGATIONS_FILE ) ; if ( ! fs . existsSync ( mitigationsFile ) ) { return { } ; } const mitigationsJSON = fs . readFileSync ( mitigationsFile , { encoding : 'utf8' } ) ; try { return JSON . parse ( mitigationsJSON ) ; } catch { return { } ; } } function writeMitigations ( shell , value ) { const mitigationsFile = path . join ( baseInstallFolder ( shell ) , MITIGATIONS_FILE ) ; try { fs . writeFileSync ( mitigationsFile , JSON . stringify ( value , undefined , 2 ) ) ; } catch ( e ) { console . log ( `Failed to record mitigation: ${ e }` ) ; } } function isMitigated ( shell ) { const mitigations = readMitigations ( shell ) ; return ! ! mitigations && ! ! mitigations [ 'permissions' ] ; } function recordMitigated ( shell ) { const mitigations = readMitigations ( shell ) ; mitigations [ 'permissions' ] = true ; writeMitigations ( shell , mitigations ) ; }