<commit_before>#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import json
import base64
import sys
import os
import traceback
import string
import random
from pwd import getpwnam

STATE_PREFIX="TTS_"
OVERRIDE_USER_NAME={{plugin_ssh_override_user}}
FULL_ACCESS=False


def list_params():
    RequestParams = [{'name':'public_key', 'description':'the public key to upload to the service',
                     'type':'textarea', 'mandatory':False}]
    ConfParams = [{'name':'full_access', 'type':'boolean', 'default': False},
                  {'name':'state_prefix', 'type':'string', 'default':'TTS_'},
                  {'name':'override_user_name', 'type':'boolean',
                   'default':{{plugin_ssh_override_user}} }]
    return json.dumps({'conf_params': ConfParams, 'request_params': RequestParams})

def create_ssh(UserName, Uid, Gid, HomeDir, Params):
    UserExists = does_user_exist(UserName,Uid,Gid,HomeDir)
    if UserExists:
        if Params.has_key('public_key'):
            return insert_ssh_key(UserName, HomeDir, Params['public_key'])
        else:
            return create_ssh_for(UserName,HomeDir)
    else:
        # dear admin, this is not the problem of tts
        return json.dumps({'error':'no_user'})


def revoke_ssh(UserName, Uid, Gid, HomeDir, State):
    UserExists = does_user_exist(UserName,Uid,Gid,HomeDir)
    if UserExists:
        return delete_ssh_for(UserName,HomeDir,State)
    else:
        # dear admin, this is not the problem of tts
        return json.dumps({'error':'no_user'})


def create_ssh_for(UserName,HomeDir):
    SshDir = create_ssh_dir(UserName,HomeDir)
    if SshDir == None:
        return json.dumps({'error':'ssh_dir_missing'})
    Password = <PASSWORD>()
    State = "%s%s"%(STATE_PREFIX,id_generator(32))
    # maybe change this to random/temp file
    OutputFile = os.path.join(SshDir,"tts_ssh_key")
    OutputPubFile = os.path.join(SshDir,"tts_ssh_key.pub")
    AuthorizedFile = os.path.join(SshDir,"authorized_keys")
    DelKey = "rm -f %s %s.pub > /dev/null"%(OutputFile,OutputFile)
    # DelKey = "srm -f %s %s.pub > /dev/null"%(OutputFile,OutputFile)
    # DelKey = "shred -f %s %s.pub > /dev/null"%(OutputFile,OutputFile)
    os.system(DelKey)
    Cmd = "ssh-keygen -N %s -C %s -f %s > /dev/null"%(Password,State,OutputFile)
    if os.system(Cmd) != 0:
        return json.dumps({'error':'keygen_failed'})

    PubKey = get_file_content(OutputPubFile)
    do_insert_key(SshDir, PubKey)

    PrivKey = get_file_content(OutputFile)
    os.system(DelKey)
    UserNameObj = {'name':'Username', 'type':'text', 'value':UserName}
    PrivKeyObj = {'name':'Private Key', 'type':'textfile', 'value':PrivKey, 'rows':30, 'cols':64}
    PasswdObj = {'name':'Passphrase (for Private Key)', 'type':'text', 'value':Password}
    Credential = [UserNameObj, PrivKeyObj, PasswdObj]
    return json.dumps({'credential':Credential, 'state':State})

def insert_ssh_key(UserName, HomeDir, InKey):
    SshDir = create_ssh_dir(UserName,HomeDir)
    if SshDir == None:
        return json.dumps({'error':'ssh_dir_missing'})
    State = "%s%s"%(STATE_PREFIX,id_generator(32))
    Key = set_key_state(InKey, State)
    do_insert_key(SshDir, Key)
    UserNameObj = {'name':'Username', 'type':'text', 'value':UserName}
    Credential = [UserNameObj]
    return json.dumps({'credential':Credential, 'state':State})

def set_key_state(Key, State):
    [KeyPart, KeyName] = Key.rsplit(" ",1)
    return "%s %s"%(KeyPart, State)


def do_insert_key(SshDir, Key):
    AuthorizedFile = os.path.join(SshDir,"authorized_keys")
    if FULL_ACCESS:
        Prepend='no-port-forwarding,no-X11-forwarding,no-agent-forwarding '
    else:
        #make this a really locked down ssh access
        Prepend='command="cat {{platform_etc_dir}}/services/ssh.msg",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty '
    Cmd = "echo '%s %s' >> %s"%(Prepend,Key,AuthorizedFile)
    os.system(Cmd)



def delete_ssh_for(UserName, HomeDir, State):
    SshDir = create_ssh_dir(UserName,HomeDir)
    if SshDir == None:
        return json.dumps({'error':'ssh_dir_missing'})<commit_msg>ssh now works with request params<commit_after>#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import json
import base64
import sys
import os
import traceback
import string
import random
from pwd import getpwnam

STATE_PREFIX="TTS_"
OVERRIDE_USER_NAME={{plugin_ssh_override_user}}
FULL_ACCESS=False


def list_params():
    RequestParams = [{'name':'public key', 'description':'the public key to upload to the service',
                     'type':'textarea', 'mandatory':False}]
    ConfParams = [{'name':'full_access', 'type':'boolean', 'default': False},
                  {'name':'state_prefix', 'type':'string', 'default':'TTS_'},
                  {'name':'override_user_name', 'type':'boolean',
                   'default':{{plugin_ssh_override_user}} }]
    return json.dumps({'conf_params': ConfParams, 'request_params': RequestParams})

def create_ssh(UserName, Uid, Gid, HomeDir, Params):
    UserExists = does_user_exist(UserName,Uid,Gid,HomeDir)
    if UserExists:
        if Params.has_key('public key'):
            return insert_ssh_key(UserName, HomeDir, Params['public key'])
        else:
            return create_ssh_for(UserName,HomeDir)
    else:
        # dear admin, this is not the problem of tts
        return json.dumps({'error':'no_user'})


def revoke_ssh(UserName, Uid, Gid, HomeDir, State):
    UserExists = does_user_exist(UserName,Uid,Gid,HomeDir)
    if UserExists:
        return delete_ssh_for(UserName,HomeDir,State)
    else:
        # dear admin, this is not the problem of tts
        return json.dumps({'error':'no_user'})


def create_ssh_for(UserName,HomeDir):
    SshDir = create_ssh_dir(UserName,HomeDir)
    if SshDir == None:
        return json.dumps({'error':'ssh_dir_missing'})
    Password = <PASSWORD>()
    State = "%s%s"%(STATE_PREFIX,id_generator(32))
    # maybe change this to random/temp file
    OutputFile = os.path.join(SshDir,"tts_ssh_key")
    OutputPubFile = os.path.join(SshDir,"tts_ssh_key.pub")
    AuthorizedFile = os.path.join(SshDir,"authorized_keys")
    DelKey = "rm -f %s %s.pub > /dev/null"%(OutputFile,OutputFile)
    # DelKey = "srm -f %s %s.pub > /dev/null"%(OutputFile,OutputFile)
    # DelKey = "shred -f %s %s.pub > /dev/null"%(OutputFile,OutputFile)
    os.system(DelKey)
    Cmd = "ssh-keygen -N %s -C %s -f %s > /dev/null"%(Password,State,OutputFile)
    if os.system(Cmd) != 0:
        return json.dumps({'error':'keygen_failed'})

    PubKey = validate_and_update_key(get_file_content(OutputPubFile), State)
    PrivKey = get_file_content(OutputFile)
    if PubKey == None:
        return json.dumps({'error':'bad_key'})

    do_insert_key(SshDir, PubKey)
    os.system(DelKey)
    UserNameObj = {'name':'Username', 'type':'text', 'value':UserName}
    PrivKeyObj = {'name':'Private Key', 'type':'textfile', 'value':PrivKey, 'rows':30, 'cols':64}
    PasswdObj = {'name':'Passphrase (for Private Key)', 'type':'text', 'value':Password}
    Credential = [UserNameObj, PrivKeyObj, PasswdObj]
    return json.dumps({'credential':Credential, 'state':State})

def insert_ssh_key(UserName, HomeDir, InKey):
    SshDir = create_ssh_dir(UserName,HomeDir)
    if SshDir == None:
        return json.dumps({'error':'ssh_dir_missing'})
    State = "%s%s"%(STATE_PREFIX,id_generator(32))
    Key = validate_and_update_key(InKey, State)
    if Key == None:
        return json.dumps({'error':'bad_key'})

    do_insert_key(SshDir, Key)
    UserNameObj = {'name':'Username', 'type':'text', 'value':UserName}
    Credential = [UserNameObj]
    return json.dumps({'credential':Credential, 'state':State})

def validate_and_update_key(Key, State):
    if len(Key) < 3:
        return None
    KeyParts = Key.split(" ")
    if len(KeyParts) != 3:
        return None
    KeyType = KeyParts[0]
    PubKey = KeyParts[1]
    if not KeyType.startswith("ssh-"):
        return None
    if len(PubKey) < 4:
        return None
    return "%s %s %s"%(KeyType, PubKey, State)


def do_insert_key(SshDir, Key):
    AuthorizedFile = os.path.join(SshDir,"authorized_keys")
    if FULL_ACCESS:
        Prepend='no-port-forwarding,no-X11-forwarding,no-agent-forwarding '
    else:
        #make this a really locked down ssh access
        Prepend='command="cat {{platform_etc_dir}}/services/ssh.msg",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty '
    Cmd = "echo '%s %s' >> %s"%(Prepend,Key,AuthorizedFile)
    os.system(Cmd)



def delete_ssh_for(UserName, HomeDir, State):
    SshDir = create_ssh_dir(UserName,HomeDir)
    if SshDir == None:
        return json.dumps({'error':'ssh_dir_missing'})
{'fraction_non_alphanumeric': 0.15045977011494252, 'fraction_numerical': 0.004597701149425287, 'mean_word_length': 3.9241652518392756, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3797143', 'n_tokens_mistral': 3129, 'n_tokens_neox': 2976, 'n_words': 590}