code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
package org.jf.smali;
import java.io.*;
import org.antlr.runtime.*;
import org.jf.util.*;
import static org.jf.smali.smaliParser.*;
%%
%public
%class smaliFlexLexer
%implements TokenSource
%implements LexerErrorInterface
%type Token
%unicode
%line
%column
%char
%{
private StringBuffer sb = new StringBuffer();
private String stringOrCharError = null;
private int stringStartLine;
private int stringStartCol;
private int stringStartChar;
private int lexerErrors = 0;
private File sourceFile;
private boolean suppressErrors;
public Token nextToken() {
try {
Token token = yylex();
if (token instanceof InvalidToken) {
InvalidToken invalidToken = (InvalidToken)token;
if (!suppressErrors) {
System.err.println(getErrorHeader(invalidToken) + " Error for input '" +
invalidToken.getText() + "': " + invalidToken.getMessage());
}
lexerErrors++;
}
return token;
}
catch (java.io.IOException e) {
System.err.println("shouldn't happen: " + e.getMessage());
return Token.EOF_TOKEN;
}
}
public void setLine(int line) {
this.yyline = line-1;
}
public void setColumn(int column) {
this.yycolumn = column;
}
public int getLine() {
return this.yyline+1;
}
public int getColumn() {
return this.yycolumn;
}
public void setSuppressErrors(boolean suppressErrors) {
this.suppressErrors = suppressErrors;
}
public void setSourceFile(File sourceFile) {
this.sourceFile = sourceFile;
}
public String getSourceName() {
if (sourceFile == null) {
return "";
}
try {
return PathUtil.getRelativeFile(new File("."), sourceFile).getPath();
} catch (IOException ex) {
return sourceFile.getAbsolutePath();
}
}
public int getNumberOfSyntaxErrors() {
return lexerErrors;
}
private Token newToken(int type, String text, boolean hidden) {
CommonToken token = new CommonToken(type, text);
if (hidden) {
token.setChannel(Token.HIDDEN_CHANNEL);
}
token.setStartIndex(yychar);
token.setStopIndex(yychar + yylength() - 1);
token.setLine(getLine());
token.setCharPositionInLine(getColumn());
return token;
}
private Token newToken(int type, String text) {
return newToken(type, text, false);
}
private Token newToken(int type, boolean hidden) {
return newToken(type, yytext(), hidden);
}
private Token newToken(int type) {
return newToken(type, yytext(), false);
}
private Token invalidToken(String message, String text) {
InvalidToken token = new InvalidToken(message, text);
token.setStartIndex(yychar);
token.setStopIndex(yychar + yylength() - 1);
token.setLine(getLine());
token.setCharPositionInLine(getColumn());
return token;
}
private Token invalidToken(String message) {
return invalidToken(message, yytext());
}
private void beginStringOrChar(int state) {
yybegin(state);
sb.setLength(0);
stringStartLine = getLine();
stringStartCol = getColumn();
stringStartChar = yychar;
stringOrCharError = null;
}
private Token endStringOrChar(int type) {
yybegin(YYINITIAL);
if (stringOrCharError != null) {
return invalidStringOrChar(stringOrCharError);
}
CommonToken token = new CommonToken(type, sb.toString());
token.setStartIndex(stringStartChar);
token.setStopIndex(yychar + yylength() - 1);
token.setLine(stringStartLine);
token.setCharPositionInLine(stringStartCol);
return token;
}
private void setStringOrCharError(String message) {
if (stringOrCharError == null) {
stringOrCharError = message;
}
}
private Token invalidStringOrChar(String message) {
yybegin(YYINITIAL);
InvalidToken token = new InvalidToken(message, sb.toString());
token.setStartIndex(stringStartChar);
token.setStopIndex(yychar + yylength() - 1);
token.setLine(stringStartLine);
token.setCharPositionInLine(stringStartCol);
return token;
}
public String getErrorHeader(InvalidToken token) {
return getSourceName()+"["+ token.getLine()+","+token.getCharPositionInLine()+"]";
}
%}
HexPrefix = 0 [xX]
HexDigit = [0-9a-fA-F]
HexDigits = [0-9a-fA-F]{4}
FewerHexDigits = [0-9a-fA-F]{0,3}
Integer1 = 0
Integer2 = [1-9] [0-9]*
Integer3 = 0 [0-7]+
Integer4 = {HexPrefix} {HexDigit}+
Integer = {Integer1} | {Integer2} | {Integer3} | {Integer4}
DecimalExponent = [eE] -? [0-9]+
BinaryExponent = [pP] -? [0-9]+
/*This can either be a floating point number or an identifier*/
FloatOrID1 = -? [0-9]+ {DecimalExponent}
FloatOrID2 = -? {HexPrefix} {HexDigit}+ {BinaryExponent}
FloatOrID3 = -? [iI][nN][fF][iI][nN][iI][tT][yY]
FloatOrID4 = [nN][aA][nN]
FloatOrID = {FloatOrID1} | {FloatOrID2} | {FloatOrID3} | {FloatOrID4}
/*This can only be a float and not an identifier, due to the decimal point*/
Float1 = -? [0-9]+ "." [0-9]* {DecimalExponent}?
Float2 = -? "." [0-9]+ {DecimalExponent}?
Float3 = -? {HexPrefix} {HexDigit}+ "." {HexDigit}* {BinaryExponent}
Float4 = -? {HexPrefix} "." {HexDigit}+ {BinaryExponent}
Float = {Float1} | {Float2} | {Float3} | {Float4}
HighSurrogate = [\ud800-\udbff]
LowSurrogate = [\udc00-\udfff]
SimpleNameCharacter = ({HighSurrogate} {LowSurrogate}) | [A-Za-z0-9$\-_\u00a1-\u1fff\u2010-\u2027\u2030-\ud7ff\ue000-\uffef]
SimpleName = {SimpleNameCharacter}+
PrimitiveType = [ZBSCIJFD]
ClassDescriptor = L ({SimpleName} "/")* {SimpleName} ;
ArrayDescriptor = "[" + ({PrimitiveType} | {ClassDescriptor})
Type = {PrimitiveType} | {ClassDescriptor} | {ArrayDescriptor}
%state STRING
%state CHAR
%%
/*Directives*/
<YYINITIAL>
{
".class" { return newToken(CLASS_DIRECTIVE); }
".super" { return newToken(SUPER_DIRECTIVE); }
".implements" { return newToken(IMPLEMENTS_DIRECTIVE); }
".source" { return newToken(SOURCE_DIRECTIVE); }
".field" { return newToken(FIELD_DIRECTIVE); }
".end field" { return newToken(END_FIELD_DIRECTIVE); }
".subannotation" { return newToken(SUBANNOTATION_DIRECTIVE); }
".end subannotation" { return newToken(END_SUBANNOTATION_DIRECTIVE); }
".annotation" { return newToken(ANNOTATION_DIRECTIVE); }
".end annotation" { return newToken(END_ANNOTATION_DIRECTIVE); }
".enum" { return newToken(ENUM_DIRECTIVE); }
".method" { return newToken(METHOD_DIRECTIVE); }
".end method" { return newToken(END_METHOD_DIRECTIVE); }
".registers" { return newToken(REGISTERS_DIRECTIVE); }
".locals" { return newToken(LOCALS_DIRECTIVE); }
".array-data" { return newToken(ARRAY_DATA_DIRECTIVE); }
".end array-data" { return newToken(END_ARRAY_DATA_DIRECTIVE); }
".packed-switch" { return newToken(PACKED_SWITCH_DIRECTIVE); }
".end packed-switch" { return newToken(END_PACKED_SWITCH_DIRECTIVE); }
".sparse-switch" { return newToken(SPARSE_SWITCH_DIRECTIVE); }
".end sparse-switch" { return newToken(END_SPARSE_SWITCH_DIRECTIVE); }
".catch" { return newToken(CATCH_DIRECTIVE); }
".catchall" { return newToken(CATCHALL_DIRECTIVE); }
".line" { return newToken(LINE_DIRECTIVE); }
".parameter" { return newToken(PARAMETER_DIRECTIVE); }
".end parameter" { return newToken(END_PARAMETER_DIRECTIVE); }
".local" { return newToken(LOCAL_DIRECTIVE); }
".end local" { return newToken(END_LOCAL_DIRECTIVE); }
".restart local" { return newToken(RESTART_LOCAL_DIRECTIVE); }
".prologue" { return newToken(PROLOGUE_DIRECTIVE); }
".epilogue" { return newToken(EPILOGUE_DIRECTIVE); }
".end" { return invalidToken("Invalid directive"); }
".end " [a-zA-z0-9\-_]+ { return invalidToken("Invalid directive"); }
".restart" { return invalidToken("Invalid directive"); }
".restart " [a-zA-z0-9\-_]+ { return invalidToken("Invalid directive"); }
}
/*Literals*/
<YYINITIAL> {
{Integer} { return newToken(POSITIVE_INTEGER_LITERAL); }
- {Integer} { return newToken(NEGATIVE_INTEGER_LITERAL); }
-? {Integer} [lL] { return newToken(LONG_LITERAL); }
-? {Integer} [sS] { return newToken(SHORT_LITERAL); }
-? {Integer} [tT] { return newToken(BYTE_LITERAL); }
{FloatOrID} [fF] | -? [0-9]+ [fF] { return newToken(FLOAT_LITERAL_OR_ID); }
{FloatOrID} [dD]? | -? [0-9]+ [dD] { return newToken(DOUBLE_LITERAL_OR_ID); }
{Float} [fF] { return newToken(FLOAT_LITERAL); }
{Float} [dD]? { return newToken(DOUBLE_LITERAL); }
"true"|"false" { return newToken(BOOL_LITERAL); }
"null" { return newToken(NULL_LITERAL); }
"\"" { beginStringOrChar(STRING); sb.append('"'); }
' { beginStringOrChar(CHAR); sb.append('\''); }
}
<STRING> {
"\"" { sb.append('"'); return endStringOrChar(STRING_LITERAL); }
[^\r\n\"\\]+ { sb.append(yytext()); }
"\\b" { sb.append('\b'); }
"\\t" { sb.append('\t'); }
"\\n" { sb.append('\n'); }
"\\f" { sb.append('\f'); }
"\\r" { sb.append('\r'); }
"\\'" { sb.append('\''); }
"\\\"" { sb.append('"'); }
"\\\\" { sb.append('\\'); }
"\\u" {HexDigits} { sb.append((char)Integer.parseInt(yytext().substring(2,6), 16)); }
"\\u" {FewerHexDigits} {
sb.append(yytext());
setStringOrCharError("Invalid \\u sequence. \\u must be followed by 4 hex digits");
}
"\\" [^btnfr'\"\\u] {
sb.append(yytext());
setStringOrCharError("Invalid escape sequence " + yytext());
}
[\r\n] { return invalidStringOrChar("Unterminated string literal"); }
<<EOF>> { return invalidStringOrChar("Unterminated string literal"); }
}
<CHAR> {
' {
sb.append('\'');
if (sb.length() == 2) {
return invalidStringOrChar("Empty character literal");
} else if (sb.length() > 3) {
return invalidStringOrChar("Character literal with multiple chars");
}
return endStringOrChar(CHAR_LITERAL);
}
[^\r\n'\\]+ { sb.append(yytext()); }
"\\b" { sb.append('\b'); }
"\\t" { sb.append('\t'); }
"\\n" { sb.append('\n'); }
"\\f" { sb.append('\f'); }
"\\r" { sb.append('\r'); }
"\\'" { sb.append('\''); }
"\\\"" { sb.append('"'); }
"\\\\" { sb.append('\\'); }
"\\u" {HexDigits} { sb.append((char)Integer.parseInt(yytext().substring(2,6), 16)); }
"\\u" {HexDigit}* {
sb.append(yytext());
setStringOrCharError("Invalid \\u sequence. \\u must be followed by exactly 4 hex digits");
}
"\\" [^btnfr'\"\\u] {
sb.append(yytext());
setStringOrCharError("Invalid escape sequence " + yytext());
}
[\r\n] { return invalidStringOrChar("Unterminated character literal"); }
<<EOF>> { return invalidStringOrChar("Unterminated character literal"); }
}
/*Misc*/
<YYINITIAL> {
[vp] [0-9]+ { return newToken(REGISTER); }
"build" | "runtime" | "system" {
return newToken(ANNOTATION_VISIBILITY);
}
"public" | "private" | "protected" | "static" | "final" | "synchronized" | "bridge" | "varargs" | "native" |
"abstract" | "strictfp" | "synthetic" | "constructor" | "declared-synchronized" | "interface" | "enum" |
"annotation" | "volatile" | "transient" {
return newToken(ACCESS_SPEC);
}
"no-error" | "generic-error" | "no-such-class" | "no-such-field" | "no-such-method" | "illegal-class-access" |
"illegal-field-access" | "illegal-method-access" | "class-change-error" | "instantiation-error" {
return newToken(VERIFICATION_ERROR_TYPE);
}
"inline@0x" {HexDigit}+ { return newToken(INLINE_INDEX); }
"vtable@0x" {HexDigit}+ { return newToken(VTABLE_INDEX); }
"field@0x" {HexDigit}+ { return newToken(FIELD_OFFSET); }
"+" {Integer} { return newToken(OFFSET); }
# [^\r\n]* { return newToken(LINE_COMMENT, true); }
}
/*Instructions*/
<YYINITIAL> {
"goto" {
return newToken(INSTRUCTION_FORMAT10t);
}
"return-void" | "nop" {
return newToken(INSTRUCTION_FORMAT10x);
}
"return-void-barrier" {
return newToken(INSTRUCTION_FORMAT10x_ODEX);
}
"const/4" {
return newToken(INSTRUCTION_FORMAT11n);
}
"move-result" | "move-result-wide" | "move-result-object" | "move-exception" | "return" | "return-wide" |
"return-object" | "monitor-enter" | "monitor-exit" | "throw" {
return newToken(INSTRUCTION_FORMAT11x);
}
"move" | "move-wide" | "move-object" | "array-length" | "neg-int" | "not-int" | "neg-long" | "not-long" |
"neg-float" | "neg-double" | "int-to-long" | "int-to-float" | "int-to-double" | "long-to-int" | "long-to-float" |
"long-to-double" | "float-to-int" | "float-to-long" | "float-to-double" | "double-to-int" | "double-to-long" |
"double-to-float" | "int-to-byte" | "int-to-char" | "int-to-short" {
return newToken(INSTRUCTION_FORMAT12x_OR_ID);
}
"add-int/2addr" | "sub-int/2addr" | "mul-int/2addr" | "div-int/2addr" | "rem-int/2addr" | "and-int/2addr" |
"or-int/2addr" | "xor-int/2addr" | "shl-int/2addr" | "shr-int/2addr" | "ushr-int/2addr" | "add-long/2addr" |
"sub-long/2addr" | "mul-long/2addr" | "div-long/2addr" | "rem-long/2addr" | "and-long/2addr" | "or-long/2addr" |
"xor-long/2addr" | "shl-long/2addr" | "shr-long/2addr" | "ushr-long/2addr" | "add-float/2addr" |
"sub-float/2addr" | "mul-float/2addr" | "div-float/2addr" | "rem-float/2addr" | "add-double/2addr" |
"sub-double/2addr" | "mul-double/2addr" | "div-double/2addr" | "rem-double/2addr" {
return newToken(INSTRUCTION_FORMAT12x);
}
"throw-verification-error" {
return newToken(INSTRUCTION_FORMAT20bc);
}
"goto/16" {
return newToken(INSTRUCTION_FORMAT20t);
}
"sget" | "sget-wide" | "sget-object" | "sget-boolean" | "sget-byte" | "sget-char" | "sget-short" | "sput" |
"sput-wide" | "sput-object" | "sput-boolean" | "sput-byte" | "sput-char" | "sput-short" {
return newToken(INSTRUCTION_FORMAT21c_FIELD);
}
"sget-volatile" | "sget-wide-volatile" | "sget-object-volatile" | "sput-volatile" | "sput-wide-volatile" |
"sput-object-volatile" {
return newToken(INSTRUCTION_FORMAT21c_FIELD_ODEX);
}
"const-string" {
return newToken(INSTRUCTION_FORMAT21c_STRING);
}
"check-cast" | "new-instance" | "const-class" {
return newToken(INSTRUCTION_FORMAT21c_TYPE);
}
"const/high16" | "const-wide/high16" {
return newToken(INSTRUCTION_FORMAT21h);
}
"const/16" | "const-wide/16" {
return newToken(INSTRUCTION_FORMAT21s);
}
"if-eqz" | "if-nez" | "if-ltz" | "if-gez" | "if-gtz" | "if-lez" {
return newToken(INSTRUCTION_FORMAT21t);
}
"add-int/lit8" | "rsub-int/lit8" | "mul-int/lit8" | "div-int/lit8" | "rem-int/lit8" | "and-int/lit8" |
"or-int/lit8" | "xor-int/lit8" | "shl-int/lit8" | "shr-int/lit8" | "ushr-int/lit8" {
return newToken(INSTRUCTION_FORMAT22b);
}
"iget" | "iget-wide" | "iget-object" | "iget-boolean" | "iget-byte" | "iget-char" | "iget-short" | "iput" |
"iput-wide" | "iput-object" | "iput-boolean" | "iput-byte" | "iput-char" | "iput-short" {
return newToken(INSTRUCTION_FORMAT22c_FIELD);
}
"iget-volatile" | "iget-wide-volatile" | "iget-object-volatile" | "iput-volatile" | "iput-wide-volatile" |
"iput-object-volatile" {
return newToken(INSTRUCTION_FORMAT22c_FIELD_ODEX);
}
"instance-of" | "new-array" {
return newToken(INSTRUCTION_FORMAT22c_TYPE);
}
"iget-quick" | "iget-wide-quick" | "iget-object-quick" | "iput-quick" | "iput-wide-quick" | "iput-object-quick" {
return newToken(INSTRUCTION_FORMAT22cs_FIELD);
}
"rsub-int" {
return newToken(INSTRUCTION_FORMAT22s_OR_ID);
}
"add-int/lit16" | "mul-int/lit16" | "div-int/lit16" | "rem-int/lit16" | "and-int/lit16" | "or-int/lit16" |
"xor-int/lit16" {
return newToken(INSTRUCTION_FORMAT22s);
}
"if-eq" | "if-ne" | "if-lt" | "if-ge" | "if-gt" | "if-le" {
return newToken(INSTRUCTION_FORMAT22t);
}
"move/from16" | "move-wide/from16" | "move-object/from16" {
return newToken(INSTRUCTION_FORMAT22x);
}
"cmpl-float" | "cmpg-float" | "cmpl-double" | "cmpg-double" | "cmp-long" | "aget" | "aget-wide" | "aget-object" |
"aget-boolean" | "aget-byte" | "aget-char" | "aget-short" | "aput" | "aput-wide" | "aput-object" | "aput-boolean" |
"aput-byte" | "aput-char" | "aput-short" | "add-int" | "sub-int" | "mul-int" | "div-int" | "rem-int" | "and-int" |
"or-int" | "xor-int" | "shl-int" | "shr-int" | "ushr-int" | "add-long" | "sub-long" | "mul-long" | "div-long" |
"rem-long" | "and-long" | "or-long" | "xor-long" | "shl-long" | "shr-long" | "ushr-long" | "add-float" |
"sub-float" | "mul-float" | "div-float" | "rem-float" | "add-double" | "sub-double" | "mul-double" | "div-double" |
"rem-double" {
return newToken(INSTRUCTION_FORMAT23x);
}
"goto/32" {
return newToken(INSTRUCTION_FORMAT30t);
}
"const-string/jumbo" {
return newToken(INSTRUCTION_FORMAT31c);
}
"const" {
return newToken(INSTRUCTION_FORMAT31i_OR_ID);
}
"const-wide/32" {
return newToken(INSTRUCTION_FORMAT31i);
}
"fill-array-data" | "packed-switch" | "sparse-switch" {
return newToken(INSTRUCTION_FORMAT31t);
}
"move/16" | "move-wide/16" | "move-object/16" {
return newToken(INSTRUCTION_FORMAT32x);
}
"invoke-virtual" | "invoke-super" | "invoke-direct" | "invoke-static" | "invoke-interface" {
return newToken(INSTRUCTION_FORMAT35c_METHOD);
}
"invoke-direct-empty" {
return newToken(INSTRUCTION_FORMAT35c_METHOD_ODEX);
}
"filled-new-array" {
return newToken(INSTRUCTION_FORMAT35c_TYPE);
}
"execute-inline" {
return newToken(INSTRUCTION_FORMAT35mi_METHOD);
}
"invoke-virtual-quick" | "invoke-super-quick" {
return newToken(INSTRUCTION_FORMAT35ms_METHOD);
}
"invoke-virtual/range" | "invoke-super/range" | "invoke-direct/range" | "invoke-static/range" |
"invoke-interface/range" {
return newToken(INSTRUCTION_FORMAT3rc_METHOD);
}
"invoke-object-init/range" {
return newToken(INSTRUCTION_FORMAT3rc_METHOD_ODEX);
}
"filled-new-array/range" {
return newToken(INSTRUCTION_FORMAT3rc_TYPE);
}
"execute-inline/range" {
return newToken(INSTRUCTION_FORMAT3rmi_METHOD);
}
"invoke-virtual-quick/range" | "invoke-super-quick/range" {
return newToken(INSTRUCTION_FORMAT3rms_METHOD);
}
"check-cast/jumbo" | "new-instance/jumbo" | "const-class/jumbo" {
return newToken(INSTRUCTION_FORMAT41c_TYPE);
}
"sget/jumbo" | "sget-wide/jumbo" | "sget-object/jumbo" | "sget-boolean/jumbo" | "sget-byte/jumbo" |
"sget-char/jumbo" | "sget-short/jumbo" | "sput/jumbo" | "sput-wide/jumbo" | "sput-object/jumbo" |
"sput-boolean/jumbo" | "sput-byte/jumbo" | "sput-char/jumbo" | "sput-short/jumbo" {
return newToken(INSTRUCTION_FORMAT41c_FIELD);
}
"sget-volatile/jumbo" | "sget-wide-volatile/jumbo" | "sget-object-volatile/jumbo" | "sput-volatile/jumbo" |
"sput-wide-volatile/jumbo" | "sput-object-volatile/jumbo" {
return newToken(INSTRUCTION_FORMAT41c_FIELD_ODEX);
}
"const-wide" {
return newToken(INSTRUCTION_FORMAT51l);
}
"instance-of/jumbo" | "new-array/jumbo" {
return newToken(INSTRUCTION_FORMAT52c_TYPE);
}
"iget/jumbo" | "iget-wide/jumbo" | "iget-object/jumbo" | "iget-boolean/jumbo" | "iget-byte/jumbo" |
"iget-char/jumbo" | "iget-short/jumbo" | "iput/jumbo" | "iput-wide/jumbo" | "iput-object/jumbo" |
"iput-boolean/jumbo" | "iput-byte/jumbo" | "iput-char/jumbo" | "iput-short/jumbo" {
return newToken(INSTRUCTION_FORMAT52c_FIELD);
}
"iget-volatile/jumbo" | "iget-wide-volatile/jumbo" | "iget-object-volatile/jumbo" | "iput-volatile/jumbo" |
"iput-wide-volatile/jumbo" | "iput-object-volatile/jumbo" {
return newToken(INSTRUCTION_FORMAT52c_FIELD_ODEX);
}
"invoke-virtual/jumbo" | "invoke-super/jumbo" | "invoke-direct/jumbo" | "invoke-static/jumbo" |
"invoke-interface/jumbo" {
return newToken(INSTRUCTION_FORMAT5rc_METHOD);
}
"invoke-object-init/jumbo" {
return newToken(INSTRUCTION_FORMAT5rc_METHOD_ODEX);
}
"filled-new-array/jumbo" {
return newToken(INSTRUCTION_FORMAT5rc_TYPE);
}
}
/*Types*/
<YYINITIAL> {
{PrimitiveType} { return newToken(PRIMITIVE_TYPE); }
V { return newToken(VOID_TYPE); }
{ClassDescriptor} { return newToken(CLASS_DESCRIPTOR); }
{ArrayDescriptor} { return newToken(ARRAY_DESCRIPTOR); }
{PrimitiveType} {PrimitiveType}+ { return newToken(PARAM_LIST_OR_ID); }
{Type} {Type}+ { return newToken(PARAM_LIST); }
{SimpleName} { return newToken(SIMPLE_NAME); }
"<init>" | "<clinit>" { return newToken(METHOD_NAME); }
}
/*Symbols/Whitespace/EOF*/
<YYINITIAL> {
".." { return newToken(DOTDOT); }
"->" { return newToken(ARROW); }
"=" { return newToken(EQUAL); }
":" { return newToken(COLON); }
"," { return newToken(COMMA); }
"{" { return newToken(OPEN_BRACE); }
"}" { return newToken(CLOSE_BRACE); }
"(" { return newToken(OPEN_PAREN); }
")" { return newToken(CLOSE_PAREN); }
[\r\n\t ]+ { return newToken(WHITE_SPACE, true); }
<<EOF>> { return newToken(EOF); }
}
/*catch all*/
<YYINITIAL> {
"." { return invalidToken("Invalid directive"); }
"." [a-zA-z\-_] { return invalidToken("Invalid directive"); }
"." [a-zA-z\-_] [a-zA-z0-9\-_]* { return invalidToken("Invalid directive"); }
. { return invalidToken("Invalid text"); }
}
|
zztobat-apktool
|
brut.apktool.smali/smali/src/main/jflex/smaliLexer.flex
|
JFlex
|
asf20
| 22,164
|
/*
* Game
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.gui;
/*
* The Game class creates the game window and HAS-A reference to everything.
* The main method is also found in this class.
*/
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JFrame;
import rafael.materla.logic.Board;
import rafael.materla.logic.Timer;
public class Game {
// ---INSTANCE-VARIABLES---------------------------------------------------/
private JFrame frame;
private Painter panel;
private Point screenMiddle;
private Point windowLocation;
private Board board;
private Timer clock;
// ---CONSTRUCTOR----------------------------------------------------------/
public Game(String name) {
board = new Board();
frame = new JFrame(name);
panel = new Painter();
clock = new Timer(board, panel);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
// ---MORE-COMPLEX-INITIALIZER-----------------------------------------/
{
// Calculates the middle of the users screen
screenMiddle = new Point(((int) Toolkit.getDefaultToolkit()
.getScreenSize().getWidth() / 2), ((int) Toolkit
.getDefaultToolkit().getScreenSize().getHeight() / 2));
// Calculates the position where the frame has to be so it is in the
// middle of the screen
windowLocation = new Point(
(int) (screenMiddle.getX() - (int) (frame.getSize()
.getWidth() / 2)), (int) screenMiddle.getY()
- (int) (frame.getSize().getHeight() / 2));
}
frame.setLocation(windowLocation);
frame.setVisible(true);
clock.start();
}
// ---MAIN-----------------------------------------------------------------/
public static void main(String[] args) {
new Game("Zzzzznake");
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/gui/Game.java
|
Java
|
asf20
| 1,882
|
/*
* Painter
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
import rafael.materla.logic.Board;
import rafael.materla.logic.Figure;
import rafael.materla.logic.SnakePart;
/*
* The Painter class gets the informations about the visual informations about
* the board and paints them to the users display.
*/
public class Painter extends JPanel {
// ---INSTANCE-VARIABLES---------------------------------------------------/
private static final long serialVersionUID = 3597547278483158168L;
// ---CONSTRUCTOR----------------------------------------------------------/
public Painter() {
addKeyListener(Board.getSnake());
setPreferredSize(Board.getBoardSize());
setBackground(Color.BLACK);
setFocusable(true);
setRequestFocusEnabled(true);
setDoubleBuffered(true);
setFont(new Font("GAME OVER", Font.BOLD, 2 * Board.CELL_LENGTH));
}
// ---METHODS--------------------------------------------------------------/
// TODO REFACTOR GAME OVER SCREEN
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (!Board.isGameOver()) {
paintTiles(g);
g.setColor(Color.PINK);
g.drawString("SCORE: " + ((SnakePart.getCount() - 3) * 100), 0, 30);
} else {
g.setColor(Color.RED);
g.drawString("GAME OVER",
(int) Board.getBoardSize().getWidth() / 3, (int) Board
.getBoardSize().getHeight() / 2);
g.setColor(Color.PINK);
g.drawString("SCORE: " + ((SnakePart.getCount() - 3) * 100), 0, 30);
}
}
private void paintTiles(Graphics g) {
for (Figure figure : Board.getTiles()) {
g.setColor(figure.getColor());
g.fillRect((figure.getX() * Board.CELL_LENGTH) + 1,
(figure.getY() * Board.CELL_LENGTH) + 1,
Board.CELL_LENGTH - 1, Board.CELL_LENGTH - 1);
}
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/gui/Painter.java
|
Java
|
asf20
| 1,967
|
/*
* Timer
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
import rafael.materla.gui.Painter;
/*
* The Timer class times the events that have to happen to make the game run
* (update board, paint it to the screen, wait, repeat)
* Mate. Feed. Kill. Repeat. $tay ($ic)
*/
public class Timer {
// ---INSTANCE-VARIABLES---------------------------------------------------/
private long lastFrame;
private Board boardReference;
private Painter painterReference;
// ---CONSTRUCTOR----------------------------------------------------------/
public Timer(Board boardObject, Painter painterObject) {
lastFrame = System.nanoTime();
boardReference = boardObject;
painterReference = painterObject;
}
// ---METHODS--------------------------------------------------------------/
public void start() {
while (true) {
if (lastFrame + 66000000 <= System.nanoTime()
&& !Board.isGameOver()) {
boardReference.updateTiles();
painterReference.repaint();
lastFrame = System.nanoTime();
} else if (Board.isGameOver()) {
painterReference.repaint();
}
}
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Timer.java
|
Java
|
asf20
| 1,189
|
/*
* Board
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
/*
* The Board class is the logical part of the game itself. It contains
* informations about the positions of every tile including the snake and also
* controles the movement and collision of same.
*/
public class Board {
// ---INSTANCE-VARIABLES---------------------------------------------------/
public static final int CELL_LENGTH = 20;
public static final int HORIZONTAL_CELLS = 35;
public static final int VERTICAL_CELLS = 25;
private static Snake snake;
private static ArrayList<Figure> tiles;
private static boolean gameIsOver = false;
// ---CONSTRUCTOR----------------------------------------------------------/
public Board() {
snake = new Snake();
tiles = new ArrayList<Figure>();
initBoard();
}
// ---GAME-METHODS--------------------------------------------------------------/
private void initBoard() {
addTile(new Apple());
addTiles(snake.getSnake());
}
void updateTiles() {
snake.move();
collide();
synchronizeTiles();
}
private void collide() {
if (!snake.isInsideBoard()) {
setGameOver();
} else {
for (Figure figure : getTiles()) {
if (figure.getPosition().equals(snake.getPosition())) {
if (figure instanceof Apple) {
removeTile(figure);
addTile(new Apple());
snake.grow();
} else if (figure instanceof Body) {
setGameOver();
}
}
}
}
}
// ---UTILITY-METHODS------------------------------------------------------/
private void addTile(Figure tile) {
tiles.add(tile);
}
private void addTiles(List<SnakePart> tileList) {
tiles.addAll(tileList);
}
private void removeTile(Figure tile) {
tiles.remove(tile);
}
private void synchronizeTiles() {
for (Figure snakePart : snake.getSnake()) {
boolean isEqual = false;
for (Figure figure : getTiles()) {
if (figure.equals(snakePart)) {
isEqual = true;
}
}
if (!isEqual) {
addTile(snakePart);
}
}
}
public int getHorizontalCells() {
return HORIZONTAL_CELLS;
}
public int getVerticalCells() {
return VERTICAL_CELLS;
}
public static ArrayList<Figure> getTiles() {
ArrayList<Figure> test = new ArrayList<Figure>();
test.addAll(tiles);
return test;
}
public int getCellLength() {
return CELL_LENGTH;
}
public static Dimension getBoardSize() {
Dimension boardSize = new Dimension(HORIZONTAL_CELLS * CELL_LENGTH,
VERTICAL_CELLS * CELL_LENGTH);
return boardSize;
}
public static Snake getSnake() {
return snake;
}
void setGameOver() {
gameIsOver = true;
}
public static boolean isGameOver() {
return gameIsOver;
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Board.java
|
Java
|
asf20
| 2,906
|
/*
* Figure
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
import java.awt.Color;
import java.awt.Point;
public abstract class Figure {
// ---INSTANCE-VARIABLES---------------------------------------------------/
protected Point position;
protected final Color figureColor;
protected String name;
// ---CONSTRUCTORS---------------------------------------------------------/
Figure(int x, int y, Color color) {
position = new Point(x, y);
figureColor = color;
}
Figure() {
this(0, 0, Color.WHITE);
}
// ---METHODS--------------------------------------------------------------/
protected void setPosition(int x, int y) {
position.setLocation(x, y);
}
protected void setPosition(Point position) {
position.setLocation(position);
}
protected Point getPosition() {
return position;
}
public int getX() {
return (int) position.getX();
}
public int getY() {
return (int) position.getY();
}
public boolean isInsideBoard() {
return (getX() >= 0 && getX() < Board.HORIZONTAL_CELLS)
&& (getY() >= 0 && getY() < Board.VERTICAL_CELLS);
}
public Color getColor() {
return figureColor;
}
public String getName() {
return name;
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Figure.java
|
Java
|
asf20
| 1,300
|
/*
* Head
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
import java.awt.Color;
final class Head extends SnakePart {
Directions direction;
Directions oldDirection;
// ---CONSTRUCTORS---------------------------------------------------------/
Head(int x, int y) {
super(x, y, Color.GREEN);
direction = Directions.NONE;
}
public Head() {
this(Board.HORIZONTAL_CELLS / 2, Board.VERTICAL_CELLS / 2);
}
// ---METHODS--------------------------------------------------------------/
@Override
void move() {
switch (direction) {
case NORTH:
moveUp();
break;
case EAST:
moveRight();
break;
case SOUTH:
moveDown();
break;
case WEST:
moveLeft();
break;
default:
break;
}
oldDirection = direction;
}
private void moveUp() {
setPosition(position.x, position.y - 1);
}
private void moveRight() {
setPosition(position.x + 1, position.y);
}
private void moveDown() {
setPosition(position.x, position.y + 1);
}
private void moveLeft() {
setPosition(position.x - 1, position.y);
}
void setDirection(Directions direction) {
this.direction = direction;
}
Directions getDirections() {
return oldDirection;
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Head.java
|
Java
|
asf20
| 1,311
|
/*
* Apple
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
import java.awt.Color;
public final class Apple extends Figure {
Apple(int x, int y) {
super(x, y, Color.RED);
}
Apple() {
super((int) (Math.random() * Board.HORIZONTAL_CELLS), (int) (Math
.random() * Board.VERTICAL_CELLS), Color.RED);
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Apple.java
|
Java
|
asf20
| 392
|
/*
* Body
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
import java.awt.Color;
import java.awt.Point;
final class Body extends SnakePart {
// ---CONSTRUCTORS---------------------------------------------------------/
Body(int x, int y) {
super(x, y, Color.GREEN);
}
Body(Point point) {
this(point.x, point.y);
}
// ---METHODS--------------------------------------------------------------/
void move(Point position) {
setPosition(position);
}
protected void setPosition(Point point) {
setOldPosition(position);
position.setLocation(point);
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Body.java
|
Java
|
asf20
| 658
|
/*
* Directions
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
/*
* Enum class containing the four constant directions the snake head is facing
* NORTH = snake moves up
* EAST = snake moves to the right
* SOUTH = snake moves down
* WEST = snake moves to the left
* NONE = start position for slowhead (Elia... xD)
*/
public enum Directions {
NORTH, EAST, SOUTH, WEST, NONE;
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Directions.java
|
Java
|
asf20
| 462
|
/*
* Snake
*
* Version 1.0.0
*
* 5/18/13
*
* Author: Rafael Materla
*/
package rafael.materla.logic;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.LinkedList;
public final class Snake implements KeyListener {
// ---INSTANCE-VARIABLES---------------------------------------------------/
private Head head;
private LinkedList<SnakePart> snake;
// ---CONSTRUCTORS---------------------------------------------------------/
public Snake(int x, int y) {
head = new Head(x, y);
snake = new LinkedList<SnakePart>();
snake.add(head);
grow();
grow();
}
public Snake() {
this(Board.HORIZONTAL_CELLS / 2, Board.VERTICAL_CELLS / 2);
}
// ---METHODS--------------------------------------------------------------/
void move() {
Point oldPartPosition = null;
for (SnakePart part : snake) {
if (part.getID() == 0) {
part.move();
oldPartPosition = part.getOldPosition();
} else {
part.setPosition(oldPartPosition);
oldPartPosition = part.getOldPosition();
}
}
}
void grow() {
snake.add(new Body(snake.get(SnakePart.getCount() - 1).getOldPosition()));
}
Head getHead() {
return head;
}
LinkedList<SnakePart> getSnake() {
return snake;
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (head.getDirections() != Directions.SOUTH) {
head.setDirection(Directions.NORTH);
}
break;
case KeyEvent.VK_RIGHT:
if (head.getDirections() != Directions.WEST) {
head.setDirection(Directions.EAST);
}
break;
case KeyEvent.VK_DOWN:
if (head.getDirections() != Directions.NORTH) {
head.setDirection(Directions.SOUTH);
}
break;
case KeyEvent.VK_LEFT:
if (head.getDirections() != Directions.EAST) {
head.setDirection(Directions.WEST);
}
break;
}
}
boolean isInsideBoard() {
return head.isInsideBoard();
}
Point getPosition() {
return head.getPosition();
}
// ---UNUSED-METHODS-------------------------------------------------------/
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
|
zzzznake
|
Zzzzznake/src/rafael/materla/logic/Snake.java
|
Java
|
asf20
| 2,360
|
%blur image and then subsample
function [output] = blurSubsample(input)
%simple average filter (low pass filter)
filterSize = 3;
blurFilter = ones(filterSize,filterSize) * 1/(filterSize*filterSize);
blurredImage = im2double(imfilter(input, blurFilter));
%scale output in half by sampling every other value
output = blurredImage(1:2:end,1:2:end,:);
end
|
zzj928-example-based-super-resolution
|
blurSubsample.m
|
MATLAB
|
asf20
| 354
|
%returns intermediate steps
function [subsampled interpolatedBicubic lowResImage] = prepareLowRes(input)
%simple lowpass/blur filter, all 1s/(size*size), keep size at 3
filterSize = 3;
blurFilter = ones(filterSize,filterSize) * 1/(filterSize*filterSize);
blurredImage = im2double(imfilter(input, blurFilter));
%subsample and interpolate
subsampled = blurredImage(1:2:end,1:2:end,:);
interpolatedBicubic = imresize(subsampled, 2.0, 'bicubic');
%simple high pass filter, all pass - low pass
highPassFilter = [0 0 0; 0 1 0; 0 0 0] - blurFilter;
filteredImage = imfilter(interpolatedBicubic, highPassFilter);
lowResImage = filteredImage;
end
|
zzj928-example-based-super-resolution
|
prepareLowRes.m
|
MATLAB
|
asf20
| 641
|
function buildTrainingSet(inputImageFileNames, saveFileName, alpha)
%c contains number of input files
[r c] = size(inputImageFileNames);
%training set is a huge set of key-value pairs
keys = [];
values = [];
%tic and toc are for time profiling in matlab
overallTicId = tic;
for i = 1:c
display(['Generating training set from image: ' inputImageFileNames{i}]);
tic;
[tKeys tValues] = train(inputImageFileNames{i}, alpha);
toc;
keys = [keys ; tKeys];
values = [values ; tValues];
end
display('Overall time:');
toc(overallTicId);
display('Saving file');
tic;
save(saveFileName, 'keys', 'values');
toc;
display('Done saving file');
|
zzj928-example-based-super-resolution
|
buildTrainingSet.m
|
MATLAB
|
asf20
| 661
|
function [keys values] = train(inputImage, alpha)
%read in input image
inputImage = im2double(imread(inputImage));
%perform preprocessing steps, blur/downsample/interpolate/highpass
[subsampled interpolatedSubsampled lowResImage] = prepareLowRes(inputImage);
highResImage = im2double(inputImage) - im2double(interpolatedSubsampled);
%make lowResPatches
[lowResPatches lowResRows, lowResCols] = make2dPatchMap(lowResImage, 7);
%DO NOT USE HIGH RES DIMENSIONS
[highResPatches highResRows, highResCols] = make2dPatchMap(highResImage, 5);
%create key/values based on patches
[keys values] = createVectors(alpha, lowResPatches, highResPatches, lowResRows, lowResCols);
end
|
zzj928-example-based-super-resolution
|
train.m
|
MATLAB
|
asf20
| 676
|
%creates the actual key and values from the patch information
function [key values] = createVectors(alpha, lowResPatches, highResPatches, numRows, numCols)
%key is a 58 pixel vector (for each color channel). 58 pixels includes all
%49 (7x7) pixels from low res patch, and the 9 pixels from first row and
%column of high res patch (5x5 pixels)
%the value is the whole high res patch
%1 1 1 1 1 1 1 1 1 1 1 1
%1 1 1 1 1 1 1 1 0 0 0 0
%1 1 1 1 1 1 1 1 0 0 0 0
%1 1 1 1 1 1 1 1 0 0 0 0
%1 1 1 1 1 1 1 1 0 0 0 0
%1 1 1 1 1 1 1
%1 1 1 1 1 1 1
%pixe
key = zeros(numRows*numCols, 174);%174 = 3(rgb) * (7*7(lowrespatch) + 9(highrespatch))
values = zeros(numRows*numCols, 5, 5, 3);
k = 1;
for i = 1:numRows
for j = 1:numCols
output = vectorize(alpha, lowResPatches, highResPatches, i,j);
%perform contrast normalization so training set is more
%general
scale = getContrastNormalizeScale(output);
output = output/scale;
key(k,:) = output;
values(k,:,:,:) = accessPatch(highResPatches, i+1, j+1)/scale;
k = k + 1;
end
end
end
|
zzj928-example-based-super-resolution
|
createVectors.m
|
MATLAB
|
asf20
| 1,164
|
%performs concatenation of 49 low res pixels to 9 high res pixels
%for more info, see top comments in createVectors.m
function output = vectorize(alpha, lowResPatches, highResPatches, i, j);
lowResPatch = accessPatch(lowResPatches, i,j); %7x7x3
highResPatch = accessPatch(highResPatches, i+1,j+1);
output = zeros(1,58,3);
for k = 1:3
highResOutput = [];
highResOutput = [highResPatch(1,:,k) highResPatch(2:end,1,k)'];
highResOutput = highResOutput * alpha;
output(:,:,k) = [reshape(lowResPatch(:,:,k), 1, []) highResOutput];
end
output = reshape(output, 1, 174);
end
|
zzj928-example-based-super-resolution
|
vectorize.m
|
MATLAB
|
asf20
| 590
|
function scale = getContrastNormalizeScale(input)
meanAbs = abs(mean(input(:)));
epsilon = 0.0001;
scale = meanAbs+epsilon;
end
|
zzj928-example-based-super-resolution
|
getContrastNormalizeScale.m
|
MATLAB
|
asf20
| 142
|
%function output = rebuildImage(kdTree, key2d, subSampledInput, lowResImage, highResImage, keys, values, lowResPatches, highResPatches, originalInput)
function [subsampled interpolated superResImage differenceInterpolated differenceSuperres originalHiRes] = rebuildImage(kdTree, subSampledInput, values, originalInput, alpha)
%recreate the low res image that you will be adding the difference to
backImage = im2double(imresize(subSampledInput, 2.0, 'bicubic'));
interpolatedSubSampledInput = backImage;
[r c d] = size(backImage);
%obtain high frequencies from the low res image
filterSize = 3;
blurFilter = ones(filterSize,filterSize) * 1/(filterSize*filterSize);
highPassFilter = [0 0 0; 0 1 0; 0 0 0] - blurFilter;
filteredImage = imfilter(backImage, highPassFilter);
%diff difference between low res and high passed version of the low res image
%it is added back to reconstructed image at the end
diff = backImage - filteredImage;
backImage = filteredImage;
%initialize reconstructed image
reconstructedImage = zeros(r,c,d);
endR = r-6;
endC = c-6;
%while (i + 6 < r)
for i = 1:4:endR
%print current percentage done
percentage = i/endR*100
for j = 1:4:endC
%get corresponding low res patch
patch49 = backImage(i:i+6, j:j+6, :);
%obtain current high res patch being built for extracting
%9 upper left values
patch25 = reconstructedImage((i+1):(i+5), (j+1):(j+5), :);
%concatenate patch so has 58 elements and becomes key
patch58 = zeros(58,3);
for k = 1:3
patch9 = [];
patch9 = [patch25(1,:,k) patch25(2:end,1,k)'];
patch9 = patch9*alpha;
patch58(:,k) = [reshape(patch49(:,:,k), 1, []) patch9];
end
patch58 = reshape(patch58, 1, 174);
%undo contrast normalize
scale = getContrastNormalizeScale(patch58);
patch58 = patch58 / scale;
%obtain the value
index = knnsearch(kdTree, patch58);
value(:,:,:) = values(index,:,:,:);
%add high res patch to the image being reconstructed
reconstructedImage((i+1):(i+5), (j+1):(j+5), :) = value*scale;
end
toc;
end
output = reconstructedImage+backImage+diff;
superResImage = output;
mkdir('output-images');
imwrite(subSampledInput, 'output-images/subsampled.jpg');
imwrite(interpolatedSubSampledInput, 'output-images/interpolated.jpg');
imwrite(superResImage, 'output-images/superRes.jpg');
imwrite(originalInput, 'output-images/original.jpg');
subsampled = subSampledInput;
interpolated = interpolatedSubSampledInput;
originalHiRes = originalInput;
%Get difference between superResImage and originalHiRes
differenceInterpolated = obtainDifference(originalInput, interpolatedSubSampledInput);
differenceSuperres = obtainDifference(originalInput, superResImage);
imwrite(differenceInterpolated, 'output-images/difference-interpolated.jpg');
imwrite(differenceSuperres, 'output-images/difference-superres.jpg');
end
|
zzj928-example-based-super-resolution
|
rebuildImage.m
|
MATLAB
|
asf20
| 2,930
|
%create an indexed array of patches based on input image
function [patches numRows numCols] = make2dPatchMap(input, patchSize)
[r c d] = size(input);
clippedRows = r-patchSize+1;
clippedCols = c-patchSize+1;
patches = (zeros(clippedRows, clippedCols, patchSize, patchSize, 3));
parfor i = 1:clippedRows
for j = 1:clippedCols
%offset by -1, since k and m start from 1
xOffset = i-1;
yOffset = j-1;
for k = 1:patchSize
for m = 1:patchSize
patches(i,j,k,m,:) = input(k+xOffset, m+yOffset,:);
end
end
end
end
numRows = clippedRows;
numCols = clippedCols;
end
|
zzj928-example-based-super-resolution
|
make2dPatchMap.m
|
MATLAB
|
asf20
| 675
|
%obtains the difference between two images, and scales
%it into a 0 to 255 gray level image
function difference = obtainDifference(input1, input2)
[r c d] = size(input1);
difference = zeros(r,c);
for i = 1:r
for j = 1:c
rDiff = input1(i,j,1) - input2(i,j,1);
gDiff = input1(i,j,2) - input2(i,j,2);
bDiff = input1(i,j,3) - input2(i,j,3);
distance = sqrt(rDiff*rDiff + gDiff*gDiff + bDiff*bDiff);
difference(i,j) = distance;
end
end
maxDiff = max(difference(:));
difference = difference / maxDiff;
difference = difference * 255;
difference = uint8(difference);
imshow(difference);
end
|
zzj928-example-based-super-resolution
|
obtainDifference.m
|
MATLAB
|
asf20
| 644
|
function [subsampled interpolated superResImage differenceInterp differenceSuperRes originaHiRes] = superResify(fileName, trueHighResImageName, alpha, bucketSize)
display('Loading training data');
tic;
load(fileName, 'keys', 'values');
toc;
display('Done loading training data');
display('Building kd tree ');
tic;
kdTree = KDTreeSearcher(keys, 'BucketSize', bucketSize);
toc;
display('Done building kd tree');
%convert original image to double version
doubleHighResImage = im2double(imread(trueHighResImageName));
%low frequency and subsampled version of original image to use
%for the actually super resolution and to compare results
subsampledInput = blurSubsample(doubleHighResImage);
display('Rebuilding image');
tic;
[subsampled interpolated superResImage differenceInterp differenceSuperRes originaHiRes] = rebuildImage(kdTree, subsampledInput, values, doubleHighResImage, alpha);
toc;
display('Done rebuilding image');
end
|
zzj928-example-based-super-resolution
|
superRes.m
|
MATLAB
|
asf20
| 936
|
%This file is the entry function for the GUI represented in the .fig file
function varargout = superResolutionGUI(varargin)
% SUPERRESOLUTION MATLAB code for superResolution.fig
% SUPERRESOLUTION, by itself, creates a new SUPERRESOLUTION or raises the existing
% singleton*.
%
% H = SUPERRESOLUTION returns the handle to a new SUPERRESOLUTION or the handle to
% the existing singleton*.
%
% SUPERRESOLUTION('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SUPERRESOLUTION.M with the given input arguments.
%
% SUPERRESOLUTION('Property','Value',...) creates a new SUPERRESOLUTION or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before superResolution_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to superResolution_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help superResolution
% Last Modified by GUIDE v2.5 05-Dec-2012 19:55:35
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @superResolution_OpeningFcn, ...
'gui_OutputFcn', @superResolution_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
end
% End initialization code - DO NOT EDIT
% --- Executes just before superResolution is made visible.
function superResolution_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to superResolution (see VARARGIN)
axes(handles.subsampled);
axis off;
axes(handles.interpolated);
axis off;
axes(handles.superRes);
axis off;
axes(handles.differenceInterp);
axis off;
axes(handles.differenceSuperres);
axis off;
axes(handles.originalHiRes);
axis off;
axes(handles.selectImage);
axis off;
% Choose default command line output for superResolution
handles.output = hObject;
guidata(hObject, handles);
global alpha;
alpha = .5444;
global bucketSize;
bucketSize = 50;
set(handles.alphaEdit, 'String', num2str(alpha));
set(handles.bucketSizeEdit, 'String', num2str(bucketSize));
end
% --- Outputs from this function are returned to the command line.
function varargout = superResolution_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
end
% --- Executes on button press in generateTrainingSet.
function generateTrainingSet_Callback(hObject, eventdata, handles)
% hObject handle to generateTrainingSet (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
existingImageNames = get(handles.trainingImages, 'String')
global alpha;
global bucketSize;
global saveFileName;
mkdir('training-data');
saveFileName = 'training-data/trainingData.mat';
buildTrainingSet(existingImageNames', saveFileName, alpha)
end
% --- Executes on button press in superResifyButton.
function superResifyButton_Callback(hObject, eventdata, handles)
% hObject handle to superResifyButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global alpha;
global bucketSize;
global saveFileName;
global inputImageName;
[subsampled interpolated superResImage differenceInterpolated differenceSuperres originalHiRes] = superRes(saveFileName, inputImageName, alpha, bucketSize);
axes(handles.selectImage);
cla;
imshow(im2double(imread(inputImageName)));
axes(handles.subsampled);
cla;
imshow(subsampled);
axes(handles.interpolated);
cla;
imshow(interpolated);
axes(handles.superRes);
cla;
imshow(superResImage);
axes(handles.differenceInterp);
cla;
imshow(uint8(differenceInterpolated));%hack for now
axes(handles.differenceSuperres);
cla;
imshow(uint8(differenceSuperres));%hack for now
axes(handles.originalHiRes);
cla;
imshow(originalHiRes);
end
% --- Executes on button press in selectImageButton.
function selectImageButton_Callback(hObject, eventdata, handles)
% hObject handle to selectImageButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename pathname] = uigetfile('*.*');
global inputImageName;
inputImageName = strcat(pathname, filename);
inputImage = im2double(imread(inputImageName));
axes(handles.selectImage);
cla;
imshow(inputImage);
end
% --- Executes on button press in addTrainingImage.
function addTrainingImage_Callback(hObject, eventdata, handles)
% hObject handle to addTrainingImage (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename pathname] = uigetfile('*.*');
existingImageNames = get(handles.trainingImages, 'String');
existingImageNames{end+1} = strcat(pathname, filename);
set(handles.trainingImages, 'String', existingImageNames);
end
function alphaEdit_Callback(hObject, eventdata, handles)
% hObject handle to alphaEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of alphaEdit as text
% str2double(get(hObject,'String')) returns contents of alphaEdit as a double
global alpha;
alpha = str2double(get(hObject, 'String'));
end
function bucketSizeEdit_Callback(hObject, eventdata, handles)
% hObject handle to bucketSizeEdit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of bucketSizeEdit as text
% str2double(get(hObject,'String')) returns contents of bucketSizeEdit as a double
global bucketSize;
bucketSize = str2double(get(hObject, 'String'));
end
% --- Executes on button press in resetButton.
function resetButton_Callback(hObject, eventdata, handles)
% hObject handle to resetButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
existingImageNames = get(handles.trainingImages, 'String');
existingImageNames = {};
set(handles.trainingImages, 'String', existingImageNames);
end
|
zzj928-example-based-super-resolution
|
superResolution.m
|
MATLAB
|
asf20
| 7,367
|
%simple array indexing for more readable code
function patch = accessPatch(patches, i, j)
patch(:,:,:) = patches(i,j,:,:,:);
end
|
zzj928-example-based-super-resolution
|
accessPatch.m
|
MATLAB
|
asf20
| 131
|
cmake_minimum_required(VERSION 2.4)
project(fbbs)
set(fbbs_VERSION_MAJOR 0)
set(fbbs_VERSION_MINOR 1)
set(fbbs_VERSION_PATCH 0)
if(COMMAND cmake_policy)
cmake_policy(SET CMP0003 NEW)
endif(COMMAND cmake_policy)
include_directories(include)
option(ENABLE_SSH "compile ssh module" off)
option(ENABLE_DEBUG "compile debug version" on)
option(ENABLE_WWW "compile www module" on)
set(CMAKE_C_FLAGS "-O2 -pipe -Wall")
if(ENABLE_DEBUG)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0")
endif(ENABLE_DEBUG)
set(CMAKE_INSTALL_PREFIX "/home/bbs")
set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/so")
add_subdirectory(lib)
add_subdirectory(pg)
add_subdirectory(src)
if(ENABLE_WWW)
add_subdirectory(www)
endif(ENABLE_WWW)
|
zzlydm-fbbs
|
CMakeLists.txt
|
CMake
|
gpl3
| 716
|
/*
* gzip.c - hooks for compression of packets
*
* This file is part of the SSH Library
*
* Copyright (c) 2003 by Aris Adamantiadis
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include "libssh/priv.h"
#include "libssh/buffer.h"
#include "libssh/session.h"
#if defined(HAVE_LIBZ) && defined(WITH_LIBZ)
#include <zlib.h>
#include <string.h>
#include <stdlib.h>
#define BLOCKSIZE 4092
static z_stream *initcompress(ssh_session session, int level) {
z_stream *stream = NULL;
int status;
stream = malloc(sizeof(z_stream));
if (stream == NULL) {
return NULL;
}
memset(stream, 0, sizeof(z_stream));
status = deflateInit(stream, level);
if (status != Z_OK) {
SAFE_FREE(stream);
ssh_set_error(session, SSH_FATAL,
"status %d inititalising zlib deflate", status);
return NULL;
}
return stream;
}
static ssh_buffer gzip_compress(ssh_session session,ssh_buffer source,int level){
z_stream *zout = session->current_crypto->compress_out_ctx;
void *in_ptr = buffer_get(source);
unsigned long in_size = buffer_get_len(source);
ssh_buffer dest = NULL;
static unsigned char out_buf[BLOCKSIZE] = {0};
unsigned long len;
int status;
if(zout == NULL) {
zout = session->current_crypto->compress_out_ctx = initcompress(session, level);
if (zout == NULL) {
return NULL;
}
}
dest = buffer_new();
if (dest == NULL) {
return NULL;
}
zout->next_out = out_buf;
zout->next_in = in_ptr;
zout->avail_in = in_size;
do {
zout->avail_out = BLOCKSIZE;
status = deflate(zout, Z_PARTIAL_FLUSH);
if (status != Z_OK) {
buffer_free(dest);
ssh_set_error(session, SSH_FATAL,
"status %d deflating zlib packet", status);
return NULL;
}
len = BLOCKSIZE - zout->avail_out;
if (buffer_add_data(dest, out_buf, len) < 0) {
buffer_free(dest);
return NULL;
}
zout->next_out = out_buf;
} while (zout->avail_out == 0);
return dest;
}
int compress_buffer(ssh_session session, ssh_buffer buf) {
ssh_buffer dest = NULL;
dest = gzip_compress(session, buf, 9);
if (dest == NULL) {
return -1;
}
if (buffer_reinit(buf) < 0) {
buffer_free(dest);
return -1;
}
if (buffer_add_data(buf, buffer_get(dest), buffer_get_len(dest)) < 0) {
buffer_free(dest);
return -1;
}
buffer_free(dest);
return 0;
}
/* decompression */
static z_stream *initdecompress(ssh_session session) {
z_stream *stream = NULL;
int status;
stream = malloc(sizeof(z_stream));
if (stream == NULL) {
return NULL;
}
memset(stream,0,sizeof(z_stream));
status = inflateInit(stream);
if (status != Z_OK) {
SAFE_FREE(stream);
ssh_set_error(session, SSH_FATAL,
"Status = %d initiating inflate context!", status);
return NULL;
}
return stream;
}
static ssh_buffer gzip_decompress(ssh_session session, ssh_buffer source, size_t maxlen) {
z_stream *zin = session->current_crypto->compress_in_ctx;
void *in_ptr = buffer_get_rest(source);
unsigned long in_size = buffer_get_rest_len(source);
static unsigned char out_buf[BLOCKSIZE] = {0};
ssh_buffer dest = NULL;
unsigned long len;
int status;
if (zin == NULL) {
zin = session->current_crypto->compress_in_ctx = initdecompress(session);
if (zin == NULL) {
return NULL;
}
}
dest = buffer_new();
if (dest == NULL) {
return NULL;
}
zin->next_out = out_buf;
zin->next_in = in_ptr;
zin->avail_in = in_size;
do {
zin->avail_out = BLOCKSIZE;
status = inflate(zin, Z_PARTIAL_FLUSH);
if (status != Z_OK) {
ssh_set_error(session, SSH_FATAL,
"status %d inflating zlib packet", status);
buffer_free(dest);
return NULL;
}
len = BLOCKSIZE - zin->avail_out;
if (buffer_add_data(dest,out_buf,len) < 0) {
buffer_free(dest);
return NULL;
}
if (buffer_get_len(dest) > maxlen){
/* Size of packet exceded, avoid a denial of service attack */
buffer_free(dest);
return NULL;
}
zin->next_out = out_buf;
} while (zin->avail_out == 0);
return dest;
}
int decompress_buffer(ssh_session session,ssh_buffer buf, size_t maxlen){
ssh_buffer dest = NULL;
dest = gzip_decompress(session,buf, maxlen);
if (dest == NULL) {
return -1;
}
if (buffer_reinit(buf) < 0) {
buffer_free(dest);
return -1;
}
if (buffer_add_data(buf, buffer_get(dest), buffer_get_len(dest)) < 0) {
buffer_free(dest);
return -1;
}
buffer_free(dest);
return 0;
}
#endif /* HAVE_LIBZ && WITH_LIBZ */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/gzip.c
|
C
|
gpl3
| 5,434
|
/*
* init.c - initialization and finalization of the library
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include "libssh/priv.h"
#include "libssh/socket.h"
#include "libssh/dh.h"
#ifdef _WIN32
#include <winsock2.h>
#endif
/**
* \addtogroup ssh_session
* @{
*/
/**
* @brief initialize global cryptographic data structures.
*
* This function should only be called once, at the beginning of the program, in
* the main thread. It may be omitted if your program is not multithreaded.
*
* @returns 0
*/
int ssh_init(void) {
if(ssh_crypto_init())
return -1;
if(ssh_socket_init())
return -1;
if(ssh_regex_init())
return -1;
return 0;
}
/**
* @brief Finalize and cleanup all libssh and cryptographic data structures.
*
* This function should only be called once, at the end of the program!
*
* @returns -1 in case of error
@returns 0 otherwise
*/
int ssh_finalize(void) {
ssh_regex_finalize();
ssh_crypto_finalize();
#ifdef HAVE_LIBGCRYPT
gcry_control(GCRYCTL_TERM_SECMEM);
#elif defined HAVE_LIBCRYPTO
EVP_cleanup();
#endif
#ifdef _WIN32
WSACleanup();
#endif
return 0;
}
/**
* @}
*/
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/init.c
|
C
|
gpl3
| 2,023
|
/*
* sftpserver.c - server based function for the sftp protocol
*
* This file is part of the SSH Library
*
* Copyright (c) 2005 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/libssh.h"
#include "libssh/sftp.h"
#include "libssh/ssh2.h"
#include "libssh/priv.h"
#include "libssh/buffer.h"
#include "libssh/misc.h"
sftp_client_message sftp_get_client_message(sftp_session sftp) {
sftp_packet packet;
sftp_client_message msg;
ssh_buffer payload;
ssh_string tmp;
msg = malloc(sizeof (struct sftp_client_message_struct));
if (msg == NULL) {
return NULL;
}
ZERO_STRUCTP(msg);
packet = sftp_packet_read(sftp);
if (packet == NULL) {
sftp_client_message_free(msg);
return NULL;
}
payload = packet->payload;
msg->type = packet->type;
msg->sftp = sftp;
buffer_get_u32(payload, &msg->id);
switch(msg->type) {
case SSH_FXP_CLOSE:
case SSH_FXP_READDIR:
msg->handle = buffer_get_ssh_string(payload);
if (msg->handle == NULL) {
sftp_client_message_free(msg);
return NULL;
}
break;
case SSH_FXP_READ:
msg->handle = buffer_get_ssh_string(payload);
if (msg->handle == NULL) {
sftp_client_message_free(msg);
return NULL;
}
buffer_get_u64(payload, &msg->offset);
buffer_get_u32(payload, &msg->len);
break;
case SSH_FXP_WRITE:
msg->handle = buffer_get_ssh_string(payload);
if (msg->handle == NULL) {
sftp_client_message_free(msg);
return NULL;
}
buffer_get_u64(payload, &msg->offset);
msg->data = buffer_get_ssh_string(payload);
if (msg->data == NULL) {
sftp_client_message_free(msg);
return NULL;
}
break;
case SSH_FXP_REMOVE:
case SSH_FXP_RMDIR:
case SSH_FXP_OPENDIR:
case SSH_FXP_READLINK:
case SSH_FXP_REALPATH:
tmp = buffer_get_ssh_string(payload);
if (tmp == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->filename = string_to_char(tmp);
string_free(tmp);
if (msg->filename == NULL) {
sftp_client_message_free(msg);
return NULL;
}
break;
case SSH_FXP_RENAME:
case SSH_FXP_SYMLINK:
tmp = buffer_get_ssh_string(payload);
if (tmp == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->filename = string_to_char(tmp);
string_free(tmp);
if (msg->filename == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->data = buffer_get_ssh_string(payload);
if (msg->data == NULL) {
sftp_client_message_free(msg);
return NULL;
}
break;
case SSH_FXP_MKDIR:
case SSH_FXP_SETSTAT:
tmp = buffer_get_ssh_string(payload);
if (tmp == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->filename=string_to_char(tmp);
string_free(tmp);
if (msg->filename == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->attr = sftp_parse_attr(sftp, payload, 0);
if (msg->attr == NULL) {
sftp_client_message_free(msg);
return NULL;
}
break;
case SSH_FXP_FSETSTAT:
msg->handle = buffer_get_ssh_string(payload);
if (msg->handle == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->attr = sftp_parse_attr(sftp, payload, 0);
if (msg->attr == NULL) {
sftp_client_message_free(msg);
return NULL;
}
break;
case SSH_FXP_LSTAT:
case SSH_FXP_STAT:
tmp = buffer_get_ssh_string(payload);
if (tmp == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->filename = string_to_char(tmp);
string_free(tmp);
if (msg->filename == NULL) {
sftp_client_message_free(msg);
return NULL;
}
if(sftp->version > 3) {
buffer_get_u32(payload,&msg->flags);
}
break;
case SSH_FXP_OPEN:
tmp=buffer_get_ssh_string(payload);
if (tmp == NULL) {
sftp_client_message_free(msg);
return NULL;
}
msg->filename = string_to_char(tmp);
string_free(tmp);
if (msg->filename == NULL) {
sftp_client_message_free(msg);
return NULL;
}
buffer_get_u32(payload,&msg->flags);
msg->attr = sftp_parse_attr(sftp, payload, 0);
if (msg->attr == NULL) {
sftp_client_message_free(msg);
return NULL;
}
case SSH_FXP_FSTAT:
msg->handle = buffer_get_ssh_string(payload);
if (msg->handle == NULL) {
sftp_client_message_free(msg);
return NULL;
}
buffer_get_u32(payload, &msg->flags);
break;
default:
fprintf(stderr, "Received unhandled sftp message %d\n", msg->type);
}
msg->flags = ntohl(msg->flags);
msg->offset = ntohll(msg->offset);
msg->len = ntohl(msg->len);
sftp_packet_free(packet);
return msg;
}
void sftp_client_message_free(sftp_client_message msg) {
if (msg == NULL) {
return;
}
SAFE_FREE(msg->filename);
string_free(msg->data);
string_free(msg->handle);
sftp_attributes_free(msg->attr);
ZERO_STRUCTP(msg);
SAFE_FREE(msg);
}
int sftp_reply_name(sftp_client_message msg, const char *name,
sftp_attributes attr) {
ssh_buffer out;
ssh_string file;
out = buffer_new();
if (out == NULL) {
return -1;
}
file = string_from_char(name);
if (file == NULL) {
buffer_free(out);
return -1;
}
if (buffer_add_u32(out, msg->id) < 0 ||
buffer_add_u32(out, htonl(1)) < 0 ||
buffer_add_ssh_string(out, file) < 0 ||
buffer_add_ssh_string(out, file) < 0 || /* The protocol is broken here between 3 & 4 */
buffer_add_attributes(out, attr) < 0 ||
sftp_packet_write(msg->sftp, SSH_FXP_NAME, out) < 0) {
buffer_free(out);
string_free(file);
return -1;
}
buffer_free(out);
string_free(file);
return 0;
}
int sftp_reply_handle(sftp_client_message msg, ssh_string handle){
ssh_buffer out;
out = buffer_new();
if (out == NULL) {
return -1;
}
if (buffer_add_u32(out, msg->id) < 0 ||
buffer_add_ssh_string(out, handle) < 0 ||
sftp_packet_write(msg->sftp, SSH_FXP_HANDLE, out) < 0) {
buffer_free(out);
return -1;
}
buffer_free(out);
return 0;
}
int sftp_reply_attr(sftp_client_message msg, sftp_attributes attr) {
ssh_buffer out;
out = buffer_new();
if (out == NULL) {
return -1;
}
if (buffer_add_u32(out, msg->id) < 0 ||
buffer_add_attributes(out, attr) < 0 ||
sftp_packet_write(msg->sftp, SSH_FXP_ATTRS, out) < 0) {
buffer_free(out);
return -1;
}
buffer_free(out);
return 0;
}
int sftp_reply_names_add(sftp_client_message msg, const char *file,
const char *longname, sftp_attributes attr) {
ssh_string name;
name = string_from_char(file);
if (name == NULL) {
return -1;
}
if (msg->attrbuf == NULL) {
msg->attrbuf = buffer_new();
if (msg->attrbuf == NULL) {
string_free(name);
return -1;
}
}
if (buffer_add_ssh_string(msg->attrbuf, name) < 0) {
string_free(name);
return -1;
}
string_free(name);
name = string_from_char(longname);
if (name == NULL) {
return -1;
}
if (buffer_add_ssh_string(msg->attrbuf,name) < 0 ||
buffer_add_attributes(msg->attrbuf,attr) < 0) {
string_free(name);
return -1;
}
string_free(name);
msg->attr_num++;
return 0;
}
int sftp_reply_names(sftp_client_message msg) {
ssh_buffer out;
out = buffer_new();
if (out == NULL) {
buffer_free(msg->attrbuf);
return -1;
}
if (buffer_add_u32(out, msg->id) < 0 ||
buffer_add_u32(out, htonl(msg->attr_num)) < 0 ||
buffer_add_data(out, buffer_get(msg->attrbuf),
buffer_get_len(msg->attrbuf)) < 0 ||
sftp_packet_write(msg->sftp, SSH_FXP_NAME, out) < 0) {
buffer_free(out);
buffer_free(msg->attrbuf);
return -1;
}
buffer_free(out);
buffer_free(msg->attrbuf);
msg->attr_num = 0;
msg->attrbuf = NULL;
return 0;
}
int sftp_reply_status(sftp_client_message msg, uint32_t status,
const char *message) {
ssh_buffer out;
ssh_string s;
out = buffer_new();
if (out == NULL) {
return -1;
}
s = string_from_char(message ? message : "");
if (s == NULL) {
buffer_free(out);
return -1;
}
if (buffer_add_u32(out, msg->id) < 0 ||
buffer_add_u32(out, htonl(status)) < 0 ||
buffer_add_ssh_string(out, s) < 0 ||
buffer_add_u32(out, 0) < 0 || /* language string */
sftp_packet_write(msg->sftp, SSH_FXP_STATUS, out) < 0) {
buffer_free(out);
string_free(s);
return -1;
}
buffer_free(out);
string_free(s);
return 0;
}
int sftp_reply_data(sftp_client_message msg, const void *data, int len) {
ssh_buffer out;
out = buffer_new();
if (out == NULL) {
return -1;
}
if (buffer_add_u32(out, msg->id) < 0 ||
buffer_add_u32(out, ntohl(len)) < 0 ||
buffer_add_data(out, data, len) < 0 ||
sftp_packet_write(msg->sftp, SSH_FXP_DATA, out) < 0) {
buffer_free(out);
return -1;
}
buffer_free(out);
return 0;
}
/*
* This function will return you a new handle to give the client.
* the function accepts an info that can be retrieved later with
* the handle. Care is given that a corrupted handle won't give a
* valid info (or worse).
*/
ssh_string sftp_handle_alloc(sftp_session sftp, void *info) {
ssh_string ret;
uint32_t val;
int i;
if (sftp->handles == NULL) {
sftp->handles = malloc(sizeof(void *) * SFTP_HANDLES);
if (sftp->handles == NULL) {
return NULL;
}
memset(sftp->handles, 0, sizeof(void *) * SFTP_HANDLES);
}
for (i = 0; i < SFTP_HANDLES; i++) {
if (sftp->handles[i] == NULL) {
break;
}
}
if (i == SFTP_HANDLES) {
return NULL; /* no handle available */
}
val = i;
ret = string_new(4);
if (ret == NULL) {
return NULL;
}
memcpy(string_data(ret), &val, sizeof(uint32_t));
sftp->handles[i] = info;
return ret;
}
void *sftp_handle(sftp_session sftp, ssh_string handle){
uint32_t val;
if (sftp->handles == NULL) {
return NULL;
}
if (string_len(handle) != sizeof(uint32_t)) {
return NULL;
}
memcpy(&val, string_data(handle), sizeof(uint32_t));
if (val > SFTP_HANDLES) {
return NULL;
}
return sftp->handles[val];
}
void sftp_handle_remove(sftp_session sftp, void *handle) {
int i;
for (i = 0; i < SFTP_HANDLES; i++) {
if (sftp->handles[i] == handle) {
sftp->handles[i] = NULL;
break;
}
}
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/sftpserver.c
|
C
|
gpl3
| 11,574
|
/*
* crypt.c - blowfish-cbc code
*
* This file is part of the SSH Library
*
* Copyright (c) 2003 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#ifdef OPENSSL_CRYPTO
#include <openssl/blowfish.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#endif
#include "libssh/priv.h"
#include "libssh/session.h"
#include "libssh/wrapper.h"
#include "libssh/crypto.h"
uint32_t packet_decrypt_len(ssh_session session, char *crypted){
uint32_t decrypted;
if (session->current_crypto) {
if (packet_decrypt(session, crypted,
session->current_crypto->in_cipher->blocksize) < 0) {
return 0;
}
}
memcpy(&decrypted,crypted,sizeof(decrypted));
ssh_log(session, SSH_LOG_PACKET,
"Packet size decrypted: %lu (0x%lx)",
(long unsigned int) ntohl(decrypted),
(long unsigned int) ntohl(decrypted));
return ntohl(decrypted);
}
int packet_decrypt(ssh_session session, void *data,uint32_t len) {
struct crypto_struct *crypto = session->current_crypto->in_cipher;
char *out = NULL;
if(len % session->current_crypto->in_cipher->blocksize != 0){
ssh_set_error(session, SSH_FATAL, "Cryptographic functions must be set on at least one blocksize (received %d)",len);
return SSH_ERROR;
}
out = malloc(len);
if (out == NULL) {
return -1;
}
ssh_log(session,SSH_LOG_PACKET, "Decrypting %d bytes", len);
#ifdef HAVE_LIBGCRYPT
if (crypto->set_decrypt_key(crypto, session->current_crypto->decryptkey,
session->current_crypto->decryptIV) < 0) {
SAFE_FREE(out);
return -1;
}
crypto->cbc_decrypt(crypto,data,out,len);
#elif defined HAVE_LIBCRYPTO
if (crypto->set_decrypt_key(crypto, session->current_crypto->decryptkey) < 0) {
SAFE_FREE(out);
return -1;
}
crypto->cbc_decrypt(crypto,data,out,len,session->current_crypto->decryptIV);
#endif
memcpy(data,out,len);
memset(out,0,len);
SAFE_FREE(out);
return 0;
}
unsigned char *packet_encrypt(ssh_session session, void *data, uint32_t len) {
struct crypto_struct *crypto = NULL;
HMACCTX ctx = NULL;
char *out = NULL;
unsigned int finallen;
uint32_t seq;
if (!session->current_crypto) {
return NULL; /* nothing to do here */
}
if(len % session->current_crypto->in_cipher->blocksize != 0){
ssh_set_error(session, SSH_FATAL, "Cryptographic functions must be set on at least one blocksize (received %d)",len);
return NULL;
}
out = malloc(len);
if (out == NULL) {
return NULL;
}
seq = ntohl(session->send_seq);
crypto = session->current_crypto->out_cipher;
ssh_log(session, SSH_LOG_PACKET,
"Encrypting packet with seq num: %d, len: %d",
session->send_seq,len);
#ifdef HAVE_LIBGCRYPT
if (crypto->set_encrypt_key(crypto, session->current_crypto->encryptkey,
session->current_crypto->encryptIV) < 0) {
SAFE_FREE(out);
return NULL;
}
#elif defined HAVE_LIBCRYPTO
if (crypto->set_encrypt_key(crypto, session->current_crypto->encryptkey) < 0) {
SAFE_FREE(out);
return NULL;
}
#endif
if (session->version == 2) {
ctx = hmac_init(session->current_crypto->encryptMAC,20,HMAC_SHA1);
if (ctx == NULL) {
SAFE_FREE(out);
return NULL;
}
hmac_update(ctx,(unsigned char *)&seq,sizeof(uint32_t));
hmac_update(ctx,data,len);
hmac_final(ctx,session->current_crypto->hmacbuf,&finallen);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("mac: ",data,len);
if (finallen != 20) {
printf("Final len is %d\n",finallen);
}
ssh_print_hexa("Packet hmac", session->current_crypto->hmacbuf, 20);
#endif
}
#ifdef HAVE_LIBGCRYPT
crypto->cbc_encrypt(crypto, data, out, len);
#elif defined HAVE_LIBCRYPTO
crypto->cbc_encrypt(crypto, data, out, len,
session->current_crypto->encryptIV);
#endif
memcpy(data, out, len);
memset(out, 0, len);
SAFE_FREE(out);
if (session->version == 2) {
return session->current_crypto->hmacbuf;
}
return NULL;
}
/**
* @internal
*
* @brief Verify the hmac of a packet
*
* @param session The session to use.
* @param buffer The buffer to verify the hmac from.
* @param mac The mac to compare with the hmac.
*
* @return 0 if hmac and mac are equal, < 0 if not or an error
* occured.
*/
int packet_hmac_verify(ssh_session session, ssh_buffer buffer,
unsigned char *mac) {
unsigned char hmacbuf[EVP_MAX_MD_SIZE] = {0};
HMACCTX ctx;
unsigned int len;
uint32_t seq;
ctx = hmac_init(session->current_crypto->decryptMAC, 20, HMAC_SHA1);
if (ctx == NULL) {
return -1;
}
seq = htonl(session->recv_seq);
hmac_update(ctx, (unsigned char *) &seq, sizeof(uint32_t));
hmac_update(ctx, buffer_get(buffer), buffer_get_len(buffer));
hmac_final(ctx, hmacbuf, &len);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("received mac",mac,len);
ssh_print_hexa("Computed mac",hmacbuf,len);
ssh_print_hexa("seq",(unsigned char *)&seq,sizeof(uint32_t));
#endif
if (memcmp(mac, hmacbuf, len) == 0) {
return 0;
}
return -1;
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/crypt.c
|
C
|
gpl3
| 5,931
|
/*
* crc32.c - simple CRC32 code
*
* This file is part of the SSH Library
*
* Copyright (c) 2005 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "libssh/priv.h"
static uint32_t crc_table[] = {
0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
0x2d02ef8dUL
};
uint32_t ssh_crc32(const char *buf, uint32_t len) {
uint32_t ret = 0;
while(len > 0) {
ret = crc_table[(ret ^ *buf) & 0xff] ^ (ret >> 8);
--len;
++buf;
}
return ret;
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/crc32.c
|
C
|
gpl3
| 4,879
|
/*
* sftp.c - Secure FTP functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2005-2008 by Aris Adamantiadis
* Copyright (c) 2008-2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/* This file contains code written by Nick Zitzmann */
#include <errno.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
#include <arpa/inet.h>
#else
#define S_IFSOCK 0140000
#define S_IFLNK 0120000
#ifdef _MSC_VER
#define S_IFBLK 0060000
#define S_IFIFO 0010000
#endif
#endif
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/sftp.h"
#include "libssh/buffer.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#include "libssh/misc.h"
#ifdef WITH_SFTP
#define sftp_enter_function() _enter_function(sftp->channel->session)
#define sftp_leave_function() _leave_function(sftp->channel->session)
struct sftp_ext_struct {
unsigned int count;
char **name;
char **data;
};
/* functions */
static int sftp_enqueue(sftp_session session, sftp_message msg);
static void sftp_message_free(sftp_message msg);
static void sftp_set_error(sftp_session sftp, int errnum);
static void status_msg_free(sftp_status_message status);
static sftp_ext sftp_ext_new(void) {
sftp_ext ext;
ext = malloc(sizeof(struct sftp_ext_struct));
if (ext == NULL) {
return NULL;
}
ZERO_STRUCTP(ext);
return ext;
}
static void sftp_ext_free(sftp_ext ext) {
unsigned int i;
if (ext == NULL) {
return;
}
if (ext->count) {
for (i = 0; i < ext->count; i++) {
SAFE_FREE(ext->name[i]);
SAFE_FREE(ext->data[i]);
}
SAFE_FREE(ext->name);
SAFE_FREE(ext->data);
}
SAFE_FREE(ext);
}
sftp_session sftp_new(ssh_session session){
sftp_session sftp;
enter_function();
if (session == NULL) {
leave_function();
return NULL;
}
sftp = malloc(sizeof(struct sftp_session_struct));
if (sftp == NULL) {
ssh_set_error_oom(session);
leave_function();
return NULL;
}
ZERO_STRUCTP(sftp);
sftp->ext = sftp_ext_new();
if (sftp->ext == NULL) {
ssh_set_error_oom(session);
SAFE_FREE(sftp);
sftp_leave_function();
return NULL;
}
sftp->session = session;
sftp->channel = channel_new(session);
if (sftp->channel == NULL) {
SAFE_FREE(sftp);
leave_function();
return NULL;
}
if (channel_open_session(sftp->channel)) {
channel_free(sftp->channel);
SAFE_FREE(sftp);
leave_function();
return NULL;
}
if (channel_request_sftp(sftp->channel)) {
sftp_free(sftp);
leave_function();
return NULL;
}
leave_function();
return sftp;
}
#ifdef WITH_SERVER
sftp_session sftp_server_new(ssh_session session, ssh_channel chan){
sftp_session sftp = NULL;
sftp = malloc(sizeof(struct sftp_session_struct));
if (sftp == NULL) {
ssh_set_error_oom(session);
return NULL;
}
ZERO_STRUCTP(sftp);
sftp->session = session;
sftp->channel = chan;
return sftp;
}
int sftp_server_init(sftp_session sftp){
ssh_session session = sftp->session;
sftp_packet packet = NULL;
ssh_buffer reply = NULL;
uint32_t version;
sftp_enter_function();
packet = sftp_packet_read(sftp);
if (packet == NULL) {
sftp_leave_function();
return -1;
}
if (packet->type != SSH_FXP_INIT) {
ssh_set_error(session, SSH_FATAL,
"Packet read of type %d instead of SSH_FXP_INIT",
packet->type);
sftp_packet_free(packet);
sftp_leave_function();
return -1;
}
ssh_log(session, SSH_LOG_PACKET, "Received SSH_FXP_INIT");
buffer_get_u32(packet->payload, &version);
version = ntohl(version);
ssh_log(session, SSH_LOG_PACKET, "Client version: %d", version);
sftp->client_version = version;
sftp_packet_free(packet);
reply = buffer_new();
if (reply == NULL) {
ssh_set_error_oom(session);
sftp_leave_function();
return -1;
}
if (buffer_add_u32(reply, ntohl(LIBSFTP_VERSION)) < 0) {
ssh_set_error_oom(session);
buffer_free(reply);
sftp_leave_function();
return -1;
}
if (sftp_packet_write(sftp, SSH_FXP_VERSION, reply) < 0) {
buffer_free(reply);
sftp_leave_function();
return -1;
}
buffer_free(reply);
ssh_log(session, SSH_LOG_RARE, "Server version sent");
if (version > LIBSFTP_VERSION) {
sftp->version = LIBSFTP_VERSION;
} else {
sftp->version=version;
}
sftp_leave_function();
return 0;
}
#endif /* WITH_SERVER */
void sftp_free(sftp_session sftp){
sftp_request_queue ptr;
if (sftp == NULL) {
return;
}
channel_send_eof(sftp->channel);
ptr = sftp->queue;
while(ptr) {
sftp_request_queue old;
sftp_message_free(ptr->message);
old = ptr->next;
SAFE_FREE(ptr);
ptr = old;
}
channel_free(sftp->channel);
sftp_ext_free(sftp->ext);
ZERO_STRUCTP(sftp);
SAFE_FREE(sftp);
}
int sftp_packet_write(sftp_session sftp, uint8_t type, ssh_buffer payload){
int size;
if (buffer_prepend_data(payload, &type, sizeof(uint8_t)) < 0) {
ssh_set_error_oom(sftp->session);
return -1;
}
size = htonl(buffer_get_len(payload));
if (buffer_prepend_data(payload, &size, sizeof(uint32_t)) < 0) {
ssh_set_error_oom(sftp->session);
return -1;
}
size = channel_write(sftp->channel, buffer_get(payload),
buffer_get_len(payload));
if (size < 0) {
return -1;
} else if((uint32_t) size != buffer_get_len(payload)) {
ssh_log(sftp->session, SSH_LOG_PACKET,
"Had to write %d bytes, wrote only %d",
buffer_get_len(payload),
size);
}
return size;
}
sftp_packet sftp_packet_read(sftp_session sftp) {
sftp_packet packet = NULL;
uint32_t size;
sftp_enter_function();
packet = malloc(sizeof(struct sftp_packet_struct));
if (packet == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
packet->sftp = sftp;
packet->payload = buffer_new();
if (packet->payload == NULL) {
ssh_set_error_oom(sftp->session);
SAFE_FREE(packet);
return NULL;
}
if (channel_read_buffer(sftp->channel, packet->payload, 4, 0) <= 0) {
buffer_free(packet->payload);
SAFE_FREE(packet);
sftp_leave_function();
return NULL;
}
if (buffer_get_u32(packet->payload, &size) != sizeof(uint32_t)) {
ssh_set_error(sftp->session, SSH_FATAL, "Short sftp packet!");
buffer_free(packet->payload);
SAFE_FREE(packet);
sftp_leave_function();
return NULL;
}
size = ntohl(size);
if (channel_read_buffer(sftp->channel, packet->payload, 1, 0) <= 0) {
/* TODO: check if there are cases where an error needs to be set here */
buffer_free(packet->payload);
SAFE_FREE(packet);
sftp_leave_function();
return NULL;
}
buffer_get_u8(packet->payload, &packet->type);
if (size > 1) {
if (channel_read_buffer(sftp->channel, packet->payload, size - 1, 0) <= 0) {
/* TODO: check if there are cases where an error needs to be set here */
buffer_free(packet->payload);
SAFE_FREE(packet);
sftp_leave_function();
return NULL;
}
}
sftp_leave_function();
return packet;
}
static void sftp_set_error(sftp_session sftp, int errnum) {
if (sftp != NULL) {
sftp->errnum = errnum;
}
}
/* Get the last sftp error */
int sftp_get_error(sftp_session sftp) {
if (sftp == NULL) {
return -1;
}
return sftp->errnum;
}
static sftp_message sftp_message_new(sftp_session sftp){
sftp_message msg = NULL;
sftp_enter_function();
msg = malloc(sizeof(struct sftp_message_struct));
if (msg == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
ZERO_STRUCTP(msg);
msg->payload = buffer_new();
if (msg->payload == NULL) {
ssh_set_error_oom(sftp->session);
SAFE_FREE(msg);
return NULL;
}
msg->sftp = sftp;
sftp_leave_function();
return msg;
}
static void sftp_message_free(sftp_message msg) {
sftp_session sftp;
if (msg == NULL) {
return;
}
sftp = msg->sftp;
sftp_enter_function();
buffer_free(msg->payload);
SAFE_FREE(msg);
sftp_leave_function();
}
static sftp_message sftp_get_message(sftp_packet packet) {
sftp_session sftp = packet->sftp;
sftp_message msg = NULL;
sftp_enter_function();
msg = sftp_message_new(sftp);
if (msg == NULL) {
sftp_leave_function();
return NULL;
}
msg->sftp = packet->sftp;
msg->packet_type = packet->type;
if ((packet->type != SSH_FXP_STATUS) && (packet->type!=SSH_FXP_HANDLE) &&
(packet->type != SSH_FXP_DATA) && (packet->type != SSH_FXP_ATTRS) &&
(packet->type != SSH_FXP_NAME) && (packet->type != SSH_FXP_EXTENDED_REPLY)) {
ssh_set_error(packet->sftp->session, SSH_FATAL,
"Unknown packet type %d", packet->type);
sftp_message_free(msg);
sftp_leave_function();
return NULL;
}
if (buffer_get_u32(packet->payload, &msg->id) != sizeof(uint32_t)) {
ssh_set_error(packet->sftp->session, SSH_FATAL,
"Invalid packet %d: no ID", packet->type);
sftp_message_free(msg);
sftp_leave_function();
return NULL;
}
ssh_log(packet->sftp->session, SSH_LOG_PACKET,
"Packet with id %d type %d",
msg->id,
msg->packet_type);
if (buffer_add_data(msg->payload, buffer_get_rest(packet->payload),
buffer_get_rest_len(packet->payload)) < 0) {
ssh_set_error_oom(sftp->session);
sftp_message_free(msg);
sftp_leave_function();
return NULL;
}
sftp_leave_function();
return msg;
}
static int sftp_read_and_dispatch(sftp_session sftp) {
sftp_packet packet = NULL;
sftp_message msg = NULL;
sftp_enter_function();
packet = sftp_packet_read(sftp);
if (packet == NULL) {
sftp_leave_function();
return -1; /* something nasty happened reading the packet */
}
msg = sftp_get_message(packet);
sftp_packet_free(packet);
if (msg == NULL) {
sftp_leave_function();
return -1;
}
if (sftp_enqueue(sftp, msg) < 0) {
sftp_message_free(msg);
sftp_leave_function();
return -1;
}
sftp_leave_function();
return 0;
}
void sftp_packet_free(sftp_packet packet) {
if (packet == NULL) {
return;
}
buffer_free(packet->payload);
free(packet);
}
/* Initialize the sftp session with the server. */
int sftp_init(sftp_session sftp) {
sftp_packet packet = NULL;
ssh_buffer buffer = NULL;
ssh_string ext_name_s = NULL;
ssh_string ext_data_s = NULL;
char *ext_name = NULL;
char *ext_data = NULL;
uint32_t version = htonl(LIBSFTP_VERSION);
sftp_enter_function();
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
sftp_leave_function();
return -1;
}
if (buffer_add_u32(buffer, version) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
sftp_leave_function();
return -1;
}
if (sftp_packet_write(sftp, SSH_FXP_INIT, buffer) < 0) {
buffer_free(buffer);
sftp_leave_function();
return -1;
}
buffer_free(buffer);
packet = sftp_packet_read(sftp);
if (packet == NULL) {
sftp_leave_function();
return -1;
}
if (packet->type != SSH_FXP_VERSION) {
ssh_set_error(sftp->session, SSH_FATAL,
"Received a %d messages instead of SSH_FXP_VERSION", packet->type);
sftp_packet_free(packet);
sftp_leave_function();
return -1;
}
/* TODO: are we sure there are 4 bytes ready? */
buffer_get_u32(packet->payload, &version);
version = ntohl(version);
ssh_log(sftp->session, SSH_LOG_RARE,
"SFTP server version %d",
version);
ext_name_s = buffer_get_ssh_string(packet->payload);
while (ext_name_s != NULL) {
int count = sftp->ext->count;
char **tmp;
ext_data_s = buffer_get_ssh_string(packet->payload);
if (ext_data_s == NULL) {
string_free(ext_name_s);
break;
}
ext_name = string_to_char(ext_name_s);
ext_data = string_to_char(ext_data_s);
if (ext_name == NULL || ext_data == NULL) {
ssh_set_error_oom(sftp->session);
SAFE_FREE(ext_name);
SAFE_FREE(ext_data);
string_free(ext_name_s);
string_free(ext_data_s);
return -1;
}
ssh_log(sftp->session, SSH_LOG_RARE,
"SFTP server extension: %s, version: %s",
ext_name, ext_data);
count++;
tmp = realloc(sftp->ext->name, count * sizeof(char *));
if (tmp == NULL) {
ssh_set_error_oom(sftp->session);
SAFE_FREE(ext_name);
SAFE_FREE(ext_data);
string_free(ext_name_s);
string_free(ext_data_s);
return -1;
}
tmp[count - 1] = ext_name;
sftp->ext->name = tmp;
tmp = realloc(sftp->ext->data, count * sizeof(char *));
if (tmp == NULL) {
ssh_set_error_oom(sftp->session);
SAFE_FREE(ext_name);
SAFE_FREE(ext_data);
string_free(ext_name_s);
string_free(ext_data_s);
return -1;
}
tmp[count - 1] = ext_data;
sftp->ext->data = tmp;
sftp->ext->count = count;
string_free(ext_name_s);
string_free(ext_data_s);
ext_name_s = buffer_get_ssh_string(packet->payload);
}
sftp_packet_free(packet);
sftp->version = sftp->server_version = version;
sftp_leave_function();
return 0;
}
unsigned int sftp_extensions_get_count(sftp_session sftp) {
if (sftp == NULL || sftp->ext == NULL) {
return 0;
}
return sftp->ext->count;
}
const char *sftp_extensions_get_name(sftp_session sftp, unsigned int idx) {
if (sftp == NULL)
return NULL;
if (sftp->ext == NULL || sftp->ext->name == NULL) {
ssh_set_error_invalid(sftp->session, __FUNCTION__);
return NULL;
}
if (idx > sftp->ext->count) {
ssh_set_error_invalid(sftp->session, __FUNCTION__);
return NULL;
}
return sftp->ext->name[idx];
}
const char *sftp_extensions_get_data(sftp_session sftp, unsigned int idx) {
if (sftp == NULL)
return NULL;
if (sftp->ext == NULL || sftp->ext->name == NULL) {
ssh_set_error_invalid(sftp->session, __FUNCTION__);
return NULL;
}
if (idx > sftp->ext->count) {
ssh_set_error_invalid(sftp->session, __FUNCTION__);
return NULL;
}
return sftp->ext->data[idx];
}
int sftp_extension_supported(sftp_session sftp, const char *name,
const char *data) {
int i, n;
n = sftp_extensions_get_count(sftp);
for (i = 0; i < n; i++) {
if (strcmp(sftp_extensions_get_name(sftp, i), name) == 0 &&
strcmp(sftp_extensions_get_data(sftp, i), data) == 0) {
return 1;
}
}
return 0;
}
static sftp_request_queue request_queue_new(sftp_message msg) {
sftp_request_queue queue = NULL;
queue = malloc(sizeof(struct sftp_request_queue_struct));
if (queue == NULL) {
ssh_set_error_oom(msg->sftp->session);
return NULL;
}
ZERO_STRUCTP(queue);
queue->message = msg;
return queue;
}
static void request_queue_free(sftp_request_queue queue) {
if (queue == NULL) {
return;
}
ZERO_STRUCTP(queue);
SAFE_FREE(queue);
}
static int sftp_enqueue(sftp_session sftp, sftp_message msg) {
sftp_request_queue queue = NULL;
sftp_request_queue ptr;
queue = request_queue_new(msg);
if (queue == NULL) {
return -1;
}
ssh_log(sftp->session, SSH_LOG_PACKET,
"Queued msg type %d id %d",
msg->id, msg->packet_type);
if(sftp->queue == NULL) {
sftp->queue = queue;
} else {
ptr = sftp->queue;
while(ptr->next) {
ptr=ptr->next; /* find end of linked list */
}
ptr->next = queue; /* add it on bottom */
}
return 0;
}
/*
* Pulls of a message from the queue based on the ID.
* Returns NULL if no message has been found.
*/
static sftp_message sftp_dequeue(sftp_session sftp, uint32_t id){
sftp_request_queue prev = NULL;
sftp_request_queue queue;
sftp_message msg;
if(sftp->queue == NULL) {
return NULL;
}
queue = sftp->queue;
while (queue) {
if(queue->message->id == id) {
/* remove from queue */
if (prev == NULL) {
sftp->queue = queue->next;
} else {
prev->next = queue->next;
}
msg = queue->message;
request_queue_free(queue);
ssh_log(sftp->session, SSH_LOG_PACKET,
"Dequeued msg id %d type %d",
msg->id,
msg->packet_type);
return msg;
}
prev = queue;
queue = queue->next;
}
return NULL;
}
/*
* Assigns a new SFTP ID for new requests and assures there is no collision
* between them.
* Returns a new ID ready to use in a request
*/
static inline uint32_t sftp_get_new_id(sftp_session session) {
return ++session->id_counter;
}
static sftp_status_message parse_status_msg(sftp_message msg){
sftp_status_message status;
if (msg->packet_type != SSH_FXP_STATUS) {
ssh_set_error(msg->sftp->session, SSH_FATAL,
"Not a ssh_fxp_status message passed in!");
return NULL;
}
status = malloc(sizeof(struct sftp_status_message_struct));
if (status == NULL) {
ssh_set_error_oom(msg->sftp->session);
return NULL;
}
ZERO_STRUCTP(status);
status->id = msg->id;
if (buffer_get_u32(msg->payload,&status->status) != 4){
SAFE_FREE(status);
ssh_set_error(msg->sftp->session, SSH_FATAL,
"Invalid SSH_FXP_STATUS message");
return NULL;
}
status->error = buffer_get_ssh_string(msg->payload);
status->lang = buffer_get_ssh_string(msg->payload);
if(status->error == NULL || status->lang == NULL){
if(msg->sftp->version >=3){
/* These are mandatory from version 3 */
string_free(status->error);
/* status->lang never get allocated if something failed */
SAFE_FREE(status);
ssh_set_error(msg->sftp->session, SSH_FATAL,
"Invalid SSH_FXP_STATUS message");
return NULL;
}
}
status->status = ntohl(status->status);
if(status->error)
status->errormsg = string_to_char(status->error);
else
status->errormsg = strdup("No error message in packet");
if(status->lang)
status->langmsg = string_to_char(status->lang);
else
status->langmsg = strdup("");
if (status->errormsg == NULL || status->langmsg == NULL) {
ssh_set_error_oom(msg->sftp->session);
status_msg_free(status);
return NULL;
}
return status;
}
static void status_msg_free(sftp_status_message status){
if (status == NULL) {
return;
}
string_free(status->error);
string_free(status->lang);
SAFE_FREE(status->errormsg);
SAFE_FREE(status->langmsg);
SAFE_FREE(status);
}
static sftp_file parse_handle_msg(sftp_message msg){
sftp_file file;
if(msg->packet_type != SSH_FXP_HANDLE) {
ssh_set_error(msg->sftp->session, SSH_FATAL,
"Not a ssh_fxp_handle message passed in!");
return NULL;
}
file = malloc(sizeof(struct sftp_file_struct));
if (file == NULL) {
ssh_set_error_oom(msg->sftp->session);
return NULL;
}
ZERO_STRUCTP(file);
file->handle = buffer_get_ssh_string(msg->payload);
if (file->handle == NULL) {
ssh_set_error(msg->sftp->session, SSH_FATAL,
"Invalid SSH_FXP_HANDLE message");
SAFE_FREE(file);
return NULL;
}
file->sftp = msg->sftp;
file->offset = 0;
file->eof = 0;
return file;
}
/* Open a directory */
sftp_dir sftp_opendir(sftp_session sftp, const char *path){
sftp_message msg = NULL;
sftp_file file = NULL;
sftp_dir dir = NULL;
sftp_status_message status;
ssh_string path_s;
ssh_buffer payload;
uint32_t id;
payload = buffer_new();
if (payload == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
path_s = string_from_char(path);
if (path_s == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(payload);
return NULL;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(payload, id) < 0 ||
buffer_add_ssh_string(payload, path_s) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(payload);
string_free(path_s);
return NULL;
}
string_free(path_s);
if (sftp_packet_write(sftp, SSH_FXP_OPENDIR, payload) < 0) {
buffer_free(payload);
return NULL;
}
buffer_free(payload);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
/* something nasty has happened */
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
switch (msg->packet_type) {
case SSH_FXP_STATUS:
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
sftp_set_error(sftp, status->status);
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return NULL;
case SSH_FXP_HANDLE:
file = parse_handle_msg(msg);
sftp_message_free(msg);
if (file != NULL) {
dir = malloc(sizeof(struct sftp_dir_struct));
if (dir == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
ZERO_STRUCTP(dir);
dir->sftp = sftp;
dir->name = strdup(path);
if (dir->name == NULL) {
SAFE_FREE(dir);
SAFE_FREE(file);
return NULL;
}
dir->handle = file->handle;
SAFE_FREE(file);
}
return dir;
default:
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d during opendir!", msg->packet_type);
sftp_message_free(msg);
}
return NULL;
}
/*
* Parse the attributes from a payload from some messages. It is coded on
* baselines from the protocol version 4.
* This code is more or less dead but maybe we need it in future.
*/
static sftp_attributes sftp_parse_attr_4(sftp_session sftp, ssh_buffer buf,
int expectnames) {
sftp_attributes attr;
ssh_string owner = NULL;
ssh_string group = NULL;
uint32_t flags = 0;
int ok = 0;
/* unused member variable */
(void) expectnames;
attr = malloc(sizeof(struct sftp_attributes_struct));
if (attr == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
ZERO_STRUCTP(attr);
/* This isn't really a loop, but it is like a try..catch.. */
do {
if (buffer_get_u32(buf, &flags) != 4) {
break;
}
flags = ntohl(flags);
attr->flags = flags;
if (flags & SSH_FILEXFER_ATTR_SIZE) {
if (buffer_get_u64(buf, &attr->size) != 8) {
break;
}
attr->size = ntohll(attr->size);
}
if (flags & SSH_FILEXFER_ATTR_OWNERGROUP) {
if((owner = buffer_get_ssh_string(buf)) == NULL ||
(attr->owner = string_to_char(owner)) == NULL) {
break;
}
if ((group = buffer_get_ssh_string(buf)) == NULL ||
(attr->group = string_to_char(group)) == NULL) {
break;
}
}
if (flags & SSH_FILEXFER_ATTR_PERMISSIONS) {
if (buffer_get_u32(buf, &attr->permissions) != 4) {
break;
}
attr->permissions = ntohl(attr->permissions);
/* FIXME on windows! */
switch (attr->permissions & S_IFMT) {
case S_IFSOCK:
case S_IFBLK:
case S_IFCHR:
case S_IFIFO:
attr->type = SSH_FILEXFER_TYPE_SPECIAL;
break;
case S_IFLNK:
attr->type = SSH_FILEXFER_TYPE_SYMLINK;
break;
case S_IFREG:
attr->type = SSH_FILEXFER_TYPE_REGULAR;
break;
case S_IFDIR:
attr->type = SSH_FILEXFER_TYPE_DIRECTORY;
break;
default:
attr->type = SSH_FILEXFER_TYPE_UNKNOWN;
break;
}
}
if (flags & SSH_FILEXFER_ATTR_ACCESSTIME) {
if (buffer_get_u64(buf, &attr->atime64) != 8) {
break;
}
attr->atime64 = ntohll(attr->atime64);
}
if (flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES) {
if (buffer_get_u32(buf, &attr->atime_nseconds) != 4) {
break;
}
attr->atime_nseconds = ntohl(attr->atime_nseconds);
}
if (flags & SSH_FILEXFER_ATTR_CREATETIME) {
if (buffer_get_u64(buf, &attr->createtime) != 8) {
break;
}
attr->createtime = ntohll(attr->createtime);
}
if (flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES) {
if (buffer_get_u32(buf, &attr->createtime_nseconds) != 4) {
break;
}
attr->createtime_nseconds = ntohl(attr->createtime_nseconds);
}
if (flags & SSH_FILEXFER_ATTR_MODIFYTIME) {
if (buffer_get_u64(buf, &attr->mtime64) != 8) {
break;
}
attr->mtime64 = ntohll(attr->mtime64);
}
if (flags & SSH_FILEXFER_ATTR_SUBSECOND_TIMES) {
if (buffer_get_u32(buf, &attr->mtime_nseconds) != 4) {
break;
}
attr->mtime_nseconds = ntohl(attr->mtime_nseconds);
}
if (flags & SSH_FILEXFER_ATTR_ACL) {
if ((attr->acl = buffer_get_ssh_string(buf)) == NULL) {
break;
}
}
if (flags & SSH_FILEXFER_ATTR_EXTENDED) {
if (buffer_get_u32(buf,&attr->extended_count) != 4) {
break;
}
attr->extended_count = ntohl(attr->extended_count);
while(attr->extended_count &&
(attr->extended_type = buffer_get_ssh_string(buf)) &&
(attr->extended_data = buffer_get_ssh_string(buf))){
attr->extended_count--;
}
if (attr->extended_count) {
break;
}
}
ok = 1;
} while (0);
if (ok == 0) {
/* break issued somewhere */
string_free(owner);
string_free(group);
string_free(attr->acl);
string_free(attr->extended_type);
string_free(attr->extended_data);
SAFE_FREE(attr->owner);
SAFE_FREE(attr->group);
SAFE_FREE(attr);
ssh_set_error(sftp->session, SSH_FATAL, "Invalid ATTR structure");
return NULL;
}
return attr;
}
enum sftp_longname_field_e {
SFTP_LONGNAME_PERM = 0,
SFTP_LONGNAME_FIXME,
SFTP_LONGNAME_OWNER,
SFTP_LONGNAME_GROUP,
SFTP_LONGNAME_SIZE,
SFTP_LONGNAME_DATE,
SFTP_LONGNAME_TIME,
SFTP_LONGNAME_NAME,
};
static char *sftp_parse_longname(const char *longname,
enum sftp_longname_field_e longname_field) {
const char *p, *q;
size_t len, field = 0;
char *x;
p = longname;
/* Find the beginning of the field which is specified by sftp_longanme_field_e. */
while(field != longname_field) {
if(isspace(*p)) {
field++;
p++;
while(*p && isspace(*p)) {
p++;
}
} else {
p++;
}
}
q = p;
while (! isspace(*q)) {
q++;
}
/* There is no strndup on windows */
len = q - p + 1;
x = malloc(len);
if (x == NULL) {
return NULL;
}
snprintf(x, len, "%s", p);
return x;
}
/* sftp version 0-3 code. It is different from the v4 */
/* maybe a paste of the draft is better than the code */
/*
uint32 flags
uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE
uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID
uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID
uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS
uint32 atime present only if flag SSH_FILEXFER_ACMODTIME
uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME
uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED
string extended_type
string extended_data
... more extended data (extended_type - extended_data pairs),
so that number of pairs equals extended_count */
static sftp_attributes sftp_parse_attr_3(sftp_session sftp, ssh_buffer buf,
int expectname) {
ssh_string longname = NULL;
ssh_string name = NULL;
sftp_attributes attr;
uint32_t flags = 0;
int ok = 0;
attr = malloc(sizeof(struct sftp_attributes_struct));
if (attr == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
ZERO_STRUCTP(attr);
/* This isn't really a loop, but it is like a try..catch.. */
do {
if (expectname) {
if ((name = buffer_get_ssh_string(buf)) == NULL ||
(attr->name = string_to_char(name)) == NULL) {
break;
}
string_free(name);
ssh_log(sftp->session, SSH_LOG_RARE, "Name: %s", attr->name);
if ((longname=buffer_get_ssh_string(buf)) == NULL ||
(attr->longname=string_to_char(longname)) == NULL) {
break;
}
string_free(longname);
/* Set owner and group if we talk to openssh and have the longname */
if (ssh_get_openssh_version(sftp->session)) {
attr->owner = sftp_parse_longname(attr->longname, SFTP_LONGNAME_OWNER);
if (attr->owner == NULL) {
break;
}
attr->group = sftp_parse_longname(attr->longname, SFTP_LONGNAME_GROUP);
if (attr->group == NULL) {
break;
}
}
}
if (buffer_get_u32(buf, &flags) != sizeof(uint32_t)) {
break;
}
flags = ntohl(flags);
attr->flags = flags;
ssh_log(sftp->session, SSH_LOG_RARE,
"Flags: %.8lx\n", (long unsigned int) flags);
if (flags & SSH_FILEXFER_ATTR_SIZE) {
if(buffer_get_u64(buf, &attr->size) != sizeof(uint64_t)) {
break;
}
attr->size = ntohll(attr->size);
ssh_log(sftp->session, SSH_LOG_RARE,
"Size: %llu\n",
(long long unsigned int) attr->size);
}
if (flags & SSH_FILEXFER_ATTR_UIDGID) {
if (buffer_get_u32(buf, &attr->uid) != sizeof(uint32_t)) {
break;
}
if (buffer_get_u32(buf, &attr->gid) != sizeof(uint32_t)) {
break;
}
attr->uid = ntohl(attr->uid);
attr->gid = ntohl(attr->gid);
}
if (flags & SSH_FILEXFER_ATTR_PERMISSIONS) {
if (buffer_get_u32(buf, &attr->permissions) != sizeof(uint32_t)) {
break;
}
attr->permissions = ntohl(attr->permissions);
switch (attr->permissions & S_IFMT) {
case S_IFSOCK:
case S_IFBLK:
case S_IFCHR:
case S_IFIFO:
attr->type = SSH_FILEXFER_TYPE_SPECIAL;
break;
case S_IFLNK:
attr->type = SSH_FILEXFER_TYPE_SYMLINK;
break;
case S_IFREG:
attr->type = SSH_FILEXFER_TYPE_REGULAR;
break;
case S_IFDIR:
attr->type = SSH_FILEXFER_TYPE_DIRECTORY;
break;
default:
attr->type = SSH_FILEXFER_TYPE_UNKNOWN;
break;
}
}
if (flags & SSH_FILEXFER_ATTR_ACMODTIME) {
if (buffer_get_u32(buf, &attr->atime) != sizeof(uint32_t)) {
break;
}
attr->atime = ntohl(attr->atime);
if (buffer_get_u32(buf, &attr->mtime) != sizeof(uint32_t)) {
break;
}
attr->mtime = ntohl(attr->mtime);
}
if (flags & SSH_FILEXFER_ATTR_EXTENDED) {
if (buffer_get_u32(buf, &attr->extended_count) != sizeof(uint32_t)) {
break;
}
attr->extended_count = ntohl(attr->extended_count);
while (attr->extended_count &&
(attr->extended_type = buffer_get_ssh_string(buf))
&& (attr->extended_data = buffer_get_ssh_string(buf))) {
attr->extended_count--;
}
if (attr->extended_count) {
break;
}
}
ok = 1;
} while (0);
if (!ok) {
/* break issued somewhere */
string_free(name);
string_free(longname);
string_free(attr->extended_type);
string_free(attr->extended_data);
SAFE_FREE(attr->name);
SAFE_FREE(attr->longname);
SAFE_FREE(attr->owner);
SAFE_FREE(attr->group);
SAFE_FREE(attr);
ssh_set_error(sftp->session, SSH_FATAL, "Invalid ATTR structure");
return NULL;
}
/* everything went smoothly */
return attr;
}
/* FIXME is this really needed as a public function? */
int buffer_add_attributes(ssh_buffer buffer, sftp_attributes attr) {
uint32_t flags = (attr ? attr->flags : 0);
flags &= (SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_UIDGID |
SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME);
if (buffer_add_u32(buffer, htonl(flags)) < 0) {
return -1;
}
if (attr) {
if (flags & SSH_FILEXFER_ATTR_SIZE) {
if (buffer_add_u64(buffer, htonll(attr->size)) < 0) {
return -1;
}
}
if (flags & SSH_FILEXFER_ATTR_UIDGID) {
if (buffer_add_u32(buffer,htonl(attr->uid)) < 0 ||
buffer_add_u32(buffer,htonl(attr->gid)) < 0) {
return -1;
}
}
if (flags & SSH_FILEXFER_ATTR_PERMISSIONS) {
if (buffer_add_u32(buffer, htonl(attr->permissions)) < 0) {
return -1;
}
}
if (flags & SSH_FILEXFER_ATTR_ACMODTIME) {
if (buffer_add_u32(buffer, htonl(attr->atime)) < 0 ||
buffer_add_u32(buffer, htonl(attr->mtime)) < 0) {
return -1;
}
}
}
return 0;
}
sftp_attributes sftp_parse_attr(sftp_session session, ssh_buffer buf,
int expectname) {
switch(session->version) {
case 4:
return sftp_parse_attr_4(session, buf, expectname);
case 3:
case 2:
case 1:
case 0:
return sftp_parse_attr_3(session, buf, expectname);
default:
ssh_set_error(session->session, SSH_FATAL,
"Version %d unsupported by client", session->server_version);
return NULL;
}
return NULL;
}
/* Get the version of the SFTP protocol supported by the server */
int sftp_server_version(sftp_session sftp) {
return sftp->server_version;
}
/* Get a single file attributes structure of a directory. */
sftp_attributes sftp_readdir(sftp_session sftp, sftp_dir dir) {
sftp_message msg = NULL;
sftp_status_message status;
sftp_attributes attr;
ssh_buffer payload;
uint32_t id;
if (dir->buffer == NULL) {
payload = buffer_new();
if (payload == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(payload, id) < 0 ||
buffer_add_ssh_string(payload, dir->handle) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(payload);
return NULL;
}
if (sftp_packet_write(sftp, SSH_FXP_READDIR, payload) < 0) {
buffer_free(payload);
return NULL;
}
buffer_free(payload);
ssh_log(sftp->session, SSH_LOG_PACKET,
"Sent a ssh_fxp_readdir with id %d", id);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
/* something nasty has happened */
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
switch (msg->packet_type){
case SSH_FXP_STATUS:
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_EOF:
dir->eof = 1;
status_msg_free(status);
return NULL;
default:
break;
}
ssh_set_error(sftp->session, SSH_FATAL,
"Unknown error status: %d", status->status);
status_msg_free(status);
return NULL;
case SSH_FXP_NAME:
buffer_get_u32(msg->payload, &dir->count);
dir->count = ntohl(dir->count);
dir->buffer = msg->payload;
msg->payload = NULL;
sftp_message_free(msg);
break;
default:
ssh_set_error(sftp->session, SSH_FATAL,
"Unsupported message back %d", msg->packet_type);
sftp_message_free(msg);
return NULL;
}
}
/* now dir->buffer contains a buffer and dir->count != 0 */
if (dir->count == 0) {
ssh_set_error(sftp->session, SSH_FATAL,
"Count of files sent by the server is zero, which is invalid, or "
"libsftp bug");
return NULL;
}
ssh_log(sftp->session, SSH_LOG_RARE, "Count is %d", dir->count);
attr = sftp_parse_attr(sftp, dir->buffer, 1);
if (attr == NULL) {
ssh_set_error(sftp->session, SSH_FATAL,
"Couldn't parse the SFTP attributes");
return NULL;
}
dir->count--;
if (dir->count == 0) {
buffer_free(dir->buffer);
dir->buffer = NULL;
}
return attr;
}
/* Tell if the directory has reached EOF (End Of File). */
int sftp_dir_eof(sftp_dir dir) {
return dir->eof;
}
/* Free a SFTP_ATTRIBUTE handle */
void sftp_attributes_free(sftp_attributes file){
if (file == NULL) {
return;
}
string_free(file->acl);
string_free(file->extended_data);
string_free(file->extended_type);
SAFE_FREE(file->name);
SAFE_FREE(file->longname);
SAFE_FREE(file->group);
SAFE_FREE(file->owner);
SAFE_FREE(file);
}
static int sftp_handle_close(sftp_session sftp, ssh_string handle) {
sftp_status_message status;
sftp_message msg = NULL;
ssh_buffer buffer = NULL;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, handle) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
if (sftp_packet_write(sftp, SSH_FXP_CLOSE ,buffer) < 0) {
buffer_free(buffer);
return -1;
}
buffer_free(buffer);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
/* something nasty has happened */
return -1;
}
msg = sftp_dequeue(sftp,id);
}
switch (msg->packet_type) {
case SSH_FXP_STATUS:
status = parse_status_msg(msg);
sftp_message_free(msg);
if(status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_OK:
status_msg_free(status);
return 0;
break;
default:
break;
}
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
default:
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d during sftp_handle_close!", msg->packet_type);
sftp_message_free(msg);
}
return -1;
}
/* Close an open file handle. */
int sftp_close(sftp_file file){
int err = SSH_NO_ERROR;
SAFE_FREE(file->name);
if (file->handle){
err = sftp_handle_close(file->sftp,file->handle);
string_free(file->handle);
}
/* FIXME: check server response and implement errno */
SAFE_FREE(file);
return err;
}
/* Close an open directory. */
int sftp_closedir(sftp_dir dir){
int err = SSH_NO_ERROR;
SAFE_FREE(dir->name);
if (dir->handle) {
err = sftp_handle_close(dir->sftp, dir->handle);
string_free(dir->handle);
}
/* FIXME: check server response and implement errno */
buffer_free(dir->buffer);
SAFE_FREE(dir);
return err;
}
/* Open a file on the server. */
sftp_file sftp_open(sftp_session sftp, const char *file, int flags,
mode_t mode) {
sftp_message msg = NULL;
sftp_status_message status;
struct sftp_attributes_struct attr;
sftp_file handle;
ssh_string filename;
ssh_buffer buffer;
uint32_t sftp_flags = 0;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
filename = string_from_char(file);
if (filename == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return NULL;
}
ZERO_STRUCT(attr);
attr.permissions = mode;
attr.flags = SSH_FILEXFER_ATTR_PERMISSIONS;
if (flags == O_RDONLY)
sftp_flags |= SSH_FXF_READ; /* if any of the other flag is set,
READ should not be set initialy */
if (flags & O_WRONLY)
sftp_flags |= SSH_FXF_WRITE;
if (flags & O_RDWR)
sftp_flags |= (SSH_FXF_WRITE | SSH_FXF_READ);
if (flags & O_CREAT)
sftp_flags |= SSH_FXF_CREAT;
if (flags & O_TRUNC)
sftp_flags |= SSH_FXF_TRUNC;
if (flags & O_EXCL)
sftp_flags |= SSH_FXF_EXCL;
ssh_log(sftp->session,SSH_LOG_PACKET,"Opening file %s with sftp flags %x",file,sftp_flags);
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, filename) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(filename);
return NULL;
}
string_free(filename);
if (buffer_add_u32(buffer, htonl(sftp_flags)) < 0 ||
buffer_add_attributes(buffer, &attr) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return NULL;
}
if (sftp_packet_write(sftp, SSH_FXP_OPEN, buffer) < 0) {
buffer_free(buffer);
return NULL;
}
buffer_free(buffer);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
/* something nasty has happened */
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
switch (msg->packet_type) {
case SSH_FXP_STATUS:
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
sftp_set_error(sftp, status->status);
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return NULL;
case SSH_FXP_HANDLE:
handle = parse_handle_msg(msg);
sftp_message_free(msg);
return handle;
default:
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d during open!", msg->packet_type);
sftp_message_free(msg);
}
return NULL;
}
void sftp_file_set_nonblocking(sftp_file handle){
handle->nonblocking=1;
}
void sftp_file_set_blocking(sftp_file handle){
handle->nonblocking=0;
}
/* Read from a file using an opened sftp file handle. */
ssize_t sftp_read(sftp_file handle, void *buf, size_t count) {
sftp_session sftp = handle->sftp;
sftp_message msg = NULL;
sftp_status_message status;
ssh_string datastring;
ssh_buffer buffer;
int id;
if (handle->eof) {
return 0;
}
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
id = sftp_get_new_id(handle->sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, handle->handle) < 0 ||
buffer_add_u64(buffer, htonll(handle->offset)) < 0 ||
buffer_add_u32(buffer,htonl(count)) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
if (sftp_packet_write(handle->sftp, SSH_FXP_READ, buffer) < 0) {
buffer_free(buffer);
return -1;
}
buffer_free(buffer);
while (msg == NULL) {
if (handle->nonblocking) {
if (channel_poll(handle->sftp->channel, 0) == 0) {
/* we cannot block */
return 0;
}
}
if (sftp_read_and_dispatch(handle->sftp) < 0) {
/* something nasty has happened */
return -1;
}
msg = sftp_dequeue(handle->sftp, id);
}
switch (msg->packet_type) {
case SSH_FXP_STATUS:
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_EOF:
handle->eof = 1;
status_msg_free(status);
return 0;
default:
break;
}
ssh_set_error(sftp->session,SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
case SSH_FXP_DATA:
datastring = buffer_get_ssh_string(msg->payload);
sftp_message_free(msg);
if (datastring == NULL) {
ssh_set_error(sftp->session, SSH_FATAL,
"Received invalid DATA packet from sftp server");
return -1;
}
if (string_len(datastring) > count) {
ssh_set_error(sftp->session, SSH_FATAL,
"Received a too big DATA packet from sftp server: "
"%zu and asked for %zu",
string_len(datastring), count);
string_free(datastring);
return -1;
}
count = string_len(datastring);
handle->offset += count;
memcpy(buf, string_data(datastring), count);
string_free(datastring);
return count;
default:
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d during read!", msg->packet_type);
sftp_message_free(msg);
return -1;
}
return -1; /* not reached */
}
/* Start an asynchronous read from a file using an opened sftp file handle. */
int sftp_async_read_begin(sftp_file file, uint32_t len){
sftp_session sftp = file->sftp;
ssh_buffer buffer;
uint32_t id;
sftp_enter_function();
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, file->handle) < 0 ||
buffer_add_u64(buffer, htonll(file->offset)) < 0 ||
buffer_add_u32(buffer, htonl(len)) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
if (sftp_packet_write(sftp, SSH_FXP_READ, buffer) < 0) {
buffer_free(buffer);
return -1;
}
buffer_free(buffer);
file->offset += len; /* assume we'll read len bytes */
sftp_leave_function();
return id;
}
/* Wait for an asynchronous read to complete and save the data. */
int sftp_async_read(sftp_file file, void *data, uint32_t size, uint32_t id){
sftp_session sftp = file->sftp;
sftp_message msg = NULL;
sftp_status_message status;
ssh_string datastring;
int err = SSH_OK;
uint32_t len;
sftp_enter_function();
if (file->eof) {
sftp_leave_function();
return 0;
}
/* handle an existing request */
while (msg == NULL) {
if (file->nonblocking){
if (channel_poll(sftp->channel, 0) == 0) {
/* we cannot block */
return SSH_AGAIN;
}
}
if (sftp_read_and_dispatch(sftp) < 0) {
/* something nasty has happened */
sftp_leave_function();
return SSH_ERROR;
}
msg = sftp_dequeue(sftp,id);
}
switch (msg->packet_type) {
case SSH_FXP_STATUS:
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
sftp_leave_function();
return -1;
}
sftp_set_error(sftp, status->status);
if (status->status != SSH_FX_EOF) {
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server : %s", status->errormsg);
sftp_leave_function();
err = SSH_ERROR;
} else {
file->eof = 1;
}
status_msg_free(status);
sftp_leave_function();
return err;
case SSH_FXP_DATA:
datastring = buffer_get_ssh_string(msg->payload);
sftp_message_free(msg);
if (datastring == NULL) {
ssh_set_error(sftp->session, SSH_FATAL,
"Received invalid DATA packet from sftp server");
sftp_leave_function();
return SSH_ERROR;
}
if (string_len(datastring) > size) {
ssh_set_error(sftp->session, SSH_FATAL,
"Received a too big DATA packet from sftp server: "
"%zu and asked for %u",
string_len(datastring), size);
string_free(datastring);
sftp_leave_function();
return SSH_ERROR;
}
len = string_len(datastring);
//handle->offset+=len;
/* We already have set the offset previously. All we can do is warn that the expected len
* and effective lengths are different */
memcpy(data, string_data(datastring), len);
string_free(datastring);
sftp_leave_function();
return len;
default:
ssh_set_error(sftp->session,SSH_FATAL,"Received message %d during read!",msg->packet_type);
sftp_message_free(msg);
sftp_leave_function();
return SSH_ERROR;
}
sftp_leave_function();
return SSH_ERROR;
}
ssize_t sftp_write(sftp_file file, const void *buf, size_t count) {
sftp_session sftp = file->sftp;
sftp_message msg = NULL;
sftp_status_message status;
ssh_string datastring;
ssh_buffer buffer;
uint32_t id;
int len;
int packetlen;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
datastring = string_new(count);
if (datastring == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
string_fill(datastring, buf, count);
id = sftp_get_new_id(file->sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, file->handle) < 0 ||
buffer_add_u64(buffer, htonll(file->offset)) < 0 ||
buffer_add_ssh_string(buffer, datastring) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(datastring);
return -1;
}
string_free(datastring);
len = sftp_packet_write(file->sftp, SSH_FXP_WRITE, buffer);
packetlen=buffer_get_len(buffer);
buffer_free(buffer);
if (len < 0) {
return -1;
} else if (len != packetlen) {
ssh_log(sftp->session, SSH_LOG_PACKET,
"Could not write as much data as expected");
}
while (msg == NULL) {
if (sftp_read_and_dispatch(file->sftp) < 0) {
/* something nasty has happened */
return -1;
}
msg = sftp_dequeue(file->sftp, id);
}
switch (msg->packet_type) {
case SSH_FXP_STATUS:
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_OK:
file->offset += count;
status_msg_free(status);
return count;
default:
break;
}
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
file->offset += count;
status_msg_free(status);
return -1;
default:
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d during write!", msg->packet_type);
sftp_message_free(msg);
return -1;
}
return -1; /* not reached */
}
/* Seek to a specific location in a file. */
int sftp_seek(sftp_file file, uint32_t new_offset) {
if (file == NULL) {
return -1;
}
file->offset = new_offset;
return 0;
}
int sftp_seek64(sftp_file file, uint64_t new_offset) {
if (file == NULL) {
return -1;
}
file->offset = new_offset;
return 0;
}
/* Report current byte position in file. */
unsigned long sftp_tell(sftp_file file) {
return (unsigned long)file->offset;
}
/* Report current byte position in file. */
uint64_t sftp_tell64(sftp_file file) {
return (uint64_t) file->offset;
}
/* Rewinds the position of the file pointer to the beginning of the file.*/
void sftp_rewind(sftp_file file) {
file->offset = 0;
}
/* code written by Nick */
int sftp_unlink(sftp_session sftp, const char *file) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_string filename;
ssh_buffer buffer;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
filename = string_from_char(file);
if (filename == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, filename) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(filename);
}
if (sftp_packet_write(sftp, SSH_FXP_REMOVE, buffer) < 0) {
buffer_free(buffer);
string_free(filename);
}
string_free(filename);
buffer_free(buffer);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp)) {
return -1;
}
msg = sftp_dequeue(sftp, id);
}
if (msg->packet_type == SSH_FXP_STATUS) {
/* by specification, this command's only supposed to return SSH_FXP_STATUS */
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_OK:
status_msg_free(status);
return 0;
default:
break;
}
/*
* The status should be SSH_FX_OK if the command was successful, if it
* didn't, then there was an error
*/
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
} else {
ssh_set_error(sftp->session,SSH_FATAL,
"Received message %d when attempting to remove file", msg->packet_type);
sftp_message_free(msg);
}
return -1;
}
/* code written by Nick */
int sftp_rmdir(sftp_session sftp, const char *directory) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_string filename;
ssh_buffer buffer;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
filename = string_from_char(directory);
if (filename == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, filename) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(filename);
return -1;
}
if (sftp_packet_write(sftp, SSH_FXP_RMDIR, buffer) < 0) {
buffer_free(buffer);
string_free(filename);
return -1;
}
buffer_free(buffer);
string_free(filename);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return -1;
}
msg = sftp_dequeue(sftp, id);
}
/* By specification, this command returns SSH_FXP_STATUS */
if (msg->packet_type == SSH_FXP_STATUS) {
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_OK:
status_msg_free(status);
return 0;
break;
default:
break;
}
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
} else {
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to remove directory",
msg->packet_type);
sftp_message_free(msg);
}
return -1;
}
/* Code written by Nick */
int sftp_mkdir(sftp_session sftp, const char *directory, mode_t mode) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
sftp_attributes errno_attr = NULL;
struct sftp_attributes_struct attr;
ssh_buffer buffer;
ssh_string path;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
path = string_from_char(directory);
if (path == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
ZERO_STRUCT(attr);
attr.permissions = mode;
attr.flags = SSH_FILEXFER_ATTR_PERMISSIONS;
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, path) < 0 ||
buffer_add_attributes(buffer, &attr) < 0 ||
sftp_packet_write(sftp, SSH_FXP_MKDIR, buffer) < 0) {
buffer_free(buffer);
string_free(path);
}
buffer_free(buffer);
string_free(path);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return -1;
}
msg = sftp_dequeue(sftp, id);
}
/* By specification, this command only returns SSH_FXP_STATUS */
if (msg->packet_type == SSH_FXP_STATUS) {
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_FAILURE:
/*
* mkdir always returns a failure, even if the path already exists.
* To be POSIX conform and to be able to map it to EEXIST a stat
* call is needed here.
*/
errno_attr = sftp_lstat(sftp, directory);
if (errno_attr != NULL) {
SAFE_FREE(errno_attr);
sftp_set_error(sftp, SSH_FX_FILE_ALREADY_EXISTS);
}
break;
case SSH_FX_OK:
status_msg_free(status);
return 0;
break;
default:
break;
}
/*
* The status should be SSH_FX_OK if the command was successful, if it
* didn't, then there was an error
*/
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
} else {
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to make directory",
msg->packet_type);
sftp_message_free(msg);
}
return -1;
}
/* code written by nick */
int sftp_rename(sftp_session sftp, const char *original, const char *newname) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_buffer buffer;
ssh_string oldpath;
ssh_string newpath;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
oldpath = string_from_char(original);
if (oldpath == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
newpath = string_from_char(newname);
if (newpath == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(oldpath);
return -1;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, oldpath) < 0 ||
buffer_add_ssh_string(buffer, newpath) < 0 ||
/* POSIX rename atomically replaces newpath, we should do the same
* only available on >=v4 */
sftp->version>=4 ? (buffer_add_u32(buffer, SSH_FXF_RENAME_OVERWRITE) < 0):0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(oldpath);
string_free(newpath);
return -1;
}
if (sftp_packet_write(sftp, SSH_FXP_RENAME, buffer) < 0) {
buffer_free(buffer);
string_free(oldpath);
string_free(newpath);
return -1;
}
buffer_free(buffer);
string_free(oldpath);
string_free(newpath);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return -1;
}
msg = sftp_dequeue(sftp, id);
}
/* By specification, this command only returns SSH_FXP_STATUS */
if (msg->packet_type == SSH_FXP_STATUS) {
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_OK:
status_msg_free(status);
return 0;
default:
break;
}
/*
* Status should be SSH_FX_OK if the command was successful, if it didn't,
* then there was an error
*/
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
} else {
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to rename",
msg->packet_type);
sftp_message_free(msg);
}
return -1;
}
/* Code written by Nick */
/* Set file attributes on a file, directory or symbolic link. */
int sftp_setstat(sftp_session sftp, const char *file, sftp_attributes attr) {
uint32_t id = sftp_get_new_id(sftp);
ssh_buffer buffer = buffer_new();
ssh_string path = string_from_char(file);
sftp_message msg = NULL;
sftp_status_message status = NULL;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
path = string_from_char(file);
if (path == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, path) < 0 ||
buffer_add_attributes(buffer, attr) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(path);
return -1;
}
if (sftp_packet_write(sftp, SSH_FXP_SETSTAT, buffer) < 0) {
buffer_free(buffer);
string_free(path);
return -1;
}
buffer_free(buffer);
string_free(path);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return -1;
}
msg = sftp_dequeue(sftp, id);
}
/* By specification, this command only returns SSH_FXP_STATUS */
if (msg->packet_type == SSH_FXP_STATUS) {
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_OK:
status_msg_free(status);
return 0;
default:
break;
}
/*
* The status should be SSH_FX_OK if the command was successful, if it
* didn't, then there was an error
*/
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
} else {
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to set stats", msg->packet_type);
sftp_message_free(msg);
}
return -1;
}
/* Change the file owner and group */
int sftp_chown(sftp_session sftp, const char *file, uid_t owner, gid_t group) {
struct sftp_attributes_struct attr;
ZERO_STRUCT(attr);
attr.uid = owner;
attr.gid = group;
attr.flags = SSH_FILEXFER_ATTR_UIDGID;
return sftp_setstat(sftp, file, &attr);
}
/* Change permissions of a file */
int sftp_chmod(sftp_session sftp, const char *file, mode_t mode) {
struct sftp_attributes_struct attr;
ZERO_STRUCT(attr);
attr.permissions = mode;
attr.flags = SSH_FILEXFER_ATTR_PERMISSIONS;
return sftp_setstat(sftp, file, &attr);
}
/* Change the last modification and access time of a file. */
int sftp_utimes(sftp_session sftp, const char *file,
const struct timeval *times) {
struct sftp_attributes_struct attr;
ZERO_STRUCT(attr);
attr.atime = times[0].tv_sec;
attr.atime_nseconds = times[0].tv_usec;
attr.mtime = times[1].tv_sec;
attr.mtime_nseconds = times[1].tv_usec;
attr.flags |= SSH_FILEXFER_ATTR_ACCESSTIME | SSH_FILEXFER_ATTR_MODIFYTIME |
SSH_FILEXFER_ATTR_SUBSECOND_TIMES;
return sftp_setstat(sftp, file, &attr);
}
int sftp_symlink(sftp_session sftp, const char *target, const char *dest) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_string target_s;
ssh_string dest_s;
ssh_buffer buffer;
uint32_t id;
if (sftp == NULL)
return -1;
if (target == NULL || dest == NULL) {
ssh_set_error_invalid(sftp->session, __FUNCTION__);
return -1;
}
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return -1;
}
target_s = string_from_char(target);
if (target_s == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return -1;
}
dest_s = string_from_char(dest);
if (dest_s == NULL) {
ssh_set_error_oom(sftp->session);
string_free(target_s);
buffer_free(buffer);
return -1;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(dest_s);
string_free(target_s);
return -1;
}
if (ssh_get_openssh_version(sftp->session)) {
/* TODO check for version number if they ever fix it. */
if (buffer_add_ssh_string(buffer, target_s) < 0 ||
buffer_add_ssh_string(buffer, dest_s) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(dest_s);
string_free(target_s);
return -1;
}
} else {
if (buffer_add_ssh_string(buffer, dest_s) < 0 ||
buffer_add_ssh_string(buffer, target_s) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(dest_s);
string_free(target_s);
return -1;
}
}
if (sftp_packet_write(sftp, SSH_FXP_SYMLINK, buffer) < 0) {
buffer_free(buffer);
string_free(dest_s);
string_free(target_s);
return -1;
}
buffer_free(buffer);
string_free(dest_s);
string_free(target_s);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return -1;
}
msg = sftp_dequeue(sftp, id);
}
/* By specification, this command only returns SSH_FXP_STATUS */
if (msg->packet_type == SSH_FXP_STATUS) {
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return -1;
}
sftp_set_error(sftp, status->status);
switch (status->status) {
case SSH_FX_OK:
status_msg_free(status);
return 0;
default:
break;
}
/*
* The status should be SSH_FX_OK if the command was successful, if it
* didn't, then there was an error
*/
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return -1;
} else {
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to set stats", msg->packet_type);
sftp_message_free(msg);
}
return -1;
}
char *sftp_readlink(sftp_session sftp, const char *path) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_string path_s = NULL;
ssh_string link_s = NULL;
ssh_buffer buffer;
char *lnk;
uint32_t ignored;
uint32_t id;
if (sftp == NULL)
return NULL;
if (path == NULL) {
ssh_set_error_invalid(sftp, __FUNCTION__);
return NULL;
}
if (sftp->version < 3){
ssh_set_error(sftp,SSH_REQUEST_DENIED,"sftp version %d does not support sftp_readlink",sftp->version);
return NULL;
}
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
path_s = string_from_char(path);
if (path_s == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return NULL;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, path_s) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(path_s);
return NULL;
}
if (sftp_packet_write(sftp, SSH_FXP_READLINK, buffer) < 0) {
buffer_free(buffer);
string_free(path_s);
return NULL;
}
buffer_free(buffer);
string_free(path_s);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
if (msg->packet_type == SSH_FXP_NAME) {
/* we don't care about "count" */
buffer_get_u32(msg->payload, &ignored);
/* we only care about the file name string */
link_s = buffer_get_ssh_string(msg->payload);
sftp_message_free(msg);
if (link_s == NULL) {
/* TODO: what error to set here? */
return NULL;
}
lnk = string_to_char(link_s);
string_free(link_s);
return lnk;
} else if (msg->packet_type == SSH_FXP_STATUS) { /* bad response (error) */
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
} else { /* this shouldn't happen */
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to set stats", msg->packet_type);
sftp_message_free(msg);
}
return NULL;
}
static sftp_statvfs_t sftp_parse_statvfs(sftp_session sftp, ssh_buffer buf) {
sftp_statvfs_t statvfs;
uint64_t tmp;
int ok = 0;
statvfs = malloc(sizeof(struct sftp_statvfs_struct));
if (statvfs == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
ZERO_STRUCTP(statvfs);
/* try .. catch */
do {
/* file system block size */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_bsize = ntohll(tmp);
/* fundamental fs block size */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_frsize = ntohll(tmp);
/* number of blocks (unit f_frsize) */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_blocks = ntohll(tmp);
/* free blocks in file system */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_bfree = ntohll(tmp);
/* free blocks for non-root */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_bavail = ntohll(tmp);
/* total file inodes */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_files = ntohll(tmp);
/* free file inodes */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_ffree = ntohll(tmp);
/* free file inodes for to non-root */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_favail = ntohll(tmp);
/* file system id */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_fsid = ntohll(tmp);
/* bit mask of f_flag values */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_flag = ntohll(tmp);
/* maximum filename length */
if (buffer_get_u64(buf, &tmp) != sizeof(uint64_t)) {
break;
}
statvfs->f_namemax = ntohll(tmp);
ok = 1;
} while(0);
if (!ok) {
SAFE_FREE(statvfs);
ssh_set_error(sftp->session, SSH_FATAL, "Invalid statvfs structure");
return NULL;
}
return statvfs;
}
sftp_statvfs_t sftp_statvfs(sftp_session sftp, const char *path) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_string pathstr;
ssh_string ext;
ssh_buffer buffer;
uint32_t id;
if (sftp == NULL)
return NULL;
if (path == NULL) {
ssh_set_error_invalid(sftp->session, __FUNCTION__);
return NULL;
}
if (sftp->version < 3){
ssh_set_error(sftp,SSH_REQUEST_DENIED,"sftp version %d does not support sftp_statvfs",sftp->version);
return NULL;
}
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
ext = string_from_char("statvfs@openssh.com");
if (ext == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return NULL;
}
pathstr = string_from_char(path);
if (pathstr == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(ext);
return NULL;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, ext) < 0 ||
buffer_add_ssh_string(buffer, pathstr) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(ext);
string_free(pathstr);
return NULL;
}
if (sftp_packet_write(sftp, SSH_FXP_EXTENDED, buffer) < 0) {
buffer_free(buffer);
string_free(ext);
string_free(pathstr);
return NULL;
}
buffer_free(buffer);
string_free(ext);
string_free(pathstr);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
if (msg->packet_type == SSH_FXP_EXTENDED_REPLY) {
sftp_statvfs_t buf = sftp_parse_statvfs(sftp, msg->payload);
sftp_message_free(msg);
if (buf == NULL) {
return NULL;
}
return buf;
} else if (msg->packet_type == SSH_FXP_STATUS) { /* bad response (error) */
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
} else { /* this shouldn't happen */
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to get statvfs", msg->packet_type);
sftp_message_free(msg);
}
return NULL;
}
sftp_statvfs_t sftp_fstatvfs(sftp_file file) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
sftp_session sftp;
ssh_string ext;
ssh_buffer buffer;
uint32_t id;
if (file == NULL) {
return NULL;
}
sftp = file->sftp;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
ext = string_from_char("fstatvfs@openssh.com");
if (ext == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return NULL;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, ext) < 0 ||
buffer_add_ssh_string(buffer, file->handle) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(ext);
return NULL;
}
if (sftp_packet_write(sftp, SSH_FXP_EXTENDED, buffer) < 0) {
buffer_free(buffer);
string_free(ext);
return NULL;
}
buffer_free(buffer);
string_free(ext);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
if (msg->packet_type == SSH_FXP_EXTENDED_REPLY) {
sftp_statvfs_t buf = sftp_parse_statvfs(sftp, msg->payload);
sftp_message_free(msg);
if (buf == NULL) {
return NULL;
}
return buf;
} else if (msg->packet_type == SSH_FXP_STATUS) { /* bad response (error) */
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
} else { /* this shouldn't happen */
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to set stats", msg->packet_type);
sftp_message_free(msg);
}
return NULL;
}
void sftp_statvfs_free(sftp_statvfs_t statvfs) {
if (statvfs == NULL) {
return;
}
SAFE_FREE(statvfs);
}
/* another code written by Nick */
char *sftp_canonicalize_path(sftp_session sftp, const char *path) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_string name = NULL;
ssh_string pathstr;
ssh_buffer buffer;
char *cname;
uint32_t ignored;
uint32_t id;
if (sftp == NULL)
return NULL;
if (path == NULL) {
ssh_set_error_invalid(sftp->session, __FUNCTION__);
return NULL;
}
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
pathstr = string_from_char(path);
if (pathstr == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return NULL;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, pathstr) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(pathstr);
return NULL;
}
if (sftp_packet_write(sftp, SSH_FXP_REALPATH, buffer) < 0) {
buffer_free(buffer);
string_free(pathstr);
return NULL;
}
buffer_free(buffer);
string_free(pathstr);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
if (msg->packet_type == SSH_FXP_NAME) {
/* we don't care about "count" */
buffer_get_u32(msg->payload, &ignored);
/* we only care about the file name string */
name = buffer_get_ssh_string(msg->payload);
sftp_message_free(msg);
if (name == NULL) {
/* TODO: error message? */
return NULL;
}
cname = string_to_char(name);
string_free(name);
if (cname == NULL) {
ssh_set_error_oom(sftp->session);
}
return cname;
} else if (msg->packet_type == SSH_FXP_STATUS) { /* bad response (error) */
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
} else { /* this shouldn't happen */
ssh_set_error(sftp->session, SSH_FATAL,
"Received message %d when attempting to set stats", msg->packet_type);
sftp_message_free(msg);
}
return NULL;
}
static sftp_attributes sftp_xstat(sftp_session sftp, const char *path,
int param) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_string pathstr;
ssh_buffer buffer;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(sftp->session);
return NULL;
}
pathstr = string_from_char(path);
if (pathstr == NULL) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
return NULL;
}
id = sftp_get_new_id(sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, pathstr) < 0) {
ssh_set_error_oom(sftp->session);
buffer_free(buffer);
string_free(pathstr);
return NULL;
}
if (sftp_packet_write(sftp, param, buffer) < 0) {
buffer_free(buffer);
string_free(pathstr);
return NULL;
}
buffer_free(buffer);
string_free(pathstr);
while (msg == NULL) {
if (sftp_read_and_dispatch(sftp) < 0) {
return NULL;
}
msg = sftp_dequeue(sftp, id);
}
if (msg->packet_type == SSH_FXP_ATTRS) {
return sftp_parse_attr(sftp, msg->payload, 0);
} else if (msg->packet_type == SSH_FXP_STATUS) {
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
sftp_set_error(sftp, status->status);
ssh_set_error(sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return NULL;
}
ssh_set_error(sftp->session, SSH_FATAL,
"Received mesg %d during stat()", msg->packet_type);
sftp_message_free(msg);
return NULL;
}
sftp_attributes sftp_stat(sftp_session session, const char *path) {
return sftp_xstat(session, path, SSH_FXP_STAT);
}
sftp_attributes sftp_lstat(sftp_session session, const char *path) {
return sftp_xstat(session, path, SSH_FXP_LSTAT);
}
sftp_attributes sftp_fstat(sftp_file file) {
sftp_status_message status = NULL;
sftp_message msg = NULL;
ssh_buffer buffer;
uint32_t id;
buffer = buffer_new();
if (buffer == NULL) {
ssh_set_error_oom(file->sftp->session);
return NULL;
}
id = sftp_get_new_id(file->sftp);
if (buffer_add_u32(buffer, id) < 0 ||
buffer_add_ssh_string(buffer, file->handle) < 0) {
ssh_set_error_oom(file->sftp->session);
buffer_free(buffer);
return NULL;
}
if (sftp_packet_write(file->sftp, SSH_FXP_FSTAT, buffer) < 0) {
buffer_free(buffer);
return NULL;
}
buffer_free(buffer);
while (msg == NULL) {
if (sftp_read_and_dispatch(file->sftp) < 0) {
return NULL;
}
msg = sftp_dequeue(file->sftp, id);
}
if (msg->packet_type == SSH_FXP_ATTRS){
return sftp_parse_attr(file->sftp, msg->payload, 0);
} else if (msg->packet_type == SSH_FXP_STATUS) {
status = parse_status_msg(msg);
sftp_message_free(msg);
if (status == NULL) {
return NULL;
}
ssh_set_error(file->sftp->session, SSH_REQUEST_DENIED,
"SFTP server: %s", status->errormsg);
status_msg_free(status);
return NULL;
}
ssh_set_error(file->sftp->session, SSH_FATAL,
"Received msg %d during fstat()", msg->packet_type);
sftp_message_free(msg);
return NULL;
}
#endif /* WITH_SFTP */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/sftp.c
|
C
|
gpl3
| 79,809
|
/*
* agent.c - ssh agent functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2008-2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/* This file is based on authfd.c from OpenSSH */
/*
* How does the ssh-agent work?
*
* a) client sends a request to get a list of all keys
* the agent returns the cound and all public keys
* b) iterate over them to check if the server likes one
* c) the client sends a sign request to the agent
* type, pubkey as blob, data to sign, flags
* the agent returns the signed data
*/
#ifndef _WIN32
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <poll.h>
#include <unistd.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/agent.h"
#include "libssh/priv.h"
#include "libssh/socket.h"
#include "libssh/buffer.h"
#include "libssh/session.h"
#include "libssh/keys.h"
/* macro to check for "agent failure" message */
#define agent_failed(x) \
(((x) == SSH_AGENT_FAILURE) || ((x) == SSH_COM_AGENT2_FAILURE) || \
((x) == SSH2_AGENT_FAILURE))
static uint32_t agent_get_u32(const void *vp) {
const uint8_t *p = (const uint8_t *)vp;
uint32_t v;
v = (uint32_t)p[0] << 24;
v |= (uint32_t)p[1] << 16;
v |= (uint32_t)p[2] << 8;
v |= (uint32_t)p[3];
return v;
}
static void agent_put_u32(void *vp, uint32_t v) {
uint8_t *p = (uint8_t *)vp;
p[0] = (uint8_t)(v >> 24) & 0xff;
p[1] = (uint8_t)(v >> 16) & 0xff;
p[2] = (uint8_t)(v >> 8) & 0xff;
p[3] = (uint8_t)v & 0xff;
}
static size_t atomicio(struct socket *s, void *buf, size_t n, int do_read) {
char *b = buf;
size_t pos = 0;
ssize_t res;
struct pollfd pfd;
int fd = ssh_socket_get_fd(s);
pfd.fd = fd;
pfd.events = do_read ? POLLIN : POLLOUT;
while (n > pos) {
if (do_read) {
res = read(fd, b + pos, n - pos);
} else {
res = write(fd, b + pos, n - pos);
}
switch (res) {
case -1:
if (errno == EINTR) {
continue;
}
#ifdef EWOULDBLOCK
if (errno == EAGAIN || errno == EWOULDBLOCK) {
#else
if (errno == EAGAIN) {
#endif
(void) poll(&pfd, 1, -1);
continue;
}
return 0;
case 0:
errno = EPIPE;
return pos;
default:
pos += (size_t) res;
}
}
return pos;
}
ssh_agent agent_new(struct ssh_session_struct *session) {
ssh_agent agent = NULL;
agent = malloc(sizeof(struct ssh_agent_struct));
if (agent == NULL) {
return NULL;
}
ZERO_STRUCTP(agent);
agent->count = 0;
agent->sock = ssh_socket_new(session);
if (agent->sock == NULL) {
SAFE_FREE(agent);
return NULL;
}
return agent;
}
void agent_close(struct ssh_agent_struct *agent) {
if (agent == NULL) {
return;
}
if (getenv("SSH_AUTH_SOCK")) {
ssh_socket_close(agent->sock);
}
}
void agent_free(ssh_agent agent) {
if (agent) {
if (agent->ident) {
buffer_free(agent->ident);
}
if (agent->sock) {
agent_close(agent);
ssh_socket_free(agent->sock);
}
SAFE_FREE(agent);
}
}
static int agent_connect(ssh_session session) {
const char *auth_sock = NULL;
if (session == NULL || session->agent == NULL) {
return -1;
}
auth_sock = getenv("SSH_AUTH_SOCK");
if (auth_sock && *auth_sock) {
if (ssh_socket_unix(session->agent->sock, auth_sock) < 0) {
return -1;
}
return 0;
}
return -1;
}
#if 0
static int agent_decode_reply(struct ssh_session_struct *session, int type) {
switch (type) {
case SSH_AGENT_FAILURE:
case SSH2_AGENT_FAILURE:
case SSH_COM_AGENT2_FAILURE:
ssh_log(session, SSH_LOG_RARE, "SSH_AGENT_FAILURE");
return 0;
case SSH_AGENT_SUCCESS:
return 1;
default:
ssh_set_error(session, SSH_FATAL,
"Bad response from authentication agent: %d", type);
break;
}
return -1;
}
#endif
static int agent_talk(struct ssh_session_struct *session,
struct ssh_buffer_struct *request, struct ssh_buffer_struct *reply) {
uint32_t len = 0;
uint8_t payload[1024] = {0};
len = buffer_get_len(request);
ssh_log(session, SSH_LOG_PACKET, "agent_talk - len of request: %u", len);
agent_put_u32(payload, len);
/* send length and then the request packet */
if (atomicio(session->agent->sock, payload, 4, 0) == 4) {
if (atomicio(session->agent->sock, buffer_get_rest(request), len, 0)
!= len) {
ssh_log(session, SSH_LOG_PACKET, "atomicio sending request failed: %s",
strerror(errno));
return -1;
}
} else {
ssh_log(session, SSH_LOG_PACKET,
"atomicio sending request length failed: %s",
strerror(errno));
return -1;
}
/* wait for response, read the length of the response packet */
if (atomicio(session->agent->sock, payload, 4, 1) != 4) {
ssh_log(session, SSH_LOG_PACKET, "atomicio read response length failed: %s",
strerror(errno));
return -1;
}
len = agent_get_u32(payload);
if (len > 256 * 1024) {
ssh_set_error(session, SSH_FATAL,
"Authentication response too long: %u", len);
return -1;
}
ssh_log(session, SSH_LOG_PACKET, "agent_talk - response length: %u", len);
while (len > 0) {
size_t n = len;
if (n > sizeof(payload)) {
n = sizeof(payload);
}
if (atomicio(session->agent->sock, payload, n, 1) != n) {
ssh_log(session, SSH_LOG_RARE,
"Error reading response from authentication socket.");
return -1;
}
if (buffer_add_data(reply, payload, n) < 0) {
ssh_log(session, SSH_LOG_FUNCTIONS,
"Not enough space");
return -1;
}
len -= n;
}
return 0;
}
int agent_get_ident_count(struct ssh_session_struct *session) {
ssh_buffer request = NULL;
ssh_buffer reply = NULL;
unsigned int type = 0;
unsigned int c1 = 0, c2 = 0;
uint8_t buf[4] = {0};
switch (session->version) {
case 1:
c1 = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
c2 = SSH_AGENT_RSA_IDENTITIES_ANSWER;
break;
case 2:
c1 = SSH2_AGENTC_REQUEST_IDENTITIES;
c2 = SSH2_AGENT_IDENTITIES_ANSWER;
break;
default:
return 0;
}
/* send message to the agent requesting the list of identities */
request = buffer_new();
if (buffer_add_u8(request, c1) < 0) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
return -1;
}
reply = buffer_new();
if (reply == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
return -1;
}
if (agent_talk(session, request, reply) < 0) {
buffer_free(request);
return 0;
}
buffer_free(request);
/* get message type and verify the answer */
buffer_get_u8(reply, (uint8_t *) &type);
ssh_log(session, SSH_LOG_PACKET,
"agent_ident_count - answer type: %d, expected answer: %d",
type, c2);
if (agent_failed(type)) {
return 0;
} else if (type != c2) {
ssh_set_error(session, SSH_FATAL,
"Bad authentication reply message type: %d", type);
return -1;
}
buffer_get_u32(reply, (uint32_t *) buf);
session->agent->count = agent_get_u32(buf);
ssh_log(session, SSH_LOG_PACKET, "agent_ident_count - count: %d",
session->agent->count);
if (session->agent->count > 1024) {
ssh_set_error(session, SSH_FATAL,
"Too many identities in authentication reply: %d",
session->agent->count);
buffer_free(reply);
return -1;
}
if (session->agent->ident) {
buffer_reinit(session->agent->ident);
}
session->agent->ident = reply;
return session->agent->count;
}
/* caller has to free commment */
struct ssh_public_key_struct *agent_get_first_ident(struct ssh_session_struct *session,
char **comment) {
if (agent_get_ident_count(session) > 0) {
return agent_get_next_ident(session, comment);
}
return NULL;
}
/* caller has to free commment */
struct ssh_public_key_struct *agent_get_next_ident(struct ssh_session_struct *session,
char **comment) {
struct ssh_public_key_struct *pubkey = NULL;
struct ssh_string_struct *blob = NULL;
struct ssh_string_struct *tmp = NULL;
if (session->agent->count == 0) {
return NULL;
}
switch(session->version) {
case 1:
return NULL;
case 2:
/* get the blob */
blob = buffer_get_ssh_string(session->agent->ident);
if (blob == NULL) {
return NULL;
}
/* get the comment */
tmp = buffer_get_ssh_string(session->agent->ident);
if (tmp == NULL) {
string_free(blob);
return NULL;
}
if (comment) {
*comment = string_to_char(tmp);
} else {
string_free(blob);
string_free(tmp);
return NULL;
}
string_free(tmp);
/* get key from blob */
pubkey = publickey_from_string(session, blob);
string_free(blob);
break;
default:
return NULL;
}
return pubkey;
}
ssh_string agent_sign_data(struct ssh_session_struct *session,
struct ssh_buffer_struct *data,
struct ssh_public_key_struct *pubkey) {
struct ssh_string_struct *blob = NULL;
struct ssh_string_struct *sig = NULL;
struct ssh_buffer_struct *request = NULL;
struct ssh_buffer_struct *reply = NULL;
int type = SSH2_AGENT_FAILURE;
int flags = 0;
uint32_t dlen = 0;
/* create blob from the pubkey */
blob = publickey_to_string(pubkey);
request = buffer_new();
if (request == NULL) {
goto error;
}
/* create request */
if (buffer_add_u8(request, SSH2_AGENTC_SIGN_REQUEST) < 0) {
goto error;
}
/* adds len + blob */
if (buffer_add_ssh_string(request, blob) < 0) {
goto error;
}
/* Add data */
dlen = buffer_get_len(data);
if (buffer_add_u32(request, htonl(dlen)) < 0) {
goto error;
}
if (buffer_add_data(request, buffer_get(data), dlen) < 0) {
goto error;
}
if (buffer_add_u32(request, htonl(flags)) < 0) {
goto error;
}
string_free(blob);
reply = buffer_new();
if (reply == NULL) {
goto error;
}
/* send the request */
if (agent_talk(session, request, reply) < 0) {
buffer_free(request);
return NULL;
}
buffer_free(request);
/* check if reply is valid */
if (buffer_get_u8(reply, (uint8_t *) &type) != sizeof(uint8_t)) {
goto error;
}
if (agent_failed(type)) {
ssh_log(session, SSH_LOG_RARE, "Agent reports failure in signing the key");
buffer_free(reply);
return NULL;
} else if (type != SSH2_AGENT_SIGN_RESPONSE) {
ssh_set_error(session, SSH_FATAL, "Bad authentication response: %d", type);
buffer_free(reply);
return NULL;
}
sig = buffer_get_ssh_string(reply);
buffer_free(reply);
return sig;
error:
ssh_set_error(session, SSH_FATAL, "Not enough memory");
string_free(blob);
buffer_free(request);
buffer_free(reply);
return NULL;
}
int agent_is_running(ssh_session session) {
if (session == NULL || session->agent == NULL) {
return 0;
}
if (ssh_socket_is_open(session->agent->sock)) {
return 1;
} else {
if (agent_connect(session) < 0) {
return 0;
} else {
return 1;
}
}
return 0;
}
#endif /* _WIN32 */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/agent.c
|
C
|
gpl3
| 11,919
|
/*
* error.c - functions for ssh error handling
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdarg.h>
#include "libssh/priv.h"
/**
* @defgroup ssh_error SSH Errors
*
* @brief Functions for error handling.
*/
/**
* @addtogroup ssh_error
* @{
*/
/**
* @internal
*
* @brief Registers an error with a description.
*
* @param error The place to store the error.
*
* @param code The class of error.
*
* @param descr The description, which can be a format string.
*
* @param ... The arguments for the format string.
*/
void ssh_set_error(void *error, int code, const char *descr, ...) {
struct error_struct *err = error;
va_list va;
va_start(va, descr);
vsnprintf(err->error_buffer, ERROR_BUFFERLEN, descr, va);
va_end(va);
err->error_code = code;
}
/**
* @internal
*
* @brief Registers an out of memory error
*
* @param error The place to store the error.
*
*/
void ssh_set_error_oom(void *error) {
struct error_struct *err = error;
strcpy(err->error_buffer, "Out of memory");
err->error_code = SSH_FATAL;
}
/**
* @internal
*
* @brief Registers an invalid argument error
*
* @param error The place to store the error.
*
* @param function The function the error happened in.
*
*/
void ssh_set_error_invalid(void *error, const char *function) {
ssh_set_error(error, SSH_FATAL, "Invalid argument in %s", function);
}
/**
* @brief Retrieve the error text message from the last error.
*
* @param error The SSH session pointer.
*
* @return A static string describing the error.
*/
const char *ssh_get_error(void *error) {
struct error_struct *err = error;
return err->error_buffer;
}
/**
* @brief Retrieve the error code from the last error.
*
* @param error The SSH session pointer.
*
* \return SSH_NO_ERROR No error occurred\n
* SSH_REQUEST_DENIED The last request was denied but situation is
* recoverable\n
* SSH_FATAL A fatal error occurred. This could be an unexpected
* disconnection\n
*
* Other error codes are internal but can be considered same than
* SSH_FATAL.
*/
int ssh_get_error_code(void *error) {
struct error_struct *err = error;
return err->error_code;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/error.c
|
C
|
gpl3
| 3,228
|
/*
* client.c - SSH client functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/socket.h"
#include "libssh/session.h"
#include "libssh/dh.h"
#define set_status(session, status) do {\
if (session->callbacks && session->callbacks->connect_status_function) \
session->callbacks->connect_status_function(session->callbacks->userdata, status); \
} while (0)
/**
* @internal
*
* @brief Get a banner from a socket.
*
* The caller has to free memroy.
*
* @param session The session to get the banner from.
*
* @return A newly allocated string with the banner or NULL on error.
*/
char *ssh_get_banner(ssh_session session) {
char buffer[128] = {0};
char *str = NULL;
int i;
enter_function();
for (i = 0; i < 127; i++) {
if (ssh_socket_read(session->socket, &buffer[i], 1) != SSH_OK) {
ssh_set_error(session, SSH_FATAL, "Remote host closed connection");
leave_function();
return NULL;
}
#ifdef WITH_PCAP
if(session->pcap_ctx && buffer[i] == '\n'){
ssh_pcap_context_write(session->pcap_ctx,SSH_PCAP_DIR_IN,buffer,i+1,i+1);
}
#endif
if (buffer[i] == '\r') {
buffer[i] = '\0';
}
if (buffer[i] == '\n') {
buffer[i] = '\0';
str = strdup(buffer);
if (str == NULL) {
leave_function();
return NULL;
}
leave_function();
return str;
}
}
ssh_set_error(session, SSH_FATAL, "Too large banner");
leave_function();
return NULL;
}
/**
* @internal
*
* @brief Analyze the SSH banner to find out if we have a SSHv1 or SSHv2
* server.
*
* @param session The session to analyze the banner from.
* @param ssh1 The variable which is set if it is a SSHv1 server.
* @param ssh2 The variable which is set if it is a SSHv2 server.
*
* @return 0 on success, < 0 on error.
*
* @see ssh_get_banner()
*/
static int ssh_analyze_banner(ssh_session session, int *ssh1, int *ssh2) {
const char *banner = session->serverbanner;
const char *openssh;
ssh_log(session, SSH_LOG_RARE, "Analyzing banner: %s", banner);
if (strncmp(banner, "SSH-", 4) != 0) {
ssh_set_error(session, SSH_FATAL, "Protocol mismatch: %s", banner);
return -1;
}
/*
* Typical banners e.g. are:
* SSH-1.5-blah
* SSH-1.99-blah
* SSH-2.0-blah
*/
switch(banner[4]) {
case '1':
*ssh1 = 1;
if (banner[6] == '9') {
*ssh2 = 1;
} else {
*ssh2 = 0;
}
break;
case '2':
*ssh1 = 0;
*ssh2 = 1;
break;
default:
ssh_set_error(session, SSH_FATAL, "Protocol mismatch: %s", banner);
return -1;
}
openssh = strstr(banner, "OpenSSH");
if (openssh != NULL) {
int major, minor;
major = strtol(openssh + 8, (char **) NULL, 10);
minor = strtol(openssh + 10, (char **) NULL, 10);
session->openssh = SSH_VERSION_INT(major, minor, 0);
ssh_log(session, SSH_LOG_RARE,
"We are talking to an OpenSSH server version: %d.%d (%x)",
major, minor, session->openssh);
}
return 0;
}
/** @internal
* @brief Sends a SSH banner to the server.
*
* @param session The SSH session to use.
*
* @param server Send client or server banner.
*
* @return 0 on success, < 0 on error.
*/
int ssh_send_banner(ssh_session session, int server) {
const char *banner = NULL;
char buffer[128] = {0};
enter_function();
banner = session->version == 1 ? CLIENTBANNER1 : CLIENTBANNER2;
if (session->xbanner) {
banner = session->xbanner;
}
if (server) {
session->serverbanner = strdup(banner);
if (session->serverbanner == NULL) {
leave_function();
return -1;
}
} else {
session->clientbanner = strdup(banner);
if (session->clientbanner == NULL) {
leave_function();
return -1;
}
}
snprintf(buffer, 128, "%s\r\n", banner);
if (ssh_socket_write(session->socket, buffer, strlen(buffer)) == SSH_ERROR) {
leave_function();
return -1;
}
if (ssh_socket_blocking_flush(session->socket) != SSH_OK) {
leave_function();
return -1;
}
#ifdef WITH_PCAP
if(session->pcap_ctx)
ssh_pcap_context_write(session->pcap_ctx,SSH_PCAP_DIR_OUT,buffer,strlen(buffer),strlen(buffer));
#endif
leave_function();
return 0;
}
#define DH_STATE_INIT 0
#define DH_STATE_INIT_TO_SEND 1
#define DH_STATE_INIT_SENT 2
#define DH_STATE_NEWKEYS_TO_SEND 3
#define DH_STATE_NEWKEYS_SENT 4
#define DH_STATE_FINISHED 5
static int dh_handshake(ssh_session session) {
ssh_string e = NULL;
ssh_string f = NULL;
ssh_string pubkey = NULL;
ssh_string signature = NULL;
int rc = SSH_ERROR;
enter_function();
switch (session->dh_handshake_state) {
case DH_STATE_INIT:
if (buffer_add_u8(session->out_buffer, SSH2_MSG_KEXDH_INIT) < 0) {
goto error;
}
if (dh_generate_x(session) < 0) {
goto error;
}
if (dh_generate_e(session) < 0) {
goto error;
}
e = dh_get_e(session);
if (e == NULL) {
goto error;
}
if (buffer_add_ssh_string(session->out_buffer, e) < 0) {
goto error;
}
string_burn(e);
string_free(e);
e=NULL;
rc = packet_send(session);
if (rc == SSH_ERROR) {
goto error;
}
session->dh_handshake_state = DH_STATE_INIT_TO_SEND;
case DH_STATE_INIT_TO_SEND:
rc = packet_flush(session, 0);
if (rc != SSH_OK) {
goto error;
}
session->dh_handshake_state = DH_STATE_INIT_SENT;
case DH_STATE_INIT_SENT:
rc = packet_wait(session, SSH2_MSG_KEXDH_REPLY, 1);
if (rc != SSH_OK) {
goto error;
}
pubkey = buffer_get_ssh_string(session->in_buffer);
if (pubkey == NULL){
ssh_set_error(session,SSH_FATAL, "No public key in packet");
rc = SSH_ERROR;
goto error;
}
dh_import_pubkey(session, pubkey);
f = buffer_get_ssh_string(session->in_buffer);
if (f == NULL) {
ssh_set_error(session,SSH_FATAL, "No F number in packet");
rc = SSH_ERROR;
goto error;
}
if (dh_import_f(session, f) < 0) {
ssh_set_error(session, SSH_FATAL, "Cannot import f number");
rc = SSH_ERROR;
goto error;
}
string_burn(f);
string_free(f);
f=NULL;
signature = buffer_get_ssh_string(session->in_buffer);
if (signature == NULL) {
ssh_set_error(session, SSH_FATAL, "No signature in packet");
rc = SSH_ERROR;
goto error;
}
session->dh_server_signature = signature;
signature=NULL; /* ownership changed */
if (dh_build_k(session) < 0) {
ssh_set_error(session, SSH_FATAL, "Cannot build k number");
rc = SSH_ERROR;
goto error;
}
/* Send the MSG_NEWKEYS */
if (buffer_add_u8(session->out_buffer, SSH2_MSG_NEWKEYS) < 0) {
rc = SSH_ERROR;
goto error;
}
rc = packet_send(session);
if (rc == SSH_ERROR) {
goto error;
}
session->dh_handshake_state = DH_STATE_NEWKEYS_TO_SEND;
case DH_STATE_NEWKEYS_TO_SEND:
rc = packet_flush(session, 0);
if (rc != SSH_OK) {
goto error;
}
ssh_log(session, SSH_LOG_RARE, "SSH_MSG_NEWKEYS sent\n");
session->dh_handshake_state = DH_STATE_NEWKEYS_SENT;
case DH_STATE_NEWKEYS_SENT:
rc = packet_wait(session, SSH2_MSG_NEWKEYS, 1);
if (rc != SSH_OK) {
goto error;
}
ssh_log(session, SSH_LOG_RARE, "Got SSH_MSG_NEWKEYS\n");
rc = make_sessionid(session);
if (rc != SSH_OK) {
goto error;
}
/*
* Set the cryptographic functions for the next crypto
* (it is needed for generate_session_keys for key lenghts)
*/
if (crypt_set_algorithms(session)) {
rc = SSH_ERROR;
goto error;
}
if (generate_session_keys(session) < 0) {
rc = SSH_ERROR;
goto error;
}
/* Verify the host's signature. FIXME do it sooner */
signature = session->dh_server_signature;
session->dh_server_signature = NULL;
if (signature_verify(session, signature)) {
rc = SSH_ERROR;
goto error;
}
/* forget it for now ... */
string_burn(signature);
string_free(signature);
signature=NULL;
/*
* Once we got SSH2_MSG_NEWKEYS we can switch next_crypto and
* current_crypto
*/
if (session->current_crypto) {
crypto_free(session->current_crypto);
session->current_crypto=NULL;
}
/* FIXME later, include a function to change keys */
session->current_crypto = session->next_crypto;
session->next_crypto = crypto_new();
if (session->next_crypto == NULL) {
rc = SSH_ERROR;
goto error;
}
session->dh_handshake_state = DH_STATE_FINISHED;
leave_function();
return SSH_OK;
default:
ssh_set_error(session, SSH_FATAL, "Invalid state in dh_handshake(): %d",
session->dh_handshake_state);
leave_function();
return SSH_ERROR;
}
/* not reached */
error:
if(e != NULL){
string_burn(e);
string_free(e);
}
if(f != NULL){
string_burn(f);
string_free(f);
}
if(signature != NULL){
string_burn(signature);
string_free(signature);
}
leave_function();
return rc;
}
/**
* @internal
*
* @brief Request a service from the SSH server.
*
* Service requests are for example: ssh-userauth, ssh-connection, etc.
*
* @param session The session to use to ask for a service request.
* @param service The service request.
*
* @return 0 on success, < 0 on error.
*/
int ssh_service_request(ssh_session session, const char *service) {
ssh_string service_s = NULL;
enter_function();
if (buffer_add_u8(session->out_buffer, SSH2_MSG_SERVICE_REQUEST) < 0) {
leave_function();
return -1;
}
service_s = string_from_char(service);
if (service_s == NULL) {
leave_function();
return -1;
}
if (buffer_add_ssh_string(session->out_buffer,service_s) < 0) {
string_free(service_s);
leave_function();
return -1;
}
string_free(service_s);
if (packet_send(session) != SSH_OK) {
ssh_set_error(session, SSH_FATAL,
"Sending SSH2_MSG_SERVICE_REQUEST failed.");
leave_function();
return -1;
}
ssh_log(session, SSH_LOG_PACKET,
"Sent SSH_MSG_SERVICE_REQUEST (service %s)", service);
if (packet_wait(session,SSH2_MSG_SERVICE_ACCEPT,1) != SSH_OK) {
ssh_set_error(session, SSH_FATAL, "Did not receive SERVICE_ACCEPT");
leave_function();
return -1;
}
ssh_log(session, SSH_LOG_PACKET,
"Received SSH_MSG_SERVICE_ACCEPT (service %s)", service);
leave_function();
return 0;
}
/** \addtogroup ssh_session
* @{
*/
/** \brief connect to the ssh server
* \param session ssh session
* \return SSH_OK on success, SSH_ERROR on error
* \see ssh_new()
* \see ssh_disconnect()
*/
int ssh_connect(ssh_session session) {
int ssh1 = 0;
int ssh2 = 0;
int fd = -1;
int ret;
if (session == NULL) {
ssh_set_error(session, SSH_FATAL, "Invalid session pointer");
return SSH_ERROR;
}
enter_function();
session->alive = 0;
session->client = 1;
if (ssh_init() < 0) {
leave_function();
return SSH_ERROR;
}
if (session->fd == -1 && session->host == NULL &&
session->ProxyCommand == NULL) {
ssh_set_error(session, SSH_FATAL, "Hostname required");
leave_function();
return SSH_ERROR;
}
ret = ssh_options_apply(session);
if (ret < 0) {
ssh_set_error(session, SSH_FATAL, "Couldn't apply options");
leave_function();
return SSH_ERROR;
}
if (session->fd != -1) {
fd = session->fd;
#ifndef _WIN32
} else if (session->ProxyCommand != NULL) {
fd=ssh_socket_connect_proxycommand(session, session->ProxyCommand);
#endif
} else {
fd = ssh_connect_host(session, session->host, session->bindaddr,
session->port, session->timeout, session->timeout_usec);
}
if (fd < 0) {
leave_function();
return SSH_ERROR;
}
set_status(session, 0.2);
ssh_socket_set_fd(session->socket, fd);
session->alive = 1;
session->serverbanner = ssh_get_banner(session);
if (session->serverbanner == NULL) {
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
set_status(session, 0.4);
ssh_log(session, SSH_LOG_RARE,
"SSH server banner: %s", session->serverbanner);
/* Here we analyse the different protocols the server allows. */
if (ssh_analyze_banner(session, &ssh1, &ssh2) < 0) {
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
/* Here we decide which version of the protocol to use. */
if (ssh2 && session->ssh2) {
session->version = 2;
} else if(ssh1 && session->ssh1) {
session->version = 1;
} else {
ssh_set_error(session, SSH_FATAL,
"No version of SSH protocol usable (banner: %s)",
session->serverbanner);
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
if (ssh_send_banner(session, 0) < 0) {
ssh_set_error(session, SSH_FATAL, "Sending the banner failed");
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
set_status(session, 0.5);
switch (session->version) {
case 2:
if (ssh_get_kex(session,0) < 0) {
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
set_status(session,0.6);
ssh_list_kex(session, &session->server_kex);
if (set_kex(session) < 0) {
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
if (ssh_send_kex(session, 0) < 0) {
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
set_status(session,0.8);
if (dh_handshake(session) < 0) {
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
set_status(session,1.0);
session->connected = 1;
break;
case 1:
if (ssh_get_kex1(session) < 0) {
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
set_status(session,0.6);
session->connected = 1;
break;
}
leave_function();
return 0;
}
/**
* @brief Get the issue banner from the server.
*
* This is the banner showing a disclaimer to users who log in,
* typically their right or the fact that they will be monitored.
*
* @param session The SSH session to use.
*
* @return A newly allocated string with the banner, NULL on error.
*/
char *ssh_get_issue_banner(ssh_session session) {
if (session == NULL || session->banner == NULL) {
return NULL;
}
return string_to_char(session->banner);
}
/**
* @brief Get the version of the OpenSSH server, if it is not an OpenSSH server
* then 0 will be returned.
*
* You can use the SSH_VERSION_INT macro to compare version numbers.
*
* @param session The SSH session to use.
*
* @return The version number if available, 0 otherwise.
*/
int ssh_get_openssh_version(ssh_session session) {
if (session == NULL) {
return 0;
}
return session->openssh;
}
/**
* @brief Disconnect from a session (client or server).
* The session can then be reused to open a new session.
*
* @param session The SSH session to disconnect.
*/
void ssh_disconnect(ssh_session session) {
ssh_string str = NULL;
if (session == NULL) {
return;
}
enter_function();
if (ssh_socket_is_open(session->socket)) {
if (buffer_add_u8(session->out_buffer, SSH2_MSG_DISCONNECT) < 0) {
goto error;
}
if (buffer_add_u32(session->out_buffer,
htonl(SSH2_DISCONNECT_BY_APPLICATION)) < 0) {
goto error;
}
str = string_from_char("Bye Bye");
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(session->out_buffer,str) < 0) {
string_free(str);
goto error;
}
string_free(str);
packet_send(session);
ssh_socket_close(session->socket);
}
session->alive = 0;
error:
leave_function();
}
const char *ssh_copyright(void) {
return SSH_STRINGIFY(LIBSSH_VERSION) " (c) 2003-2008 Aris Adamantiadis "
"(aris@0xbadc0de.be) Distributed under the LGPL, please refer to COPYING"
"file for information about your rights";
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/client.c
|
C
|
gpl3
| 17,846
|
/*
* string.c - ssh string functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/string.h"
/** \defgroup ssh_string SSH Strings
* \brief string manipulations
*/
/** \addtogroup ssh_string
* @{ */
/**
* \brief Creates a new SSH String object
* \param size size of the string
* \return the newly allocated string
*/
struct ssh_string_struct *string_new(size_t size) {
struct ssh_string_struct *str = NULL;
str = malloc(size + 4);
if (str == NULL) {
return NULL;
}
str->size = htonl(size);
return str;
}
/**
* @brief Fill a string with given data. The string should be big enough.
*
* @param s An allocated string to fill with data.
*
* @param data The data to fill the string with.
*
* @param len Size of data.
*
* @return 0 on success, < 0 on error.
*/
int string_fill(struct ssh_string_struct *s, const void *data, size_t len) {
if ((s == NULL) || (data == NULL) ||
(len == 0) || (len > s->size)) {
return -1;
}
memcpy(s->string, data, len);
return 0;
}
/**
* \brief Creates a ssh stream using a C string
* \param what source 0-terminated C string
* \return the newly allocated string.
* \warning The nul byte is not copied nor counted in the ouput string.
*/
struct ssh_string_struct *string_from_char(const char *what) {
struct ssh_string_struct *ptr = NULL;
size_t len = strlen(what);
ptr = malloc(4 + len);
if (ptr == NULL) {
return NULL;
}
ptr->size = htonl(len);
memcpy(ptr->string, what, len);
return ptr;
}
/**
* \brief returns the size of a SSH string
* \param s the input SSH string
* \return size of the content of str, 0 on error
*/
size_t string_len(struct ssh_string_struct *s) {
if (s == NULL) {
return ntohl(0);
}
return ntohl(s->size);
}
/**
* \brief convert a SSH string to a C nul-terminated string
* \param s the input SSH string
* \return a malloc'ed string pointer.
* \warning If the input SSH string contains zeroes, some parts of
* the output string may not be readable with regular libc functions.
*/
char *string_to_char(struct ssh_string_struct *s) {
size_t len = ntohl(s->size) + 1;
char *new = malloc(len);
if (new == NULL) {
return NULL;
}
memcpy(new, s->string, len - 1);
new[len - 1] = '\0';
return new;
}
/**
* @brief Copy a string, return a newly allocated string. The caller has to
* free the string.
*
* @param s String to copy.
*
* @return Newly allocated copy of the string, NULL on error.
*/
struct ssh_string_struct *string_copy(struct ssh_string_struct *s) {
struct ssh_string_struct *new = malloc(ntohl(s->size) + 4);
if (new == NULL) {
return NULL;
}
new->size = s->size;
memcpy(new->string, s->string, ntohl(s->size));
return new;
}
/** \brief destroy data in a string so it couldn't appear in a core dump
* \param s string to burn
*/
void string_burn(struct ssh_string_struct *s) {
if (s == NULL) {
return;
}
memset(s->string, 'X', string_len(s));
}
/**
* @brief Get the payload of the string.
*
* @param s The string to get the data from.
*
* @return Return the data of the string or NULL on error.
*/
void *string_data(struct ssh_string_struct *s) {
if (s == NULL) {
return NULL;
}
return s->string;
}
/**
* \brief deallocate a STRING object
* \param s String to delete
*/
void string_free(struct ssh_string_struct *s) {
SAFE_FREE(s);
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/string.c
|
C
|
gpl3
| 4,462
|
/*
* log.c - logging and debugging functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "libssh/priv.h"
#include "libssh/session.h"
/**
* @defgroup ssh_log SSH Logging
*
* @brief Logging functions for debugging and problem resolving
*/
/** \addtogroup ssh_log
* @{ */
/**
* @brief Log a SSH event.
*
* @param session The SSH session.
*
* @param verbosity The verbosity of the event.
*
* @param format The format string of the log entry.
*/
void ssh_log(ssh_session session, int verbosity, const char *format, ...) {
char buffer[1024];
char indent[256];
int min;
va_list va;
if (verbosity <= session->log_verbosity) {
va_start(va, format);
vsnprintf(buffer, sizeof(buffer), format, va);
va_end(va);
if (session->callbacks && session->callbacks->log_function) {
session->callbacks->log_function(session, verbosity, buffer,
session->callbacks->userdata);
} else if (verbosity == SSH_LOG_FUNCTIONS) {
if (session->log_indent > 255) {
min = 255;
} else {
min = session->log_indent;
}
memset(indent, ' ', min);
indent[min] = '\0';
fprintf(stderr, "[func] %s%s\n", indent, buffer);
} else {
fprintf(stderr, "[%d] %s\n", verbosity, buffer);
}
}
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/log.c
|
C
|
gpl3
| 2,238
|
/*
* session.c - non-networking functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2005-2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <string.h>
#include <stdlib.h>
#include "libssh/libssh.h"
#include "libssh/priv.h"
#include "libssh/server.h"
#include "libssh/socket.h"
#include "libssh/agent.h"
#include "libssh/packet.h"
#include "libssh/session.h"
#include "libssh/misc.h"
#include "libssh/ssh2.h"
#include "libssh/buffer.h"
#define FIRST_CHANNEL 42 // why not ? it helps to find bugs.
/** \defgroup ssh_session SSH Session
* \brief functions that manage a session
*/
/** \addtogroup ssh_session
* @{ */
/** \brief creates a new ssh session
* \returns new ssh_session pointer
*/
ssh_session ssh_new(void) {
ssh_session session;
char *id;
int rc;
session = malloc(sizeof (struct ssh_session_struct));
if (session == NULL) {
return NULL;
}
ZERO_STRUCTP(session);
session->next_crypto = crypto_new();
if (session->next_crypto == NULL) {
goto err;
}
session->socket = ssh_socket_new(session);
if (session->socket == NULL) {
goto err;
}
session->out_buffer = buffer_new();
if (session->out_buffer == NULL) {
goto err;
}
session->in_buffer=buffer_new();
if (session->in_buffer == NULL) {
goto err;
}
session->alive = 0;
session->auth_methods = 0;
session->blocking = 1;
session->log_indent = 0;
session->maxchannel = FIRST_CHANNEL;
/* options */
session->port = 22;
session->fd = -1;
session->ssh2 = 1;
#ifdef WITH_SSH1
session->ssh1 = 1;
#else
session->ssh1 = 0;
#endif
#ifndef _WIN32
session->agent = agent_new(session);
if (session->agent == NULL) {
goto err;
}
#endif /* _WIN32 */
session->identity = ssh_list_new();
if (session->identity == NULL) {
goto err;
}
id = strdup("SSH_DIR/id_rsa");
if (id == NULL) {
goto err;
}
rc = ssh_list_append(session->identity, id);
if (rc == SSH_ERROR) {
goto err;
}
id = strdup("SSH_DIR/id_dsa");
if (id == NULL) {
goto err;
}
rc = ssh_list_append(session->identity, id);
if (rc == SSH_ERROR) {
goto err;
}
id = strdup("SSH_DIR/identity");
if (id == NULL) {
goto err;
}
rc = ssh_list_append(session->identity, id);
if (rc == SSH_ERROR) {
goto err;
}
return session;
err:
ssh_free(session);
return NULL;
}
/**
* @brief deallocate a session handle
* @see ssh_disconnect()
* @see ssh_new()
*/
void ssh_free(ssh_session session) {
int i;
enter_function();
if (session == NULL) {
return;
}
SAFE_FREE(session->serverbanner);
SAFE_FREE(session->clientbanner);
SAFE_FREE(session->banner);
#ifdef WITH_PCAP
if(session->pcap_ctx){
ssh_pcap_context_free(session->pcap_ctx);
session->pcap_ctx=NULL;
}
#endif
buffer_free(session->in_buffer);
buffer_free(session->out_buffer);
session->in_buffer=session->out_buffer=NULL;
crypto_free(session->current_crypto);
crypto_free(session->next_crypto);
ssh_socket_free(session->socket);
/* delete all channels */
while (session->channels) {
channel_free(session->channels);
}
#ifndef _WIN32
agent_free(session->agent);
#endif /* _WIN32 */
if (session->client_kex.methods) {
for (i = 0; i < 10; i++) {
SAFE_FREE(session->client_kex.methods[i]);
}
}
if (session->server_kex.methods) {
for (i = 0; i < 10; i++) {
SAFE_FREE(session->server_kex.methods[i]);
}
}
SAFE_FREE(session->client_kex.methods);
SAFE_FREE(session->server_kex.methods);
privatekey_free(session->dsa_key);
privatekey_free(session->rsa_key);
if(session->ssh_message_list){
ssh_message msg;
while((msg=ssh_list_pop_head(ssh_message ,session->ssh_message_list))
!= NULL){
ssh_message_free(msg);
}
ssh_list_free(session->ssh_message_list);
}
if (session->identity) {
char *id;
for (id = ssh_list_pop_head(char *, session->identity);
id != NULL;
id = ssh_list_pop_head(char *, session->identity)) {
SAFE_FREE(id);
}
ssh_list_free(session->identity);
}
/* options */
SAFE_FREE(session->username);
SAFE_FREE(session->host);
SAFE_FREE(session->sshdir);
SAFE_FREE(session->knownhosts);
SAFE_FREE(session->ProxyCommand);
for (i = 0; i < 10; i++) {
if (session->wanted_methods[i]) {
SAFE_FREE(session->wanted_methods[i]);
}
}
/* burn connection, it could hang sensitive datas */
ZERO_STRUCTP(session);
SAFE_FREE(session);
}
/** \brief disconnect impolitely from remote host by closing the socket.
* Suitable if you forked and want to destroy this session.
* \param session current ssh session
*/
void ssh_silent_disconnect(ssh_session session) {
enter_function();
if (session == NULL) {
return;
}
ssh_socket_close(session->socket);
session->alive = 0;
ssh_disconnect(session);
leave_function();
}
/** \brief set the session in blocking/nonblocking mode
* \param session ssh session
* \param blocking zero for nonblocking mode
* \bug nonblocking code is in development and won't work as expected
*/
void ssh_set_blocking(ssh_session session, int blocking) {
if (session == NULL) {
return;
}
session->blocking = blocking ? 1 : 0;
}
/** In case you'd need the file descriptor of the connection
* to the server/client
* \brief recover the fd of connection
* \param session ssh session
* \return file descriptor of the connection, or -1 if it is
* not connected
*/
socket_t ssh_get_fd(ssh_session session) {
if (session == NULL) {
return -1;
}
return ssh_socket_get_fd(session->socket);
}
/** \brief say to the session it has data to read on the file descriptor without blocking
* \param session ssh session
*/
void ssh_set_fd_toread(ssh_session session) {
if (session == NULL) {
return;
}
ssh_socket_set_toread(session->socket);
}
/** \brief say the session it may write to the file descriptor without blocking
* \param session ssh session
*/
void ssh_set_fd_towrite(ssh_session session) {
if (session == NULL) {
return;
}
ssh_socket_set_towrite(session->socket);
}
/** \brief say the session it has an exception to catch on the file descriptor
* \param session ssh session
*/
void ssh_set_fd_except(ssh_session session) {
if (session == NULL) {
return;
}
ssh_socket_set_except(session->socket);
}
/** \warning I don't remember if this should be internal or not
*/
/* looks if there is data to read on the socket and parse it. */
int ssh_handle_packets(ssh_session session) {
int w = 0;
int e = 0;
int rc = -1;
enter_function();
do {
rc = ssh_socket_poll(session->socket, &w, &e);
if (rc <= 0) {
/* error or no data available */
leave_function();
return rc;
}
/* if an exception happened, it will be trapped by packet_read() */
if ((packet_read(session) != SSH_OK) ||
(packet_translate(session) != SSH_OK)) {
leave_function();
return -1;
}
packet_parse(session);
} while(rc > 0);
leave_function();
return rc;
}
/**
* @brief Get session status
*
* @param session The ssh session to use.
*
* @returns A bitmask including SSH_CLOSED, SSH_READ_PENDING or SSH_CLOSED_ERROR
* which respectively means the session is closed, has data to read on
* the connection socket and session was closed due to an error.
*/
int ssh_get_status(ssh_session session) {
int socketstate;
int r = 0;
if (session == NULL) {
return 0;
}
socketstate = ssh_socket_get_status(session->socket);
if (session->closed) {
r |= SSH_CLOSED;
}
if (socketstate & SSH_READ_PENDING) {
r |= SSH_READ_PENDING;
}
if (session->closed && (socketstate & SSH_CLOSED_ERROR)) {
r |= SSH_CLOSED_ERROR;
}
return r;
}
/** \brief get the disconnect message from the server
* \param session ssh session
* \return message sent by the server along with the disconnect, or NULL in which case the reason of the disconnect may be found with ssh_get_error.
* \see ssh_get_error()
*/
const char *ssh_get_disconnect_message(ssh_session session) {
if (session == NULL) {
return NULL;
}
if (!session->closed) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Connection not closed yet");
} else if(session->closed_by_except) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Connection closed by socket error");
} else if(!session->discon_msg) {
ssh_set_error(session, SSH_FATAL,
"Connection correctly closed but no disconnect message");
} else {
return session->discon_msg;
}
return NULL;
}
/**
* @brief Get the protocol version of the session.
*
* @param session The ssh session to use.
*
* @return 1 or 2, for ssh1 or ssh2, < 0 on error.
*/
int ssh_get_version(ssh_session session) {
if (session == NULL) {
return -1;
}
return session->version;
}
/**
* @internal
* @handle a SSH_MSG_GLOBAL_REQUEST packet
* @param session the SSH session
*/
void ssh_global_request_handle(ssh_session session){
ssh_string type;
char *type_c;
uint32_t needreply;
type=buffer_get_ssh_string(session->in_buffer);
buffer_get_u32(session->in_buffer,&needreply);
if(type==NULL)
return;
type_c=string_to_char(type);
if(!type_c)
return;
ssh_log(session, SSH_LOG_PROTOCOL,
"Received SSH_GLOBAL_REQUEST %s (wantreply=%d)",type_c,needreply);
SAFE_FREE(type_c);
string_free(type);
if(needreply != 0){
buffer_add_u8(session->out_buffer,SSH2_MSG_REQUEST_FAILURE);
packet_send(session);
}
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/session.c
|
C
|
gpl3
| 10,459
|
/*
* connect.c - handles connections to ssh servers
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
/*
* Only use Windows API functions available on Windows 2000 SP4 or later.
* The available constants are in <sdkddkver.h>.
* http://msdn.microsoft.com/en-us/library/aa383745.aspx
* http://blogs.msdn.com/oldnewthing/archive/2007/04/11/2079137.aspx
*/
#undef _WIN32_WINNT
#ifdef HAVE_WSPIAPI_H
#define _WIN32_WINNT 0x0500 /* _WIN32_WINNT_WIN2K */
#undef NTDDI_VERSION
#define NTDDI_VERSION 0x05000400 /* NTDDI_WIN2KSP4 */
#else
#define _WIN32_WINNT 0x0501 /* _WIN32_WINNT_WINXP */
#undef NTDDI_VERSION
#define NTDDI_VERSION 0x05010000 /* NTDDI_WINXP */
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
/* <wspiapi.h> is necessary for getaddrinfo before Windows XP, but it isn't
* available on some platforms like MinGW. */
#ifdef HAVE_WSPIAPI_H
#include <wspiapi.h>
#endif
#else /* _WIN32 */
#include <netdb.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#endif /* _WIN32 */
#include "libssh/priv.h"
#include "libssh/socket.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#ifndef HAVE_SELECT
#error "Your system must have select()"
#endif
#ifndef HAVE_GETADDRINFO
#error "Your system must have getaddrinfo()"
#endif
#ifdef HAVE_REGCOMP
/* don't declare gnu extended regexp's */
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE
#endif
#include <regex.h>
#endif /* HAVE_REGCOMP */
#ifdef _WIN32
static void sock_set_nonblocking(socket_t sock) {
u_long nonblocking = 1;
ioctlsocket(sock, FIONBIO, &nonblocking);
}
static void sock_set_blocking(socket_t sock) {
u_long nonblocking = 0;
ioctlsocket(sock, FIONBIO, &nonblocking);
}
#ifndef gai_strerror
char WSAAPI *gai_strerrorA(int code) {
static char buf[256];
snprintf(buf, sizeof(buf), "Undetermined error code (%d)", code);
return buf;
}
#endif /* gai_strerror */
#else /* _WIN32 */
static void sock_set_nonblocking(socket_t sock) {
fcntl(sock, F_SETFL, O_NONBLOCK);
}
static void sock_set_blocking(socket_t sock) {
fcntl(sock, F_SETFL, 0);
}
#endif /* _WIN32 */
#ifdef HAVE_REGCOMP
static regex_t *ip_regex = NULL;
/** @internal
* @brief initializes and compile the regexp to be used for IP matching
* @returns -1 on error (and error message is set)
* @returns 0 on success
*/
int ssh_regex_init(){
if(ip_regex==NULL){
int err;
regex_t *regex=malloc(sizeof (regex_t));
ZERO_STRUCTP(regex);
err=regcomp(regex,"^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$",REG_EXTENDED | REG_NOSUB);
if(err != 0){
char buffer[128];
regerror(err,regex,buffer,sizeof(buffer));
fprintf(stderr,"Error while compiling regular expression : %s\n",buffer);
SAFE_FREE(regex);
return -1;
}
ip_regex=regex;
}
return 0;
}
/** @internal
* @brief clean up the IP regexp
*/
void ssh_regex_finalize(){
if(ip_regex){
regfree(ip_regex);
SAFE_FREE(ip_regex);
}
}
#else /* HAVE_REGCOMP */
int ssh_regex_init(){
return 0;
}
void ssh_regex_finalize(){
}
#endif
static int ssh_connect_socket_close(socket_t s){
#ifdef _WIN32
return closesocket(s);
#else
return close(s);
#endif
}
static int getai(ssh_session session, const char *host, int port, struct addrinfo **ai) {
const char *service = NULL;
struct addrinfo hints;
char s_port[10];
ZERO_STRUCT(hints);
hints.ai_protocol = IPPROTO_TCP;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (port == 0) {
hints.ai_flags = AI_PASSIVE;
} else {
snprintf(s_port, sizeof(s_port), "%hu", port);
service = s_port;
#ifdef AI_NUMERICSERV
hints.ai_flags=AI_NUMERICSERV;
#endif
}
#ifdef HAVE_REGCOMP
if(regexec(ip_regex,host,0,NULL,0) == 0){
/* this is an IP address */
ssh_log(session,SSH_LOG_PACKET,"host %s matches an IP address",host);
hints.ai_flags |= AI_NUMERICHOST;
}
#endif
return getaddrinfo(host, service, &hints, ai);
}
static int ssh_connect_ai_timeout(ssh_session session, const char *host,
int port, struct addrinfo *ai, long timeout, long usec, socket_t s) {
struct timeval to;
fd_set set;
int rc = 0;
unsigned int len = sizeof(rc);
enter_function();
to.tv_sec = timeout;
to.tv_usec = usec;
sock_set_nonblocking(s);
ssh_log(session, SSH_LOG_RARE, "Trying to connect to host: %s:%d with "
"timeout %ld.%ld", host, port, timeout, usec);
/* The return value is checked later */
connect(s, ai->ai_addr, ai->ai_addrlen);
freeaddrinfo(ai);
FD_ZERO(&set);
FD_SET(s, &set);
rc = select(s + 1, NULL, &set, NULL, &to);
if (rc == 0) {
/* timeout */
ssh_set_error(session, SSH_FATAL,
"Timeout while connecting to %s:%d", host, port);
ssh_connect_socket_close(s);
leave_function();
return -1;
}
if (rc < 0) {
ssh_set_error(session, SSH_FATAL,
"Select error: %s", strerror(errno));
ssh_connect_socket_close(s);
leave_function();
return -1;
}
rc = 0;
/* Get connect(2) return code. Zero means no error */
getsockopt(s, SOL_SOCKET, SO_ERROR,(char *) &rc, &len);
if (rc != 0) {
ssh_set_error(session, SSH_FATAL,
"Connect to %s:%d failed: %s", host, port, strerror(rc));
ssh_connect_socket_close(s);
leave_function();
return -1;
}
/* s is connected ? */
ssh_log(session, SSH_LOG_PACKET, "Socket connected with timeout\n");
sock_set_blocking(s);
leave_function();
return s;
}
/**
* @internal
*
* @brief Connect to an IPv4 or IPv6 host specified by its IP address or
* hostname.
*
* @returns A file descriptor, < 0 on error.
*/
socket_t ssh_connect_host(ssh_session session, const char *host,
const char *bind_addr, int port, long timeout, long usec) {
socket_t s = -1;
int rc;
struct addrinfo *ai;
struct addrinfo *itr;
enter_function();
rc = getai(session,host, port, &ai);
if (rc != 0) {
ssh_set_error(session, SSH_FATAL,
"Failed to resolve hostname %s (%s)", host, gai_strerror(rc));
leave_function();
return -1;
}
for (itr = ai; itr != NULL; itr = itr->ai_next){
/* create socket */
s = socket(itr->ai_family, itr->ai_socktype, itr->ai_protocol);
if (s < 0) {
ssh_set_error(session, SSH_FATAL,
"Socket create failed: %s", strerror(errno));
continue;
}
if (bind_addr) {
struct addrinfo *bind_ai;
struct addrinfo *bind_itr;
ssh_log(session, SSH_LOG_PACKET, "Resolving %s\n", bind_addr);
rc = getai(session,bind_addr, 0, &bind_ai);
if (rc != 0) {
ssh_set_error(session, SSH_FATAL,
"Failed to resolve bind address %s (%s)",
bind_addr,
gai_strerror(rc));
leave_function();
return -1;
}
for (bind_itr = bind_ai; bind_itr != NULL; bind_itr = bind_itr->ai_next) {
if (bind(s, bind_itr->ai_addr, bind_itr->ai_addrlen) < 0) {
ssh_set_error(session, SSH_FATAL,
"Binding local address: %s", strerror(errno));
continue;
} else {
break;
}
}
freeaddrinfo(bind_ai);
/* Cannot bind to any local addresses */
if (bind_itr == NULL) {
ssh_connect_socket_close(s);
s = -1;
continue;
}
}
if (timeout || usec) {
socket_t ret = ssh_connect_ai_timeout(session, host, port, itr,
timeout, usec, s);
leave_function();
return ret;
}
if (connect(s, itr->ai_addr, itr->ai_addrlen) < 0) {
ssh_set_error(session, SSH_FATAL, "Connect failed: %s", strerror(errno));
ssh_connect_socket_close(s);
s = -1;
continue;
} else {
/* We are connected */
break;
}
}
freeaddrinfo(ai);
leave_function();
return s;
}
/**
* @addtogroup ssh_session
* @{ */
/**
* @brief A wrapper for the select syscall
*
* This functions acts more or less like the select(2) syscall.\n
* There is no support for writing or exceptions.\n
*
* @param channels Arrays of channels pointers terminated by a NULL.
* It is never rewritten.
*
* @param outchannels Arrays of same size that "channels", there is no need
* to initialize it.
*
* @param maxfd Maximum +1 file descriptor from readfds.
*
* @param readfds A fd_set of file descriptors to be select'ed for
* reading.
*
* @param timeout A timeout for the select.
*
* @return -1 if an error occured. E_INTR if it was interrupted. In that case,
* just restart it.
*
* @warning libssh is not threadsafe here. That means that if a signal is caught
* during the processing of this function, you cannot call ssh functions on
* sessions that are busy with ssh_select().
*
* @see select(2)
*/
int ssh_select(ssh_channel *channels, ssh_channel *outchannels, socket_t maxfd,
fd_set *readfds, struct timeval *timeout) {
struct timeval zerotime;
fd_set localset, localset2;
int rep;
int set;
int i;
int j;
zerotime.tv_sec = 0;
zerotime.tv_usec = 0;
/*
* First, poll the maxfd file descriptors from the user with a zero-second
* timeout. They have the bigger priority.
*/
if (maxfd > 0) {
memcpy(&localset, readfds, sizeof(fd_set));
rep = select(maxfd, &localset, NULL, NULL, &zerotime);
/* catch the eventual errors */
if (rep==-1) {
return -1;
}
}
/* Poll every channel */
j = 0;
for (i = 0; channels[i]; i++) {
if (channels[i]->session->alive) {
if(channel_poll(channels[i], 0) > 0) {
outchannels[j] = channels[i];
j++;
} else {
if(channel_poll(channels[i], 1) > 0) {
outchannels[j] = channels[i];
j++;
}
}
}
}
outchannels[j] = NULL;
/* Look into the localset for active fd */
set = 0;
for (i = 0; (i < maxfd) && !set; i++) {
if (FD_ISSET(i, &localset)) {
set = 1;
}
}
/* j != 0 means a channel has data */
if( (j != 0) || (set != 0)) {
if(maxfd > 0) {
memcpy(readfds, &localset, sizeof(fd_set));
}
return 0;
}
/*
* At this point, not any channel had any data ready for reading, nor any fd
* had data for reading.
*/
memcpy(&localset, readfds, sizeof(fd_set));
for (i = 0; channels[i]; i++) {
if (channels[i]->session->alive) {
ssh_socket_fd_set(channels[i]->session->socket, &localset, &maxfd);
}
}
rep = select(maxfd, &localset, NULL, NULL, timeout);
if (rep == -1 && errno == EINTR) {
/* Interrupted by a signal */
return SSH_EINTR;
}
if (rep == -1) {
/*
* Was the error due to a libssh's channel or from a closed descriptor from
* the user? User closed descriptors have been caught in the first select
* and not closed since that moment. That case shouldn't occur at all
*/
return -1;
}
/* Set the data_to_read flag on each session */
for (i = 0; channels[i]; i++) {
if (channels[i]->session->alive &&
ssh_socket_fd_isset(channels[i]->session->socket,&localset)) {
ssh_socket_set_toread(channels[i]->session->socket);
}
}
/* Now, test each channel */
j = 0;
for (i = 0; channels[i]; i++) {
if (channels[i]->session->alive &&
ssh_socket_fd_isset(channels[i]->session->socket,&localset)) {
if ((channel_poll(channels[i],0) > 0) ||
(channel_poll(channels[i], 1) > 0)) {
outchannels[j] = channels[i];
j++;
}
}
}
outchannels[j] = NULL;
FD_ZERO(&localset2);
for (i = 0; i < maxfd; i++) {
if (FD_ISSET(i, readfds) && FD_ISSET(i, &localset)) {
FD_SET(i, &localset2);
}
}
memcpy(readfds, &localset2, sizeof(fd_set));
return 0;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/connect.c
|
C
|
gpl3
| 12,687
|
/*
* scp - SSH scp wrapper functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis <aris@0xbadc0de.be>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdio.h>
#include <string.h>
#include "libssh/priv.h"
#include "libssh/scp.h"
/** @defgroup ssh_scp SSH-scp
* @brief SCP protocol over SSH functions
* @addtogroup ssh_scp
* @{
*/
/** @brief Creates a new scp session
* @param session the SSH session to use
* @param mode one of SSH_SCP_WRITE or SSH_SCP_READ, depending if you need to drop files remotely or read them.
* It is not possible to combine read and write.
* @param location The directory in which write or read will be done. Any push or pull will be relative
* to this place
* @returns NULL if the creation was impossible.
* @returns a ssh_scp handle if it worked.
*/
ssh_scp ssh_scp_new(ssh_session session, int mode, const char *location){
ssh_scp scp=malloc(sizeof(struct ssh_scp_struct));
if(scp == NULL){
ssh_set_error(session,SSH_FATAL,"Error allocating memory for ssh_scp");
return NULL;
}
ZERO_STRUCTP(scp);
if((mode&~SSH_SCP_RECURSIVE) != SSH_SCP_WRITE && (mode &~SSH_SCP_RECURSIVE) != SSH_SCP_READ){
ssh_set_error(session,SSH_FATAL,"Invalid mode %d for ssh_scp_new()",mode);
ssh_scp_free(scp);
return NULL;
}
scp->location=strdup(location);
if (scp->location == NULL) {
ssh_set_error(session,SSH_FATAL,"Error allocating memory for ssh_scp");
ssh_scp_free(scp);
return NULL;
}
scp->session=session;
scp->mode=mode & ~SSH_SCP_RECURSIVE;
scp->recursive = (mode & SSH_SCP_RECURSIVE) != 0;
scp->channel=NULL;
scp->state=SSH_SCP_NEW;
return scp;
}
int ssh_scp_init(ssh_scp scp){
int r;
char execbuffer[1024];
uint8_t code;
if(scp->state != SSH_SCP_NEW){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_init called under invalid state");
return SSH_ERROR;
}
ssh_log(scp->session,SSH_LOG_PROTOCOL,"Initializing scp session %s %son location '%s'",
scp->mode==SSH_SCP_WRITE?"write":"read",
scp->recursive?"recursive ":"",
scp->location);
scp->channel=channel_new(scp->session);
if(scp->channel == NULL){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
r= channel_open_session(scp->channel);
if(r==SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
if(scp->mode == SSH_SCP_WRITE)
snprintf(execbuffer,sizeof(execbuffer),"scp -t %s %s",
scp->recursive ? "-r":"", scp->location);
else
snprintf(execbuffer,sizeof(execbuffer),"scp -f %s %s",
scp->recursive ? "-r":"", scp->location);
if(channel_request_exec(scp->channel,execbuffer) == SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
if(scp->mode == SSH_SCP_WRITE){
r=channel_read(scp->channel,&code,1,0);
if(code != 0){
ssh_set_error(scp->session,SSH_FATAL, "scp status code %ud not valid", code);
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
} else {
channel_write(scp->channel,"",1);
}
if(scp->mode == SSH_SCP_WRITE)
scp->state=SSH_SCP_WRITE_INITED;
else
scp->state=SSH_SCP_READ_INITED;
return SSH_OK;
}
int ssh_scp_close(ssh_scp scp){
char buffer[128];
int err;
if(scp->channel != NULL){
if(channel_send_eof(scp->channel) == SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
/* avoid situations where data are buffered and
* not yet stored on disk. This can happen if the close is sent
* before we got the EOF back
*/
while(!channel_is_eof(scp->channel)){
err=channel_read(scp->channel,buffer,sizeof(buffer),0);
if(err==SSH_ERROR)
break;
}
if(channel_close(scp->channel) == SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
channel_free(scp->channel);
scp->channel=NULL;
}
scp->state=SSH_SCP_NEW;
return SSH_OK;
}
void ssh_scp_free(ssh_scp scp){
if(scp->state != SSH_SCP_NEW)
ssh_scp_close(scp);
if(scp->channel)
channel_free(scp->channel);
SAFE_FREE(scp->location);
SAFE_FREE(scp->request_name);
SAFE_FREE(scp->warning);
SAFE_FREE(scp);
}
/** @brief creates a directory in a scp in sink mode
* @param scp the scp handle.
* @param dirname Name of the directory being created.
* @param mode Unix permissions for the new directory, e.g. 0755.
* @returns SSH_OK if the directory was created.
* @returns SSH_ERROR if an error happened.
* @see ssh_scp_leave_directory
*/
int ssh_scp_push_directory(ssh_scp scp, const char *dirname, int mode){
char buffer[1024];
int r;
uint8_t code;
char *dir;
char *perms;
if(scp->state != SSH_SCP_WRITE_INITED){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_push_directory called under invalid state");
return SSH_ERROR;
}
dir=ssh_basename(dirname);
perms=ssh_scp_string_mode(mode);
snprintf(buffer, sizeof(buffer), "D%s 0 %s\n", perms, dir);
SAFE_FREE(dir);
SAFE_FREE(perms);
r=channel_write(scp->channel,buffer,strlen(buffer));
if(r==SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
r=channel_read(scp->channel,&code,1,0);
if(code != 0){
ssh_set_error(scp->session,SSH_FATAL, "scp status code %ud not valid", code);
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
return SSH_OK;
}
/**
* @brief Leaves a directory
* @returns SSH_OK if the directory was created.
* @returns SSH_ERROR if an error happened.
* @see ssh_scp_push_directory
*/
int ssh_scp_leave_directory(ssh_scp scp){
char buffer[]="E\n";
int r;
uint8_t code;
if(scp->state != SSH_SCP_WRITE_INITED){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_leave_directory called under invalid state");
return SSH_ERROR;
}
r=channel_write(scp->channel,buffer,strlen(buffer));
if(r==SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
r=channel_read(scp->channel,&code,1,0);
if(code != 0){
ssh_set_error(scp->session,SSH_FATAL, "scp status code %ud not valid", code);
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
return SSH_OK;
}
/** @brief initializes the sending of a file to a scp in sink mode
* @param scp the scp handle.
* @param filename Name of the file being sent. It should not contain any path indicator
* @param size Exact size in bytes of the file being sent.
* @param mode Unix permissions for the new file, e.g. 0644
* @returns SSH_OK if the file is ready to be sent.
* @returns SSH_ERROR if an error happened.
*/
int ssh_scp_push_file(ssh_scp scp, const char *filename, size_t size, int mode){
char buffer[1024];
int r;
uint8_t code;
char *file;
char *perms;
if(scp->state != SSH_SCP_WRITE_INITED){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_push_file called under invalid state");
return SSH_ERROR;
}
file=ssh_basename(filename);
perms=ssh_scp_string_mode(mode);
ssh_log(scp->session,SSH_LOG_PROTOCOL,"SCP pushing file %s, size %" PRIdS " with permissions '%s'",file,size,perms);
snprintf(buffer, sizeof(buffer), "C%s %" PRIdS " %s\n", perms, size, file);
SAFE_FREE(file);
SAFE_FREE(perms);
r=channel_write(scp->channel,buffer,strlen(buffer));
if(r==SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
r=channel_read(scp->channel,&code,1,0);
if(code != 0){
ssh_set_error(scp->session,SSH_FATAL, "scp status code %ud not valid", code);
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
scp->filelen = size;
scp->processed = 0;
scp->state=SSH_SCP_WRITE_WRITING;
return SSH_OK;
}
/** @brief waits for a response of the scp server
* @internal
* @param response pointer where the response message must be
* copied if any. This pointer must then be free'd.
* @returns the return code.
* @returns SSH_ERROR a error occured
*/
int ssh_scp_response(ssh_scp scp, char **response){
unsigned char code;
int r;
char msg[128];
r=channel_read(scp->channel,&code,1,0);
if(r == SSH_ERROR)
return SSH_ERROR;
if(code == 0)
return 0;
if(code > 2){
ssh_set_error(scp->session,SSH_FATAL, "SCP: invalid status code %ud received", code);
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
r=ssh_scp_read_string(scp,msg,sizeof(msg));
if(r==SSH_ERROR)
return r;
/* Warning */
if(code == 1){
ssh_set_error(scp->session,SSH_REQUEST_DENIED, "SCP: Warning: status code 1 received: %s", msg);
ssh_log(scp->session,SSH_LOG_RARE,"SCP: Warning: status code 1 received: %s", msg);
if(response)
*response=strdup(msg);
return 1;
}
if(code == 2){
ssh_set_error(scp->session,SSH_FATAL, "SCP: Error: status code 2 received: %s", msg);
if(response)
*response=strdup(msg);
return 2;
}
/* Not reached */
return SSH_ERROR;
}
/** @brief Write into a remote scp file
* @param scp the scp handle.
* @param buffer the buffer to write
* @param len the number of bytes to write
* @returns SSH_OK the write was successful
* @returns SSH_ERROR an error happened while writing
*/
int ssh_scp_write(ssh_scp scp, const void *buffer, size_t len){
int w;
//int r;
//uint8_t code;
if(scp->state != SSH_SCP_WRITE_WRITING){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_write called under invalid state");
return SSH_ERROR;
}
if(scp->processed + len > scp->filelen)
len = scp->filelen - scp->processed;
/* hack to avoid waiting for window change */
channel_poll(scp->channel,0);
w=channel_write(scp->channel,buffer,len);
if(w != SSH_ERROR)
scp->processed += w;
else {
scp->state=SSH_SCP_ERROR;
//return=channel_get_exit_status(scp->channel);
return SSH_ERROR;
}
/* Check if we arrived at end of file */
if(scp->processed == scp->filelen) {
/* r=channel_read(scp->channel,&code,1,0);
if(r==SSH_ERROR){
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
if(code != 0){
ssh_set_error(scp->session,SSH_FATAL, "scp status code %ud not valid", code);
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
*/
scp->processed=scp->filelen=0;
scp->state=SSH_SCP_WRITE_INITED;
}
return SSH_OK;
}
/**
* @brief reads a string on a channel, terminated by '\n'
* @param scp the scp handle.
* @param buffer pointer to a buffer to place the string
* @param len size of the buffer in bytes. If the string is bigger
* than len-1, only len-1 bytes are read and the string
* is null-terminated.
* @returns SSH_OK The string was read
* @returns SSH_ERROR Error happened while reading
*/
int ssh_scp_read_string(ssh_scp scp, char *buffer, size_t len){
size_t r=0;
int err=SSH_OK;
while(r<len-1){
err=channel_read(scp->channel,&buffer[r],1,0);
if(err==SSH_ERROR){
break;
}
if(err==0){
ssh_set_error(scp->session,SSH_FATAL,"End of file while reading string");
err=SSH_ERROR;
break;
}
r++;
if(buffer[r-1] == '\n')
break;
}
buffer[r]=0;
return err;
}
/** @brief waits for a scp request (file, directory)
* @returns SSH_ERROR Some error happened
* @returns SSH_SCP_REQUEST_NEWFILE The other side is sending a file
* @returns SSH_SCP_REQUEST_NEWDIRECTORY The other side is sending a directory
* @returns SSH_SCP_REQUEST_END_DIRECTORY The other side has finished with the current directory
* @see ssh_scp_read
* @see ssh_scp_deny_request
* @see ssh_scp_accept_request
*/
int ssh_scp_pull_request(ssh_scp scp){
char buffer[4096];
char *mode=NULL;
char *p,*tmp;
size_t size;
char *name=NULL;
int err;
if(scp->state != SSH_SCP_READ_INITED){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_pull_request called under invalid state");
return SSH_ERROR;
}
err=ssh_scp_read_string(scp,buffer,sizeof(buffer));
if(err==SSH_ERROR){
if(channel_is_eof(scp->channel)){
scp->state=SSH_SCP_TERMINATED;
return SSH_SCP_REQUEST_EOF;
}
return err;
}
p=strchr(buffer,'\n');
if(p!=NULL)
*p='\0';
ssh_log(scp->session,SSH_LOG_PROTOCOL,"Received SCP request: '%s'",buffer);
switch(buffer[0]){
case 'C':
/* File */
case 'D':
/* Directory */
p=strchr(buffer,' ');
if(p==NULL)
goto error;
*p='\0';
p++;
//mode=strdup(&buffer[1]);
scp->request_mode=ssh_scp_integer_mode(&buffer[1]);
tmp=p;
p=strchr(p,' ');
if(p==NULL)
goto error;
*p=0;
size=strtoull(tmp,NULL,10);
p++;
name=strdup(p);
SAFE_FREE(scp->request_name);
scp->request_name=name;
if(buffer[0]=='C'){
scp->filelen=size;
scp->request_type=SSH_SCP_REQUEST_NEWFILE;
} else {
scp->filelen='0';
scp->request_type=SSH_SCP_REQUEST_NEWDIR;
}
scp->state=SSH_SCP_READ_REQUESTED;
scp->processed = 0;
return scp->request_type;
break;
case 'E':
scp->request_type=SSH_SCP_REQUEST_ENDDIR;
channel_write(scp->channel,"",1);
return scp->request_type;
case 0x1:
ssh_set_error(scp->session,SSH_REQUEST_DENIED,"SCP: Warning: %s",&buffer[1]);
scp->request_type=SSH_SCP_REQUEST_WARNING;
SAFE_FREE(scp->warning);
scp->warning=strdup(&buffer[1]);
return scp->request_type;
case 0x2:
ssh_set_error(scp->session,SSH_FATAL,"SCP: Error: %s",&buffer[1]);
return SSH_ERROR;
case 'T':
/* Timestamp */
default:
ssh_set_error(scp->session,SSH_FATAL,"Unhandled message: (%d)%s",buffer[0],buffer);
return SSH_ERROR;
}
/* a parsing error occured */
error:
SAFE_FREE(name);
SAFE_FREE(mode);
ssh_set_error(scp->session,SSH_FATAL,"Parsing error while parsing message: %s",buffer);
return SSH_ERROR;
}
/**
* @brief denies the transfer of a file or creation of a directory
* coming from the remote party
* @param scp the scp handle.
* @param reason nul-terminated string with a human-readable explanation
* of the deny
* @returns SSH_OK the message was sent
* @returns SSH_ERROR Error sending the message, or sending it in a bad state
*/
int ssh_scp_deny_request(ssh_scp scp, const char *reason){
char buffer[4096];
int err;
if(scp->state != SSH_SCP_READ_REQUESTED){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_deny_request called under invalid state");
return SSH_ERROR;
}
snprintf(buffer,sizeof(buffer),"%c%s\n",2,reason);
err=channel_write(scp->channel,buffer,strlen(buffer));
if(err==SSH_ERROR) {
return SSH_ERROR;
}
else {
scp->state=SSH_SCP_READ_INITED;
return SSH_OK;
}
}
/**
* @brief accepts transfer of a file or creation of a directory
* coming from the remote party
* @param scp the scp handle.
* @returns SSH_OK the message was sent
* @returns SSH_ERROR Error sending the message, or sending it in a bad state
*/
int ssh_scp_accept_request(ssh_scp scp){
char buffer[]={0x00};
int err;
if(scp->state != SSH_SCP_READ_REQUESTED){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_deny_request called under invalid state");
return SSH_ERROR;
}
err=channel_write(scp->channel,buffer,1);
if(err==SSH_ERROR) {
return SSH_ERROR;
}
if(scp->request_type==SSH_SCP_REQUEST_NEWFILE)
scp->state=SSH_SCP_READ_READING;
else
scp->state=SSH_SCP_READ_INITED;
return SSH_OK;
}
/** @brief Read from a remote scp file
* @param scp the scp handle.
* @param buffer Destination buffer
* @param size Size of the buffer
* @returns Number of bytes read
* @returns SSH_ERROR An error happened while reading
*/
int ssh_scp_read(ssh_scp scp, void *buffer, size_t size){
int r;
int code;
if(scp->state == SSH_SCP_READ_REQUESTED && scp->request_type == SSH_SCP_REQUEST_NEWFILE){
r=ssh_scp_accept_request(scp);
if(r==SSH_ERROR)
return r;
}
if(scp->state != SSH_SCP_READ_READING){
ssh_set_error(scp->session,SSH_FATAL,"ssh_scp_read called under invalid state");
return SSH_ERROR;
}
if(scp->processed + size > scp->filelen)
size = scp->filelen - scp->processed;
if(size > 65536)
size=65536; /* avoid too large reads */
r=channel_read(scp->channel,buffer,size,0);
if(r != SSH_ERROR)
scp->processed += r;
else {
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
/* Check if we arrived at end of file */
if(scp->processed == scp->filelen) {
scp->processed=scp->filelen=0;
channel_write(scp->channel,"",1);
code=ssh_scp_response(scp,NULL);
if(code == 0){
scp->state=SSH_SCP_READ_INITED;
return r;
}
if(code==1){
scp->state=SSH_SCP_READ_INITED;
return SSH_ERROR;
}
scp->state=SSH_SCP_ERROR;
return SSH_ERROR;
}
return r;
}
/** @brief Gets the name of the directory or file being
* pushed from the other party
* @returns file name. Should not be freed.
*/
const char *ssh_scp_request_get_filename(ssh_scp scp){
return scp->request_name;
}
/**@brief Gets the permissions of the directory or file being
* pushed from the other party
* @returns Unix permission, e.g 0644.
*/
int ssh_scp_request_get_permissions(ssh_scp scp){
return scp->request_mode;
}
/** @brief Gets the size of the file being pushed
* from the other party
* @returns Numeric size of the file being read.
*/
size_t ssh_scp_request_get_size(ssh_scp scp){
return scp->filelen;
}
/** @brief Converts a scp text mode to an integer one
* @param mode mode to convert, e.g. "0644"
* @returns integer value, e.g. 420 for "0644"
*/
int ssh_scp_integer_mode(const char *mode){
int value=strtoul(mode,NULL,8) & 0xffff;
return value;
}
/** @brief Converts a unix mode into a scp string one.
* @param mode mode to convert, e.g. 420 or 0644
* @returns pointer to a malloc'ed string containing the scp mode,
* e.g. "0644".
*/
char *ssh_scp_string_mode(int mode){
char buffer[16];
snprintf(buffer,sizeof(buffer),"%.4o",mode);
return strdup(buffer);
}
/** @brief Gets the warning string
* @returns Warning string. Should not be freed.
*/
const char *ssh_scp_request_get_warning(ssh_scp scp){
return scp->warning;
}
/** @} */
|
zzlydm-fbbs
|
libssh/scp.c
|
C
|
gpl3
| 18,582
|
/*
* auth1.c - authentication with SSH protocols
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
* Copyright (c) 2008-2009 Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/buffer.h"
#include "libssh/agent.h"
#include "libssh/keyfiles.h"
#include "libssh/misc.h"
#include "libssh/packet.h"
#include "libssh/session.h"
#include "libssh/keys.h"
/** \defgroup ssh_auth SSH Authentication functions
* \brief functions to authenticate to servers
*/
/** \addtogroup ssh_auth
* @{ */
static int ask_userauth(ssh_session session) {
int rc = 0;
enter_function();
if (session->auth_service_asked) {
rc = 0;
} else if (ssh_service_request(session,"ssh-userauth")) {
rc = -1;
} else {
session->auth_service_asked++;
}
leave_function();
return rc;
}
static int wait_auth_status(ssh_session session, int kbdint) {
char *auth_methods = NULL;
ssh_string auth;
int rc = SSH_AUTH_ERROR;
int cont = 1;
uint8_t partial = 0;
enter_function();
while (cont) {
if (packet_read(session) != SSH_OK) {
break;
}
if (packet_translate(session) != SSH_OK) {
break;
}
switch (session->in_packet.type) {
case SSH2_MSG_USERAUTH_FAILURE:
auth = buffer_get_ssh_string(session->in_buffer);
if (auth == NULL || buffer_get_u8(session->in_buffer, &partial) != 1) {
ssh_set_error(session, SSH_FATAL,
"Invalid SSH_MSG_USERAUTH_FAILURE message");
leave_function();
return SSH_AUTH_ERROR;
}
auth_methods = string_to_char(auth);
if (auth_methods == NULL) {
ssh_set_error(session, SSH_FATAL,
"Not enough space");
string_free(auth);
leave_function();
return SSH_AUTH_ERROR;
}
if (partial) {
rc = SSH_AUTH_PARTIAL;
ssh_set_error(session, SSH_NO_ERROR,
"Partial success. Authentication that can continue: %s",
auth_methods);
} else {
rc = SSH_AUTH_DENIED;
ssh_set_error(session, SSH_REQUEST_DENIED,
"Access denied. Authentication that can continue: %s",
auth_methods);
session->auth_methods = 0;
if (strstr(auth_methods, "password") != NULL) {
session->auth_methods |= SSH_AUTH_METHOD_PASSWORD;
}
if (strstr(auth_methods, "keyboard-interactive") != NULL) {
session->auth_methods |= SSH_AUTH_METHOD_INTERACTIVE;
}
if (strstr(auth_methods, "publickey") != NULL) {
session->auth_methods |= SSH_AUTH_METHOD_PUBLICKEY;
}
if (strstr(auth_methods, "hostbased") != NULL) {
session->auth_methods |= SSH_AUTH_METHOD_HOSTBASED;
}
}
string_free(auth);
SAFE_FREE(auth_methods);
cont = 0;
break;
case SSH2_MSG_USERAUTH_PK_OK:
/* SSH monkeys have defined the same number for both */
/* SSH_MSG_USERAUTH_PK_OK and SSH_MSG_USERAUTH_INFO_REQUEST */
/* which is not really smart; */
/*case SSH2_MSG_USERAUTH_INFO_REQUEST: */
if (kbdint) {
rc = SSH_AUTH_INFO;
cont = 0;
break;
}
/* continue through success */
case SSH2_MSG_USERAUTH_SUCCESS:
rc = SSH_AUTH_SUCCESS;
cont = 0;
break;
case SSH2_MSG_USERAUTH_BANNER:
{
ssh_string banner;
banner = buffer_get_ssh_string(session->in_buffer);
if (banner == NULL) {
ssh_log(session, SSH_LOG_PACKET,
"The banner message was invalid. Continuing though\n");
break;
}
ssh_log(session, SSH_LOG_PACKET,
"Received a message banner\n");
string_free(session->banner); /* erase the older one */
session->banner = banner;
break;
}
default:
packet_parse(session);
break;
}
}
leave_function();
return rc;
}
int ssh_auth_list(ssh_session session) {
if (session == NULL) {
return -1;
}
return session->auth_methods;
}
int ssh_userauth_list(ssh_session session, const char *username) {
if (session == NULL || username == NULL) {
return SSH_AUTH_ERROR;
}
if (session->auth_methods == 0) {
ssh_userauth_none(session, username);
}
return ssh_auth_list(session);
}
/* use the "none" authentication question */
/**
* @brief Try to authenticate through the "none" method.
*
* @param session The ssh session to use.
*
* @param username The username to authenticate. You can specify NULL if
* ssh_option_set_username() has been used. You cannot try
* two different logins in a row.
*
* @returns SSH_AUTH_ERROR: A serious error happened.\n
* SSH_AUTH_DENIED: Authentication failed: use another method\n
* SSH_AUTH_PARTIAL: You've been partially authenticated, you still
* have to use another method\n
* SSH_AUTH_SUCCESS: Authentication success
*/
int ssh_userauth_none(ssh_session session, const char *username) {
ssh_string user = NULL;
ssh_string service = NULL;
ssh_string method = NULL;
int rc = SSH_AUTH_ERROR;
enter_function();
#ifdef WITH_SSH1
if (session->version == 1) {
ssh_userauth1_none(session, username);
leave_function();
return rc;
}
#endif
if (username == NULL) {
if (session->username == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_USER, NULL) < 0) {
leave_function();
return rc;
}
}
user = string_from_char(session->username);
} else {
user = string_from_char(username);
}
if (user == NULL) {
leave_function();
return rc;
}
if (ask_userauth(session) < 0) {
string_free(user);
leave_function();
return rc;
}
method = string_from_char("none");
if (method == NULL) {
goto error;
}
service = string_from_char("ssh-connection");
if (service == NULL) {
goto error;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_REQUEST) < 0 ||
buffer_add_ssh_string(session->out_buffer, user) < 0 ||
buffer_add_ssh_string(session->out_buffer, service) < 0 ||
buffer_add_ssh_string(session->out_buffer, method) < 0) {
goto error;
}
string_free(service);
string_free(method);
string_free(user);
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
rc = wait_auth_status(session, 0);
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(service);
string_free(method);
string_free(user);
leave_function();
return rc;
}
/**
* @brief Try to authenticate through public key.
*
* @param session The ssh session to use.
*
* @param username The username to authenticate. You can specify NULL if
* ssh_option_set_username() has been used. You cannot try
* two different logins in a row.
*
* @param type The type of the public key. This value is given by
* publickey_from_file().
*
* @param publickey A public key returned by publickey_from_file().
*
* @returns SSH_AUTH_ERROR: A serious error happened.\n
* SSH_AUTH_DENIED: The server doesn't accept that public key as an
* authentication token. Try another key or another
* method.\n
* SSH_AUTH_PARTIAL: You've been partially authenticated, you still
* have to use another method.\n
* SSH_AUTH_SUCCESS: The public key is accepted, you want now to use
* ssh_userauth_pubkey().
*
* @see publickey_from_file()
* @see privatekey_from_file()
* @see ssh_userauth_pubkey()
*/
int ssh_userauth_offer_pubkey(ssh_session session, const char *username,
int type, ssh_string publickey) {
ssh_string user = NULL;
ssh_string service = NULL;
ssh_string method = NULL;
ssh_string algo = NULL;
int rc = SSH_AUTH_ERROR;
enter_function();
#ifdef WITH_SSH1
if (session->version == 1) {
ssh_userauth1_offer_pubkey(session, username, type, publickey);
leave_function();
return rc;
}
#endif
if (username == NULL) {
if (session->username == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_USER, NULL) < 0) {
leave_function();
return rc;
}
}
user = string_from_char(session->username);
} else {
user = string_from_char(username);
}
if (user == NULL) {
leave_function();
return rc;
}
if (ask_userauth(session) < 0) {
string_free(user);
leave_function();
return rc;
}
service = string_from_char("ssh-connection");
if (service == NULL) {
goto error;
}
method = string_from_char("publickey");
if (method == NULL) {
goto error;
}
algo = string_from_char(ssh_type_to_char(type));
if (algo == NULL) {
goto error;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_REQUEST) < 0 ||
buffer_add_ssh_string(session->out_buffer, user) < 0 ||
buffer_add_ssh_string(session->out_buffer, service) < 0 ||
buffer_add_ssh_string(session->out_buffer, method) < 0 ||
buffer_add_u8(session->out_buffer, 0) < 0 ||
buffer_add_ssh_string(session->out_buffer, algo) < 0 ||
buffer_add_ssh_string(session->out_buffer, publickey) < 0) {
goto error;
}
string_free(user);
string_free(method);
string_free(service);
string_free(algo);
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
rc = wait_auth_status(session,0);
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(user);
string_free(method);
string_free(service);
string_free(algo);
leave_function();
return rc;
}
/**
* @brief Try to authenticate through public key.
*
* @param session The ssh session to use.
*
* @param username The username to authenticate. You can specify NULL if
* ssh_option_set_username() has been used. You cannot try
* two different logins in a row.
*
* @param publickey A public key returned by publickey_from_file().
*
* @param privatekey A private key returned by privatekey_from_file().
*
* @returns SSH_AUTH_ERROR: A serious error happened.\n
* SSH_AUTH_DENIED: Authentication failed: use another method.\n
* SSH_AUTH_PARTIAL: You've been partially authenticated, you still
* have to use another method.\n
* SSH_AUTH_SUCCESS: Authentication successful.
*
* @see publickey_from_file()
* @see privatekey_from_file()
* @see privatekey_free()
* @see ssh_userauth_offer_pubkey()
*/
int ssh_userauth_pubkey(ssh_session session, const char *username,
ssh_string publickey, ssh_private_key privatekey) {
ssh_string user = NULL;
ssh_string service = NULL;
ssh_string method = NULL;
ssh_string algo = NULL;
ssh_string sign = NULL;
int rc = SSH_AUTH_ERROR;
enter_function();
#if 0
if (session->version == 1) {
return ssh_userauth1_pubkey(session, username, publickey, privatekey);
}
#endif
if (username == NULL) {
if (session->username == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_USER, NULL) < 0) {
leave_function();
return rc;
}
}
user = string_from_char(session->username);
} else {
user = string_from_char(username);
}
if (user == NULL) {
leave_function();
return rc;
}
if (ask_userauth(session) < 0) {
string_free(user);
leave_function();
return rc;
}
service = string_from_char("ssh-connection");
if (service == NULL) {
goto error;
}
method = string_from_char("publickey");
if (method == NULL) {
goto error;
}
algo = string_from_char(ssh_type_to_char(privatekey->type));
if (algo == NULL) {
goto error;
}
/* we said previously the public key was accepted */
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_REQUEST) < 0 ||
buffer_add_ssh_string(session->out_buffer, user) < 0 ||
buffer_add_ssh_string(session->out_buffer, service) < 0 ||
buffer_add_ssh_string(session->out_buffer, method) < 0 ||
buffer_add_u8(session->out_buffer, 1) < 0 ||
buffer_add_ssh_string(session->out_buffer, algo) < 0 ||
buffer_add_ssh_string(session->out_buffer, publickey) < 0) {
goto error;
}
string_free(user);
string_free(service);
string_free(method);
string_free(algo);
sign = ssh_do_sign(session,session->out_buffer, privatekey);
if (sign) {
if (buffer_add_ssh_string(session->out_buffer,sign) < 0) {
goto error;
}
string_free(sign);
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
rc = wait_auth_status(session,0);
}
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(user);
string_free(service);
string_free(method);
string_free(algo);
leave_function();
return rc;
}
#ifndef _WIN32
/**
* @brief Try to authenticate through public key with an ssh agent.
*
* @param session The ssh session to use.
*
* @param username The username to authenticate. You can specify NULL if
* ssh_option_set_username() has been used. You cannot try
* two different logins in a row.
*
* @param publickey The public key provided by the agent.
*
* @returns SSH_AUTH_ERROR: A serious error happened.\n
* SSH_AUTH_DENIED: Authentication failed: use another method.\n
* SSH_AUTH_PARTIAL: You've been partially authenticated, you still
* have to use another method.\n
* SSH_AUTH_SUCCESS: Authentication successful.
*
* @see publickey_from_file()
* @see privatekey_from_file()
* @see privatekey_free()
* @see ssh_userauth_offer_pubkey()
*/
int ssh_userauth_agent_pubkey(ssh_session session, const char *username,
ssh_public_key publickey) {
ssh_string user = NULL;
ssh_string service = NULL;
ssh_string method = NULL;
ssh_string algo = NULL;
ssh_string key = NULL;
ssh_string sign = NULL;
int rc = SSH_AUTH_ERROR;
enter_function();
if (! agent_is_running(session)) {
return rc;
}
if (username == NULL) {
if (session->username == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_USER, NULL) < 0) {
leave_function();
return rc;
}
}
user = string_from_char(session->username);
} else {
user = string_from_char(username);
}
if (user == NULL) {
leave_function();
return rc;
}
if (ask_userauth(session) < 0) {
string_free(user);
leave_function();
return rc;
}
service = string_from_char("ssh-connection");
if (service == NULL) {
goto error;
}
method = string_from_char("publickey");
if (method == NULL) {
goto error;
}
algo = string_from_char(ssh_type_to_char(publickey->type));
if (algo == NULL) {
goto error;
}
key = publickey_to_string(publickey);
if (key == NULL) {
goto error;
}
/* we said previously the public key was accepted */
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_REQUEST) < 0 ||
buffer_add_ssh_string(session->out_buffer, user) < 0 ||
buffer_add_ssh_string(session->out_buffer, service) < 0 ||
buffer_add_ssh_string(session->out_buffer, method) < 0 ||
buffer_add_u8(session->out_buffer, 1) < 0 ||
buffer_add_ssh_string(session->out_buffer, algo) < 0 ||
buffer_add_ssh_string(session->out_buffer, key) < 0) {
goto error;
}
sign = ssh_do_sign_with_agent(session, session->out_buffer, publickey);
if (sign) {
if (buffer_add_ssh_string(session->out_buffer, sign) < 0) {
goto error;
}
string_free(sign);
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
rc = wait_auth_status(session,0);
}
string_free(user);
string_free(service);
string_free(method);
string_free(algo);
string_free(key);
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(sign);
string_free(user);
string_free(service);
string_free(method);
string_free(algo);
string_free(key);
leave_function();
return rc;
}
#endif /* _WIN32 */
/**
* @brief Try to authenticate by password.
*
* @param session The ssh session to use.
*
* @param username The username to authenticate. You can specify NULL if
* ssh_option_set_username() has been used. You cannot try
* two different logins in a row.
*
* @param password The password to use. Take care to clean it after
* the authentication.
*
* @returns SSH_AUTH_ERROR: A serious error happened.\n
* SSH_AUTH_DENIED: Authentication failed: use another method.\n
* SSH_AUTH_PARTIAL: You've been partially authenticated, you still
* have to use another method.\n
* SSH_AUTH_SUCCESS: Authentication successful.
*
* @see ssh_userauth_kbdint()
* @see BURN_STRING
*/
int ssh_userauth_password(ssh_session session, const char *username,
const char *password) {
ssh_string user = NULL;
ssh_string service = NULL;
ssh_string method = NULL;
ssh_string pwd = NULL;
int rc = SSH_AUTH_ERROR;
enter_function();
#ifdef WITH_SSH1
if (session->version == 1) {
rc = ssh_userauth1_password(session, username, password);
leave_function();
return rc;
}
#endif
if (username == NULL) {
if (session->username == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_USER, NULL) < 0) {
leave_function();
return rc;
}
}
user = string_from_char(session->username);
} else {
user = string_from_char(username);
}
if (user == NULL) {
leave_function();
return rc;
}
if (ask_userauth(session) < 0) {
string_free(user);
leave_function();
return rc;
}
service = string_from_char("ssh-connection");
if (service == NULL) {
goto error;
}
method = string_from_char("password");
if (method == NULL) {
goto error;
}
pwd = string_from_char(password);
if (pwd == NULL) {
goto error;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_REQUEST) < 0 ||
buffer_add_ssh_string(session->out_buffer, user) < 0 ||
buffer_add_ssh_string(session->out_buffer, service) < 0 ||
buffer_add_ssh_string(session->out_buffer, method) < 0 ||
buffer_add_u8(session->out_buffer, 0) < 0 ||
buffer_add_ssh_string(session->out_buffer, pwd) < 0) {
goto error;
}
string_free(user);
string_free(service);
string_free(method);
string_burn(pwd);
string_free(pwd);
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
rc = wait_auth_status(session, 0);
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(user);
string_free(service);
string_free(method);
string_burn(pwd);
string_free(pwd);
leave_function();
return rc;
}
/**
* @brief Tries to automaticaly authenticate with public key and "none"
*
* It may fail, for instance it doesn't ask for a password and uses a default
* asker for passphrases (in case the private key is encrypted).
*
* @param session The ssh session to authenticate with.
*
* @param passphrase Use this passphrase to unlock the privatekey. Use NULL
* if you don't want to use a passphrase or the user
* should be asked.
*
* @returns SSH_AUTH_ERROR: A serious error happened\n
* SSH_AUTH_DENIED: Authentication failed: use another method\n
* SSH_AUTH_PARTIAL: You've been partially authenticated, you still
* have to use another method\n
* SSH_AUTH_SUCCESS: Authentication success
*
* @see ssh_userauth_kbdint()
* @see ssh_userauth_password()
* @see ssh_options_set()
*/
int ssh_userauth_autopubkey(ssh_session session, const char *passphrase) {
struct ssh_iterator *it;
ssh_private_key privkey;
ssh_public_key pubkey;
ssh_string pubkey_string;
int type = 0;
int rc;
enter_function();
/* Always test none authentication */
rc = ssh_userauth_none(session, NULL);
if (rc == SSH_AUTH_ERROR || rc == SSH_AUTH_SUCCESS) {
leave_function();
return rc;
}
/* Try authentication with ssh-agent first */
#ifndef _WIN32
if (agent_is_running(session)) {
char *privkey_file = NULL;
ssh_log(session, SSH_LOG_RARE,
"Trying to authenticate with SSH agent keys as user: %s",
session->username);
for (pubkey = agent_get_first_ident(session, &privkey_file);
pubkey != NULL;
pubkey = agent_get_next_ident(session, &privkey_file)) {
ssh_log(session, SSH_LOG_RARE, "Trying identity %s", privkey_file);
pubkey_string = publickey_to_string(pubkey);
if (pubkey_string) {
rc = ssh_userauth_offer_pubkey(session, NULL, pubkey->type, pubkey_string);
string_free(pubkey_string);
if (rc == SSH_AUTH_ERROR) {
SAFE_FREE(privkey_file);
publickey_free(pubkey);
leave_function();
return rc;
} else if (rc != SSH_AUTH_SUCCESS) {
ssh_log(session, SSH_LOG_PROTOCOL, "Public key refused by server");
SAFE_FREE(privkey_file);
publickey_free(pubkey);
continue;
}
ssh_log(session, SSH_LOG_RARE, "Public key accepted");
/* pubkey accepted by server ! */
rc = ssh_userauth_agent_pubkey(session, NULL, pubkey);
if (rc == SSH_AUTH_ERROR) {
SAFE_FREE(privkey_file);
publickey_free(pubkey);
leave_function();
return rc;
} else if (rc != SSH_AUTH_SUCCESS) {
ssh_log(session, SSH_LOG_RARE,
"Server accepted public key but refused the signature ;"
" It might be a bug of libssh");
SAFE_FREE(privkey_file);
publickey_free(pubkey);
continue;
}
/* auth success */
ssh_log(session, SSH_LOG_PROTOCOL, "Authentication using %s success",
privkey_file);
SAFE_FREE(privkey_file);
publickey_free(pubkey);
leave_function();
return SSH_AUTH_SUCCESS;
} /* if pubkey */
SAFE_FREE(privkey_file);
publickey_free(pubkey);
} /* for each privkey */
} /* if agent is running */
#endif
for (it = ssh_list_get_iterator(session->identity);
it != NULL;
it = it->next) {
const char *privkey_file = it->data;
int privkey_open = 0;
privkey = NULL;
ssh_log(session, SSH_LOG_PROTOCOL, "Trying to read privatekey %s", privkey_file);
rc = ssh_try_publickey_from_file(session, privkey_file, &pubkey_string, &type);
if (rc == 1) {
char *publickey_file;
size_t len;
privkey = privatekey_from_file(session, privkey_file, type, passphrase);
if (privkey == NULL) {
ssh_log(session, SSH_LOG_RARE,
"Reading private key %s failed (bad passphrase ?)",
privkey_file);
leave_function();
return SSH_AUTH_ERROR;
}
privkey_open = 1;
pubkey = publickey_from_privatekey(privkey);
if (pubkey == NULL) {
privatekey_free(privkey);
ssh_set_error_oom(session);
leave_function();
return SSH_AUTH_ERROR;
}
pubkey_string = publickey_to_string(pubkey);
type = pubkey->type;
publickey_free(pubkey);
if (pubkey_string == NULL) {
ssh_set_error_oom(session);
leave_function();
return SSH_AUTH_ERROR;
}
len = strlen(privkey_file) + 5;
publickey_file = malloc(len);
if (publickey_file == NULL) {
ssh_set_error_oom(session);
leave_function();
return SSH_AUTH_ERROR;
}
snprintf(publickey_file, len, "%s.pub", privkey_file);
rc = ssh_publickey_to_file(session, publickey_file, pubkey_string, type);
if (rc < 0) {
ssh_log(session, SSH_LOG_PACKET,
"Could not write public key to file: %s", publickey_file);
}
SAFE_FREE(publickey_file);
} else if (rc < 0) {
continue;
}
rc = ssh_userauth_offer_pubkey(session, NULL, type, pubkey_string);
if (rc == SSH_AUTH_ERROR){
string_free(pubkey_string);
ssh_log(session, SSH_LOG_RARE, "Publickey authentication error");
leave_function();
return rc;
} else {
if (rc != SSH_AUTH_SUCCESS){
ssh_log(session, SSH_LOG_PROTOCOL, "Publickey refused by server");
string_free(pubkey_string);
continue;
}
}
/* Public key accepted by server! */
if (!privkey_open) {
ssh_log(session, SSH_LOG_PROTOCOL, "Trying to read privatekey %s",
privkey_file);
privkey = privatekey_from_file(session, privkey_file, type, passphrase);
if (privkey == NULL) {
ssh_log(session, SSH_LOG_RARE,
"Reading private key %s failed (bad passphrase ?)",
privkey_file);
string_free(pubkey_string);
continue; /* continue the loop with other pubkey */
}
}
rc = ssh_userauth_pubkey(session, NULL, pubkey_string, privkey);
if (rc == SSH_AUTH_ERROR) {
string_free(pubkey_string);
privatekey_free(privkey);
leave_function();
return rc;
} else {
if (rc != SSH_AUTH_SUCCESS){
ssh_log(session, SSH_LOG_FUNCTIONS,
"The server accepted the public key but refused the signature");
string_free(pubkey_string);
privatekey_free(privkey);
continue;
}
}
/* auth success */
ssh_log(session, SSH_LOG_PROTOCOL,
"Successfully authenticated using %s", privkey_file);
string_free(pubkey_string);
privatekey_free(privkey);
leave_function();
return SSH_AUTH_SUCCESS;
}
/* at this point, pubkey is NULL and so is privkeyfile */
ssh_log(session, SSH_LOG_FUNCTIONS,
"Tried every public key, none matched");
ssh_set_error(session,SSH_NO_ERROR,"No public key matched");
leave_function();
return SSH_AUTH_DENIED;
}
struct ssh_kbdint_struct {
uint32_t nprompts;
char *name;
char *instruction;
char **prompts;
unsigned char *echo; /* bool array */
char **answers;
};
static ssh_kbdint kbdint_new(void) {
ssh_kbdint kbd;
kbd = malloc(sizeof (struct ssh_kbdint_struct));
if (kbd == NULL) {
return NULL;
}
ZERO_STRUCTP(kbd);
return kbd;
}
static void kbdint_free(ssh_kbdint kbd) {
int i, n;
if (kbd == NULL) {
return;
}
n = kbd->nprompts;
SAFE_FREE(kbd->name);
SAFE_FREE(kbd->instruction);
SAFE_FREE(kbd->echo);
if (kbd->prompts) {
for (i = 0; i < n; i++) {
BURN_STRING(kbd->prompts[i]);
SAFE_FREE(kbd->prompts[i]);
}
SAFE_FREE(kbd->prompts);
}
if (kbd->answers) {
for (i = 0; i < n; i++) {
BURN_STRING(kbd->answers[i]);
SAFE_FREE(kbd->answers[i]);
}
SAFE_FREE(kbd->answers);
}
SAFE_FREE(kbd);
}
static void kbdint_clean(ssh_kbdint kbd) {
int i, n;
if (kbd == NULL) {
return;
}
n = kbd->nprompts;
SAFE_FREE(kbd->name);
SAFE_FREE(kbd->instruction);
SAFE_FREE(kbd->echo);
if (kbd->prompts) {
for (i = 0; i < n; i++) {
BURN_STRING(kbd->prompts[i]);
SAFE_FREE(kbd->prompts[i]);
}
SAFE_FREE(kbd->prompts);
}
if (kbd->answers) {
for (i = 0; i < n; i++) {
BURN_STRING(kbd->answers[i]);
SAFE_FREE(kbd->answers[i]);
}
SAFE_FREE(kbd->answers);
}
kbd->nprompts = 0;
}
/* this function sends the first packet as explained in section 3.1
* of the draft */
static int kbdauth_init(ssh_session session, const char *user,
const char *submethods) {
ssh_string usr = NULL;
ssh_string sub = NULL;
ssh_string service = NULL;
ssh_string method = NULL;
int rc = SSH_AUTH_ERROR;
enter_function();
usr = string_from_char(user);
if (usr == NULL) {
goto error;
}
sub = (submethods ? string_from_char(submethods) : string_from_char(""));
if (sub == NULL) {
goto error;
}
service = string_from_char("ssh-connection");
if (service == NULL) {
goto error;
}
method = string_from_char("keyboard-interactive");
if (method == NULL) {
goto error;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_REQUEST) < 0 ||
buffer_add_ssh_string(session->out_buffer, usr) < 0 ||
buffer_add_ssh_string(session->out_buffer, service) < 0 ||
buffer_add_ssh_string(session->out_buffer, method) < 0 ||
buffer_add_u32(session->out_buffer, 0) < 0 ||
buffer_add_ssh_string(session->out_buffer, sub) < 0) {
goto error;
}
string_free(usr);
string_free(service);
string_free(method);
string_free(sub);
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
rc = wait_auth_status(session,1);
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(usr);
string_free(service);
string_free(method);
string_free(sub);
leave_function();
return rc;
}
static int kbdauth_info_get(ssh_session session) {
ssh_string name; /* name of the "asking" window showed to client */
ssh_string instruction;
ssh_string tmp;
uint32_t nprompts;
uint32_t i;
enter_function();
name = buffer_get_ssh_string(session->in_buffer);
instruction = buffer_get_ssh_string(session->in_buffer);
tmp = buffer_get_ssh_string(session->in_buffer);
buffer_get_u32(session->in_buffer, &nprompts);
if (name == NULL || instruction == NULL || tmp == NULL) {
string_free(name);
string_free(instruction);
/* tmp if empty if we got here */
ssh_set_error(session, SSH_FATAL, "Invalid USERAUTH_INFO_REQUEST msg");
leave_function();
return SSH_AUTH_ERROR;
}
string_free(tmp);
if (session->kbdint == NULL) {
session->kbdint = kbdint_new();
if (session->kbdint == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
string_free(name);
string_free(instruction);
leave_function();
return SSH_AUTH_ERROR;
}
} else {
kbdint_clean(session->kbdint);
}
session->kbdint->name = string_to_char(name);
string_free(name);
if (session->kbdint->name == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
kbdint_free(session->kbdint);
leave_function();
return SSH_AUTH_ERROR;
}
session->kbdint->instruction = string_to_char(instruction);
string_free(instruction);
if (session->kbdint->instruction == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
kbdint_free(session->kbdint);
session->kbdint = NULL;
leave_function();
return SSH_AUTH_ERROR;
}
nprompts = ntohl(nprompts);
if (nprompts > KBDINT_MAX_PROMPT) {
ssh_set_error(session, SSH_FATAL,
"Too much prompt asked from server: %u (0x%.4x)",
nprompts, nprompts);
kbdint_free(session->kbdint);
session->kbdint = NULL;
leave_function();
return SSH_AUTH_ERROR;
}
session->kbdint->nprompts = nprompts;
session->kbdint->prompts = malloc(nprompts * sizeof(char *));
if (session->kbdint->prompts == NULL) {
session->kbdint->nprompts = 0;
ssh_set_error(session, SSH_FATAL, "No space left");
kbdint_free(session->kbdint);
session->kbdint = NULL;
leave_function();
return SSH_AUTH_ERROR;
}
memset(session->kbdint->prompts, 0, nprompts * sizeof(char *));
session->kbdint->echo = malloc(nprompts);
if (session->kbdint->echo == NULL) {
session->kbdint->nprompts = 0;
ssh_set_error(session, SSH_FATAL, "No space left");
kbdint_free(session->kbdint);
session->kbdint = NULL;
leave_function();
return SSH_AUTH_ERROR;
}
memset(session->kbdint->echo, 0, nprompts);
for (i = 0; i < nprompts; i++) {
tmp = buffer_get_ssh_string(session->in_buffer);
buffer_get_u8(session->in_buffer, &session->kbdint->echo[i]);
if (tmp == NULL) {
ssh_set_error(session, SSH_FATAL, "Short INFO_REQUEST packet");
kbdint_free(session->kbdint);
session->kbdint = NULL;
leave_function();
return SSH_AUTH_ERROR;
}
session->kbdint->prompts[i] = string_to_char(tmp);
string_free(tmp);
if (session->kbdint->prompts[i] == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
kbdint_free(session->kbdint);
session->kbdint = NULL;
leave_function();
return SSH_AUTH_ERROR;
}
}
leave_function();
return SSH_AUTH_INFO; /* we are not auth. but we parsed the packet */
}
/* sends challenge back to the server */
static int kbdauth_send(ssh_session session) {
ssh_string answer = NULL;
int rc = SSH_AUTH_ERROR;
uint32_t i;
enter_function();
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_INFO_RESPONSE) < 0 ||
buffer_add_u32(session->out_buffer,
htonl(session->kbdint->nprompts)) < 0) {
goto error;
}
for (i = 0; i < session->kbdint->nprompts; i++) {
if (session->kbdint->answers[i]) {
answer = string_from_char(session->kbdint->answers[i]);
} else {
answer = string_from_char("");
}
if (answer == NULL) {
goto error;
}
if (buffer_add_ssh_string(session->out_buffer, answer) < 0) {
goto error;
}
string_burn(answer);
string_free(answer);
}
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
rc = wait_auth_status(session,1);
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_burn(answer);
string_free(answer);
leave_function();
return rc;
}
/**
* @brief Try to authenticate through the "keyboard-interactive" method.
*
* @param session The ssh session to use.
*
* @param user The username to authenticate. You can specify NULL if
* ssh_option_set_username() has been used. You cannot try
* two different logins in a row.
*
* @param submethods Undocumented. Set it to NULL.
*
* @returns SSH_AUTH_ERROR: A serious error happened\n
* SSH_AUTH_DENIED: Authentication failed : use another method\n
* SSH_AUTH_PARTIAL: You've been partially authenticated, you still
* have to use another method\n
* SSH_AUTH_SUCCESS: Authentication success\n
* SSH_AUTH_INFO: The server asked some questions. Use
* ssh_userauth_kbdint_getnprompts() and such.
*
* @see ssh_userauth_kbdint_getnprompts()
* @see ssh_userauth_kbdint_getname()
* @see ssh_userauth_kbdint_getinstruction()
* @see ssh_userauth_kbdint_getprompt()
* @see ssh_userauth_kbdint_setanswer()
*/
int ssh_userauth_kbdint(ssh_session session, const char *user,
const char *submethods) {
int rc = SSH_AUTH_ERROR;
if (session->version == 1) {
/* No keyb-interactive for ssh1 */
return SSH_AUTH_DENIED;
}
enter_function();
if (session->kbdint == NULL) {
/* first time we call. we must ask for a challenge */
if (user == NULL) {
if ((user = session->username) == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_USER, NULL) < 0) {
leave_function();
return SSH_AUTH_ERROR;
} else {
user = session->username;
}
}
}
if (ask_userauth(session)) {
leave_function();
return SSH_AUTH_ERROR;
}
rc = kbdauth_init(session, user, submethods);
if (rc != SSH_AUTH_INFO) {
leave_function();
return rc; /* error or first try success */
}
rc = kbdauth_info_get(session);
if (rc == SSH_AUTH_ERROR) {
kbdint_free(session->kbdint);
session->kbdint = NULL;
}
leave_function();
return rc;
}
/*
* If we are at this point, it ss because session->kbdint exists.
* It means the user has set some information there we need to send
* the server and then we need to ack the status (new questions or ok
* pass in).
*/
rc = kbdauth_send(session);
kbdint_free(session->kbdint);
session->kbdint = NULL;
if(rc != SSH_AUTH_INFO) {
leave_function();
return rc;
}
rc = kbdauth_info_get(session);
if (rc == SSH_AUTH_ERROR) {
kbdint_free(session->kbdint);
session->kbdint = NULL;
}
leave_function();
return rc;
}
/**
* @brief Get the number of prompts (questions) the server has given.
*
* You have called ssh_userauth_kbdint() and got SSH_AUTH_INFO. This
* function returns the questions from the server.
*
* @param session The ssh session to use.
*
* @returns The number of prompts.
*/
int ssh_userauth_kbdint_getnprompts(ssh_session session) {
return session->kbdint->nprompts;
}
/**
* @brief Get the "name" of the message block.
*
* You have called ssh_userauth_kbdint() and got SSH_AUTH_INFO. This
* function returns the questions from the server.
*
* @param session The ssh session to use.
*
* @returns The name of the message block. Do not free it.
*/
const char *ssh_userauth_kbdint_getname(ssh_session session) {
return session->kbdint->name;
}
/**
* @brief Get the "instruction" of the message block.
*
* You have called ssh_userauth_kbdint() and got SSH_AUTH_INFO. This
* function returns the questions from the server.
*
* @param session The ssh session to use.
*
* @returns The instruction of the message block.
*/
const char *ssh_userauth_kbdint_getinstruction(ssh_session session) {
return session->kbdint->instruction;
}
/**
* @brief Get a prompt from a message block.
*
* You have called ssh_userauth_kbdint() and got SSH_AUTH_INFO. This
* function returns the questions from the server.
*
* @param session The ssh session to use.
*
* @param i The inndex number of the i'th prompt.
*
* @param echo When different of NULL, it will obtain a boolean meaning
* that the resulting user input should be echoed or not
* (like passwords).
*
* @returns A pointer to the prompt. Do not free it.
*/
const char *ssh_userauth_kbdint_getprompt(ssh_session session, unsigned int i,
char *echo) {
if (i > session->kbdint->nprompts) {
return NULL;
}
if (echo) {
*echo = session->kbdint->echo[i];
}
return session->kbdint->prompts[i];
}
/** You have called ssh_userauth_kbdint() and got SSH_AUTH_INFO. this
* function returns the questions from the server
* \brief set the answer for a question from a message block.
* \param session ssh session
* \param i index number of the ith prompt
* \param answer answer to give to server
* \return 0 on success, < 0 on error.
*/
int ssh_userauth_kbdint_setanswer(ssh_session session, unsigned int i,
const char *answer) {
if (session == NULL || answer == NULL || i > session->kbdint->nprompts) {
return -1;
}
if (session->kbdint->answers == NULL) {
session->kbdint->answers = malloc(sizeof(char*) * session->kbdint->nprompts);
if (session->kbdint->answers == NULL) {
return -1;
}
memset(session->kbdint->answers, 0, sizeof(char *) * session->kbdint->nprompts);
}
if (session->kbdint->answers[i]) {
BURN_STRING(session->kbdint->answers[i]);
SAFE_FREE(session->kbdint->answers[i]);
}
session->kbdint->answers[i] = strdup(answer);
if (session->kbdint->answers[i] == NULL) {
return -1;
}
return 0;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/auth.c
|
C
|
gpl3
| 40,720
|
/*
* dh.c - Diffie-Helman algorithm code against SSH 2
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/*
* Let us resume the dh protocol.
* Each side computes a private prime number, x at client side, y at server
* side.
* g and n are two numbers common to every ssh software.
* client's public key (e) is calculated by doing:
* e = g^x mod p
* client sents e to the server.
* the server computes his own public key, f
* f = g^y mod p
* it sents it to the client
* the common key K is calculated by the client by doing
* k = f^x mod p
* the server does the same with the client public key e
* k' = e^y mod p
* if everything went correctly, k and k' are equal
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/crypto.h"
#include "libssh/buffer.h"
#include "libssh/session.h"
#include "libssh/keys.h"
#include "libssh/dh.h"
/* todo: remove it */
#include "libssh/string.h"
#ifdef HAVE_LIBCRYPTO
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#endif
static unsigned char p_value[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2,
0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6,
0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D,
0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9,
0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11,
0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
#define P_LEN 128 /* Size in bytes of the p number */
static unsigned long g_int = 2 ; /* G is defined as 2 by the ssh2 standards */
static bignum g;
static bignum p;
static int ssh_crypto_initialized;
int ssh_get_random(void *where, int len, int strong){
#ifdef HAVE_LIBGCRYPT
/* variable not used in gcrypt */
(void) strong;
/* not using GCRY_VERY_STRONG_RANDOM which is a bit overkill */
gcry_randomize(where,len,GCRY_STRONG_RANDOM);
return 1;
#elif defined HAVE_LIBCRYPTO
if (strong) {
return RAND_bytes(where,len);
} else {
return RAND_pseudo_bytes(where,len);
}
#endif
/* never reached */
return 1;
}
/*
* This inits the values g and p which are used for DH key agreement
* FIXME: Make the function thread safe by adding a semaphore or mutex.
*/
int ssh_crypto_init(void) {
if (ssh_crypto_initialized == 0) {
#ifdef HAVE_LIBGCRYPT
gcry_check_version(NULL);
if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P,0)) {
gcry_control(GCRYCTL_INIT_SECMEM, 4096);
gcry_control(GCRYCTL_INITIALIZATION_FINISHED,0);
}
#endif
g = bignum_new();
if (g == NULL) {
return -1;
}
bignum_set_word(g,g_int);
#ifdef HAVE_LIBGCRYPT
bignum_bin2bn(p_value, P_LEN, &p);
if (p == NULL) {
bignum_free(g);
g = NULL;
return -1;
}
#elif defined HAVE_LIBCRYPTO
p = bignum_new();
if (p == NULL) {
bignum_free(g);
g = NULL;
return -1;
}
bignum_bin2bn(p_value, P_LEN, p);
OpenSSL_add_all_algorithms();
#endif
ssh_crypto_initialized = 1;
}
return 0;
}
void ssh_crypto_finalize(void) {
if (ssh_crypto_initialized) {
bignum_free(g);
g = NULL;
bignum_free(p);
p = NULL;
ssh_crypto_initialized=0;
}
}
/* prints the bignum on stderr */
void ssh_print_bignum(const char *which, bignum num) {
#ifdef HAVE_LIBGCRYPT
unsigned char *hex = NULL;
bignum_bn2hex(num, &hex);
#elif defined HAVE_LIBCRYPTO
char *hex = NULL;
hex = bignum_bn2hex(num);
#endif
fprintf(stderr, "%s value: ", which);
fprintf(stderr, "%s\n", (hex == NULL) ? "(null)" : (char *) hex);
SAFE_FREE(hex);
}
/**
* @brief Convert a buffer into a colon separated hex string.
* The caller has to free the memory.
*
* @param what What should be converted to a hex string.
*
* @param len Length of the buffer to convert.
*
* @return The hex string or NULL on error.
*/
char *ssh_get_hexa(const unsigned char *what, size_t len) {
char *hexa = NULL;
size_t i;
hexa = malloc(len * 3 + 1);
if (hexa == NULL) {
return NULL;
}
ZERO_STRUCTP(hexa);
for (i = 0; i < len; i++) {
char hex[4];
snprintf(hex, sizeof(hex), "%02x:", what[i]);
strcat(hexa, hex);
}
hexa[(len * 3) - 1] = '\0';
return hexa;
}
/**
* @brief Print a buffer as colon separated hex string.
*
* @param descr Description printed infront of the hex string.
*
* @param what What should be converted to a hex string.
*
* @param len Length of the buffer to convert.
*/
void ssh_print_hexa(const char *descr, const unsigned char *what, size_t len) {
char *hexa = ssh_get_hexa(what, len);
if (hexa == NULL) {
return;
}
printf("%s: %s\n", descr, hexa);
}
int dh_generate_x(ssh_session session) {
session->next_crypto->x = bignum_new();
if (session->next_crypto->x == NULL) {
return -1;
}
#ifdef HAVE_LIBGCRYPT
bignum_rand(session->next_crypto->x, 128);
#elif defined HAVE_LIBCRYPTO
bignum_rand(session->next_crypto->x, 128, 0, -1);
#endif
/* not harder than this */
#ifdef DEBUG_CRYPTO
ssh_print_bignum("x", session->next_crypto->x);
#endif
return 0;
}
/* used by server */
int dh_generate_y(ssh_session session) {
session->next_crypto->y = bignum_new();
if (session->next_crypto->y == NULL) {
return -1;
}
#ifdef HAVE_LIBGCRYPT
bignum_rand(session->next_crypto->y, 128);
#elif defined HAVE_LIBCRYPTO
bignum_rand(session->next_crypto->y, 128, 0, -1);
#endif
/* not harder than this */
#ifdef DEBUG_CRYPTO
ssh_print_bignum("y", session->next_crypto->y);
#endif
return 0;
}
/* used by server */
int dh_generate_e(ssh_session session) {
#ifdef HAVE_LIBCRYPTO
bignum_CTX ctx = bignum_ctx_new();
if (ctx == NULL) {
return -1;
}
#endif
session->next_crypto->e = bignum_new();
if (session->next_crypto->e == NULL) {
#ifdef HAVE_LIBCRYPTO
bignum_ctx_free(ctx);
#endif
return -1;
}
#ifdef HAVE_LIBGCRYPT
bignum_mod_exp(session->next_crypto->e, g, session->next_crypto->x, p);
#elif defined HAVE_LIBCRYPTO
bignum_mod_exp(session->next_crypto->e, g, session->next_crypto->x, p, ctx);
#endif
#ifdef DEBUG_CRYPTO
ssh_print_bignum("e", session->next_crypto->e);
#endif
#ifdef HAVE_LIBCRYPTO
bignum_ctx_free(ctx);
#endif
return 0;
}
int dh_generate_f(ssh_session session) {
#ifdef HAVE_LIBCRYPTO
bignum_CTX ctx = bignum_ctx_new();
if (ctx == NULL) {
return -1;
}
#endif
session->next_crypto->f = bignum_new();
if (session->next_crypto->f == NULL) {
#ifdef HAVE_LIBCRYPTO
bignum_ctx_free(ctx);
#endif
return -1;
}
#ifdef HAVE_LIBGCRYPT
bignum_mod_exp(session->next_crypto->f, g, session->next_crypto->y, p);
#elif defined HAVE_LIBCRYPTO
bignum_mod_exp(session->next_crypto->f, g, session->next_crypto->y, p, ctx);
#endif
#ifdef DEBUG_CRYPTO
ssh_print_bignum("f", session->next_crypto->f);
#endif
#ifdef HAVE_LIBCRYPTO
bignum_ctx_free(ctx);
#endif
return 0;
}
ssh_string make_bignum_string(bignum num) {
ssh_string ptr = NULL;
int pad = 0;
unsigned int len = bignum_num_bytes(num);
unsigned int bits = bignum_num_bits(num);
/* Remember if the fist bit is set, it is considered as a
* negative number. So 0's must be appended */
if (!(bits % 8) && bignum_is_bit_set(num, bits - 1)) {
pad++;
}
#ifdef DEBUG_CRYPTO
fprintf(stderr, "%d bits, %d bytes, %d padding\n", bits, len, pad);
#endif /* DEBUG_CRYPTO */
/* TODO: fix that crap !! */
ptr = malloc(4 + len + pad);
if (ptr == NULL) {
return NULL;
}
ptr->size = htonl(len + pad);
if (pad) {
ptr->string[0] = 0;
}
#ifdef HAVE_LIBGCRYPT
bignum_bn2bin(num, len, ptr->string + pad);
#elif HAVE_LIBCRYPTO
bignum_bn2bin(num, ptr->string + pad);
#endif
return ptr;
}
bignum make_string_bn(ssh_string string){
bignum bn = NULL;
unsigned int len = string_len(string);
#ifdef DEBUG_CRYPTO
fprintf(stderr, "Importing a %d bits, %d bytes object ...\n",
len * 8, len);
#endif /* DEBUG_CRYPTO */
#ifdef HAVE_LIBGCRYPT
bignum_bin2bn(string->string, len, &bn);
#elif defined HAVE_LIBCRYPTO
bn = bignum_bin2bn(string->string, len, NULL);
#endif
return bn;
}
ssh_string dh_get_e(ssh_session session) {
return make_bignum_string(session->next_crypto->e);
}
/* used by server */
ssh_string dh_get_f(ssh_session session) {
return make_bignum_string(session->next_crypto->f);
}
void dh_import_pubkey(ssh_session session, ssh_string pubkey_string) {
session->next_crypto->server_pubkey = pubkey_string;
}
int dh_import_f(ssh_session session, ssh_string f_string) {
session->next_crypto->f = make_string_bn(f_string);
if (session->next_crypto->f == NULL) {
return -1;
}
#ifdef DEBUG_CRYPTO
ssh_print_bignum("f",session->next_crypto->f);
#endif
return 0;
}
/* used by the server implementation */
int dh_import_e(ssh_session session, ssh_string e_string) {
session->next_crypto->e = make_string_bn(e_string);
if (session->next_crypto->e == NULL) {
return -1;
}
#ifdef DEBUG_CRYPTO
ssh_print_bignum("e",session->next_crypto->e);
#endif
return 0;
}
int dh_build_k(ssh_session session) {
#ifdef HAVE_LIBCRYPTO
bignum_CTX ctx = bignum_ctx_new();
if (ctx == NULL) {
return -1;
}
#endif
session->next_crypto->k = bignum_new();
if (session->next_crypto->k == NULL) {
#ifdef HAVE_LIBCRYPTO
bignum_ctx_free(ctx);
#endif
return -1;
}
/* the server and clients don't use the same numbers */
#ifdef HAVE_LIBGCRYPT
if(session->client) {
bignum_mod_exp(session->next_crypto->k, session->next_crypto->f,
session->next_crypto->x, p);
} else {
bignum_mod_exp(session->next_crypto->k, session->next_crypto->e,
session->next_crypto->y, p);
}
#elif defined HAVE_LIBCRYPTO
if (session->client) {
bignum_mod_exp(session->next_crypto->k, session->next_crypto->f,
session->next_crypto->x, p, ctx);
} else {
bignum_mod_exp(session->next_crypto->k, session->next_crypto->e,
session->next_crypto->y, p, ctx);
}
#endif
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Session server cookie", session->server_kex.cookie, 16);
ssh_print_hexa("Session client cookie", session->client_kex.cookie, 16);
ssh_print_bignum("Shared secret key", session->next_crypto->k);
#endif
#ifdef HAVE_LIBCRYPTO
bignum_ctx_free(ctx);
#endif
return 0;
}
/*
static void sha_add(ssh_string str,SHACTX ctx){
sha1_update(ctx,str,string_len(str)+4);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("partial hashed sessionid",str,string_len(str)+4);
#endif
}
*/
int make_sessionid(ssh_session session) {
SHACTX ctx;
ssh_string num = NULL;
ssh_string str = NULL;
ssh_buffer server_hash = NULL;
ssh_buffer client_hash = NULL;
ssh_buffer buf = NULL;
uint32_t len;
int rc = SSH_ERROR;
enter_function();
ctx = sha1_init();
if (ctx == NULL) {
return rc;
}
buf = buffer_new();
if (buf == NULL) {
return rc;
}
str = string_from_char(session->clientbanner);
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(buf, str) < 0) {
goto error;
}
string_free(str);
str = string_from_char(session->serverbanner);
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(buf, str) < 0) {
goto error;
}
if (session->client) {
server_hash = session->in_hashbuf;
client_hash = session->out_hashbuf;
} else {
server_hash = session->out_hashbuf;
client_hash = session->in_hashbuf;
}
if (buffer_add_u32(server_hash, 0) < 0) {
goto error;
}
if (buffer_add_u8(server_hash, 0) < 0) {
goto error;
}
if (buffer_add_u32(client_hash, 0) < 0) {
goto error;
}
if (buffer_add_u8(client_hash, 0) < 0) {
goto error;
}
len = ntohl(buffer_get_len(client_hash));
if (buffer_add_u32(buf,len) < 0) {
goto error;
}
if (buffer_add_data(buf, buffer_get(client_hash),
buffer_get_len(client_hash)) < 0) {
goto error;
}
len = ntohl(buffer_get_len(server_hash));
if (buffer_add_u32(buf, len) < 0) {
goto error;
}
if (buffer_add_data(buf, buffer_get(server_hash),
buffer_get_len(server_hash)) < 0) {
goto error;
}
len = string_len(session->next_crypto->server_pubkey) + 4;
if (buffer_add_data(buf, session->next_crypto->server_pubkey, len) < 0) {
goto error;
}
num = make_bignum_string(session->next_crypto->e);
if (num == NULL) {
goto error;
}
len = string_len(num) + 4;
if (buffer_add_data(buf, num, len) < 0) {
goto error;
}
string_free(num);
num = make_bignum_string(session->next_crypto->f);
if (num == NULL) {
goto error;
}
len = string_len(num) + 4;
if (buffer_add_data(buf, num, len) < 0) {
goto error;
}
string_free(num);
num = make_bignum_string(session->next_crypto->k);
if (num == NULL) {
goto error;
}
len = string_len(num) + 4;
if (buffer_add_data(buf, num, len) < 0) {
goto error;
}
#ifdef DEBUG_CRYPTO
ssh_print_hexa("hash buffer", buffer_get(buf), buffer_get_len(buf));
#endif
sha1_update(ctx, buffer_get(buf), buffer_get_len(buf));
sha1_final(session->next_crypto->session_id, ctx);
#ifdef DEBUG_CRYPTO
printf("Session hash: ");
ssh_print_hexa("session id", session->next_crypto->session_id, SHA_DIGEST_LEN);
#endif
rc = SSH_OK;
error:
buffer_free(buf);
buffer_free(client_hash);
buffer_free(server_hash);
session->in_hashbuf = NULL;
session->out_hashbuf = NULL;
string_free(str);
string_free(num);
leave_function();
return rc;
}
int hashbufout_add_cookie(ssh_session session) {
session->out_hashbuf = buffer_new();
if (session->out_hashbuf == NULL) {
return -1;
}
if (buffer_add_u8(session->out_hashbuf, 20) < 0) {
buffer_reinit(session->out_hashbuf);
return -1;
}
if (session->server) {
if (buffer_add_data(session->out_hashbuf,
session->server_kex.cookie, 16) < 0) {
buffer_reinit(session->out_hashbuf);
return -1;
}
} else {
if (buffer_add_data(session->out_hashbuf,
session->client_kex.cookie, 16) < 0) {
buffer_reinit(session->out_hashbuf);
return -1;
}
}
return 0;
}
int hashbufin_add_cookie(ssh_session session, unsigned char *cookie) {
session->in_hashbuf = buffer_new();
if (session->in_hashbuf == NULL) {
return -1;
}
if (buffer_add_u8(session->in_hashbuf, 20) < 0) {
buffer_reinit(session->in_hashbuf);
return -1;
}
if (buffer_add_data(session->in_hashbuf,cookie, 16) < 0) {
buffer_reinit(session->in_hashbuf);
return -1;
}
return 0;
}
static int generate_one_key(ssh_string k,
unsigned char session_id[SHA_DIGEST_LEN],
unsigned char output[SHA_DIGEST_LEN],
char letter) {
SHACTX ctx = NULL;
ctx = sha1_init();
if (ctx == NULL) {
return -1;
}
sha1_update(ctx, k, string_len(k) + 4);
sha1_update(ctx, session_id, SHA_DIGEST_LEN);
sha1_update(ctx, &letter, 1);
sha1_update(ctx, session_id, SHA_DIGEST_LEN);
sha1_final(output, ctx);
return 0;
}
int generate_session_keys(ssh_session session) {
ssh_string k_string = NULL;
SHACTX ctx = NULL;
int rc = -1;
enter_function();
k_string = make_bignum_string(session->next_crypto->k);
if (k_string == NULL) {
goto error;
}
/* IV */
if (session->client) {
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->encryptIV, 'A') < 0) {
goto error;
}
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->decryptIV, 'B') < 0) {
goto error;
}
} else {
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->decryptIV, 'A') < 0) {
goto error;
}
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->encryptIV, 'B') < 0) {
goto error;
}
}
if (session->client) {
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->encryptkey, 'C') < 0) {
goto error;
}
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->decryptkey, 'D') < 0) {
goto error;
}
} else {
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->decryptkey, 'C') < 0) {
goto error;
}
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->encryptkey, 'D') < 0) {
goto error;
}
}
/* some ciphers need more than 20 bytes of input key */
/* XXX verify it's ok for server implementation */
if (session->next_crypto->out_cipher->keysize > SHA_DIGEST_LEN * 8) {
ctx = sha1_init();
if (ctx == NULL) {
goto error;
}
sha1_update(ctx, k_string, string_len(k_string) + 4);
sha1_update(ctx, session->next_crypto->session_id, SHA_DIGEST_LEN);
sha1_update(ctx, session->next_crypto->encryptkey, SHA_DIGEST_LEN);
sha1_final(session->next_crypto->encryptkey + SHA_DIGEST_LEN, ctx);
}
if (session->next_crypto->in_cipher->keysize > SHA_DIGEST_LEN * 8) {
ctx = sha1_init();
sha1_update(ctx, k_string, string_len(k_string) + 4);
sha1_update(ctx, session->next_crypto->session_id, SHA_DIGEST_LEN);
sha1_update(ctx, session->next_crypto->decryptkey, SHA_DIGEST_LEN);
sha1_final(session->next_crypto->decryptkey + SHA_DIGEST_LEN, ctx);
}
if(session->client) {
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->encryptMAC, 'E') < 0) {
goto error;
}
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->decryptMAC, 'F') < 0) {
goto error;
}
} else {
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->decryptMAC, 'E') < 0) {
goto error;
}
if (generate_one_key(k_string, session->next_crypto->session_id,
session->next_crypto->encryptMAC, 'F') < 0) {
goto error;
}
}
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Encrypt IV", session->next_crypto->encryptIV, SHA_DIGEST_LEN);
ssh_print_hexa("Decrypt IV", session->next_crypto->decryptIV, SHA_DIGEST_LEN);
ssh_print_hexa("Encryption key", session->next_crypto->encryptkey,
session->next_crypto->out_cipher->keysize);
ssh_print_hexa("Decryption key", session->next_crypto->decryptkey,
session->next_crypto->in_cipher->keysize);
ssh_print_hexa("Encryption MAC", session->next_crypto->encryptMAC, SHA_DIGEST_LEN);
ssh_print_hexa("Decryption MAC", session->next_crypto->decryptMAC, 20);
#endif
rc = 0;
error:
string_free(k_string);
leave_function();
return rc;
}
/** \addtogroup ssh_session
* @{ */
/**
* @brief Allocates a buffer with the MD5 hash of the server public key.
*
* @param session The SSH session to use.
*
* @param hash The buffer to allocate.
*
* @return The bytes allocated or < 0 on error.
*
* @warning It is very important that you verify at some moment that the hash
* matches a known server. If you don't do it, cryptography wont help
* you at making things secure
*
* @see ssh_is_server_known()
* @see ssh_get_hexa()
* @see ssh_print_hexa()
*/
int ssh_get_pubkey_hash(ssh_session session, unsigned char **hash) {
ssh_string pubkey;
MD5CTX ctx;
unsigned char *h;
if (session == NULL || hash == NULL) {
return -1;
}
*hash = NULL;
h = malloc(sizeof(unsigned char *) * MD5_DIGEST_LEN);
if (h == NULL) {
return -1;
}
ctx = md5_init();
if (ctx == NULL) {
SAFE_FREE(h);
return -1;
}
pubkey = session->current_crypto->server_pubkey;
md5_update(ctx, pubkey->string, string_len(pubkey));
md5_final(h, ctx);
*hash = h;
return MD5_DIGEST_LEN;
}
/**
* @brief Deallocate the hash obtained by ssh_get_pubkey_hash.
* This is required under Microsoft platform as this library might use a
* different C library than your software, hence a different heap.
*
* @param hash The buffer to deallocate.
*
* @see ssh_get_pubkey_hash()
*/
void ssh_clean_pubkey_hash(unsigned char **hash) {
SAFE_FREE(*hash);
*hash = NULL;
}
ssh_string ssh_get_pubkey(ssh_session session){
return string_copy(session->current_crypto->server_pubkey);
}
static int match(const char *group, const char *object){
const char *a;
const char *z;
a = z = group;
do {
a = strchr(z, ',');
if (a == NULL) {
if (strcmp(z, object) == 0) {
return 1;
}
return 0;
} else {
if (strncmp(z, object, a - z) == 0) {
return 1;
}
}
z = a + 1;
} while(1);
/* not reached */
return 0;
}
int sig_verify(ssh_session session, ssh_public_key pubkey,
SIGNATURE *signature, unsigned char *digest, int size) {
#ifdef HAVE_LIBGCRYPT
gcry_error_t valid = 0;
gcry_sexp_t gcryhash;
#elif defined HAVE_LIBCRYPTO
int valid = 0;
#endif
unsigned char hash[SHA_DIGEST_LEN + 1] = {0};
sha1(digest, size, hash + 1);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Hash to be verified with dsa", hash + 1, SHA_DIGEST_LEN);
#endif
switch(pubkey->type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
valid = gcry_sexp_build(&gcryhash, NULL, "%b", SHA_DIGEST_LEN + 1, hash);
if (valid != 0) {
ssh_set_error(session, SSH_FATAL,
"RSA error: %s", gcry_strerror(valid));
return -1;
}
valid = gcry_pk_verify(signature->dsa_sign, gcryhash, pubkey->dsa_pub);
gcry_sexp_release(gcryhash);
if (valid == 0) {
return 0;
}
if (gcry_err_code(valid) != GPG_ERR_BAD_SIGNATURE) {
ssh_set_error(session, SSH_FATAL,
"DSA error: %s", gcry_strerror(valid));
return -1;
}
#elif defined HAVE_LIBCRYPTO
valid = DSA_do_verify(hash + 1, SHA_DIGEST_LEN, signature->dsa_sign,
pubkey->dsa_pub);
if (valid == 1) {
return 0;
}
if (valid == -1) {
ssh_set_error(session, SSH_FATAL,
"DSA error: %s", ERR_error_string(ERR_get_error(), NULL));
return -1;
}
#endif
ssh_set_error(session, SSH_FATAL, "Invalid DSA signature");
return -1;
case TYPE_RSA:
case TYPE_RSA1:
#ifdef HAVE_LIBGCRYPT
valid = gcry_sexp_build(&gcryhash, NULL,
"(data(flags pkcs1)(hash sha1 %b))", SHA_DIGEST_LEN, hash + 1);
if (valid != 0) {
ssh_set_error(session, SSH_FATAL,
"RSA error: %s", gcry_strerror(valid));
return -1;
}
valid = gcry_pk_verify(signature->rsa_sign,gcryhash,pubkey->rsa_pub);
gcry_sexp_release(gcryhash);
if (valid == 0) {
return 0;
}
if (gcry_err_code(valid) != GPG_ERR_BAD_SIGNATURE) {
ssh_set_error(session, SSH_FATAL,
"RSA error: %s", gcry_strerror(valid));
return -1;
}
#elif defined HAVE_LIBCRYPTO
valid = RSA_verify(NID_sha1, hash + 1, SHA_DIGEST_LEN,
signature->rsa_sign->string, string_len(signature->rsa_sign),
pubkey->rsa_pub);
if (valid == 1) {
return 0;
}
if (valid == -1) {
ssh_set_error(session, SSH_FATAL,
"RSA error: %s", ERR_error_string(ERR_get_error(), NULL));
return -1;
}
#endif
ssh_set_error(session, SSH_FATAL, "Invalid RSA signature");
return -1;
default:
ssh_set_error(session, SSH_FATAL, "Unknown public key type");
return -1;
}
return -1;
}
int signature_verify(ssh_session session, ssh_string signature) {
ssh_public_key pubkey = NULL;
SIGNATURE *sign = NULL;
int err;
enter_function();
pubkey = publickey_from_string(session,session->next_crypto->server_pubkey);
if(pubkey == NULL) {
leave_function();
return -1;
}
if (session->wanted_methods[SSH_HOSTKEYS]) {
if(!match(session->wanted_methods[SSH_HOSTKEYS],pubkey->type_c)) {
ssh_set_error(session, SSH_FATAL,
"Public key from server (%s) doesn't match user preference (%s)",
pubkey->type_c, session->wanted_methods[SSH_HOSTKEYS]);
publickey_free(pubkey);
leave_function();
return -1;
}
}
sign = signature_from_string(session, signature, pubkey, pubkey->type);
if (sign == NULL) {
ssh_set_error(session, SSH_FATAL, "Invalid signature blob");
publickey_free(pubkey);
leave_function();
return -1;
}
ssh_log(session, SSH_LOG_FUNCTIONS,
"Going to verify a %s type signature", pubkey->type_c);
err = sig_verify(session,pubkey,sign,
session->next_crypto->session_id,SHA_DIGEST_LEN);
signature_free(sign);
session->next_crypto->server_pubkey_type = pubkey->type_c;
publickey_free(pubkey);
leave_function();
return err;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/dh.c
|
C
|
gpl3
| 26,274
|
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
* All rights reserved
* Simple pattern matching, with '*' and '?' as wildcards.
*
* As far as I am concerned, the code I have written for this software
* can be used freely for any purpose. Any derived versions of this
* software must be clearly marked as such, and if the derived work is
* incompatible with the protocol description in the RFC file, it must be
* called by a name other than "ssh" or "Secure Shell".
*/
/*
* Copyright (c) 2000 Markus Friedl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ctype.h>
#include <string.h>
#include <sys/types.h>
#include "libssh/priv.h"
/*
* Returns true if the given string matches the pattern (which may contain ?
* and * as wildcards), and zero if it does not match.
*/
static int match_pattern(const char *s, const char *pattern) {
for (;;) {
/* If at end of pattern, accept if also at end of string. */
if (!*pattern) {
return !*s;
}
if (*pattern == '*') {
/* Skip the asterisk. */
pattern++;
/* If at end of pattern, accept immediately. */
if (!*pattern)
return 1;
/* If next character in pattern is known, optimize. */
if (*pattern != '?' && *pattern != '*') {
/*
* Look instances of the next character in
* pattern, and try to match starting from
* those.
*/
for (; *s; s++)
if (*s == *pattern && match_pattern(s + 1, pattern + 1)) {
return 1;
}
/* Failed. */
return 0;
}
/*
* Move ahead one character at a time and try to
* match at each position.
*/
for (; *s; s++) {
if (match_pattern(s, pattern)) {
return 1;
}
}
/* Failed. */
return 0;
}
/*
* There must be at least one more character in the string.
* If we are at the end, fail.
*/
if (!*s) {
return 0;
}
/* Check if the next character of the string is acceptable. */
if (*pattern != '?' && *pattern != *s) {
return 0;
}
/* Move to the next character, both in string and in pattern. */
s++;
pattern++;
}
/* NOTREACHED */
}
/*
* Tries to match the string against the comma-separated sequence of subpatterns
* (each possibly preceded by ! to indicate negation).
* Returns -1 if negation matches, 1 if there is a positive match, 0 if there is
* no match at all.
*/
static int match_pattern_list(const char *string, const char *pattern,
unsigned int len, int dolower) {
char sub[1024];
int negated;
int got_positive;
unsigned int i, subi;
got_positive = 0;
for (i = 0; i < len;) {
/* Check if the subpattern is negated. */
if (pattern[i] == '!') {
negated = 1;
i++;
} else {
negated = 0;
}
/*
* Extract the subpattern up to a comma or end. Convert the
* subpattern to lowercase.
*/
for (subi = 0;
i < len && subi < sizeof(sub) - 1 && pattern[i] != ',';
subi++, i++) {
sub[subi] = dolower && isupper(pattern[i]) ?
(char)tolower(pattern[i]) : pattern[i];
}
/* If subpattern too long, return failure (no match). */
if (subi >= sizeof(sub) - 1) {
return 0;
}
/* If the subpattern was terminated by a comma, skip the comma. */
if (i < len && pattern[i] == ',') {
i++;
}
/* Null-terminate the subpattern. */
sub[subi] = '\0';
/* Try to match the subpattern against the string. */
if (match_pattern(string, sub)) {
if (negated) {
return -1; /* Negative */
} else {
got_positive = 1; /* Positive */
}
}
}
/*
* Return success if got a positive match. If there was a negative
* match, we have already returned -1 and never get here.
*/
return got_positive;
}
/*
* Tries to match the host name (which must be in all lowercase) against the
* comma-separated sequence of subpatterns (each possibly preceded by ! to
* indicate negation).
* Returns -1 if negation matches, 1 if there is a positive match, 0 if there
* is no match at all.
*/
int match_hostname(const char *host, const char *pattern, unsigned int len) {
return match_pattern_list(host, pattern, len, 1);
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/match.c
|
C
|
gpl3
| 5,655
|
/*
* kex.c - key exchange
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/ssh1.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/session.h"
#include "libssh/wrapper.h"
#include "libssh/keys.h"
#include "libssh/dh.h"
#include "libssh/string.h"
#ifdef HAVE_LIBGCRYPT
#define BLOWFISH "blowfish-cbc,"
#define AES "aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,"
#define DES "3des-cbc"
#elif defined HAVE_LIBCRYPTO
#ifdef HAVE_OPENSSL_BLOWFISH_H
#define BLOWFISH "blowfish-cbc,"
#else
#define BLOWFISH ""
#endif
#ifdef HAVE_OPENSSL_AES_H
#ifdef BROKEN_AES_CTR
#define AES "aes256-cbc,aes192-cbc,aes128-cbc,"
#else
#define AES "aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,"
#endif /* BROKEN_AES_CTR */
#else
#define AES ""
#endif
#define DES "3des-cbc"
#endif
#if defined(HAVE_LIBZ) && defined(WITH_LIBZ)
#define ZLIB "none,zlib"
#else
#define ZLIB "none"
#endif
const char *default_methods[] = {
"diffie-hellman-group1-sha1",
"ssh-rsa,ssh-dss",
AES BLOWFISH DES,
AES BLOWFISH DES,
"hmac-sha1",
"hmac-sha1",
"none",
"none",
"",
"",
NULL
};
const char *supported_methods[] = {
"diffie-hellman-group1-sha1",
"ssh-rsa,ssh-dss",
AES BLOWFISH DES,
AES BLOWFISH DES,
"hmac-sha1",
"hmac-sha1",
ZLIB,
ZLIB,
"",
"",
NULL
};
/* descriptions of the key exchange packet */
const char *ssh_kex_nums[] = {
"kex algos",
"server host key algo",
"encryption client->server",
"encryption server->client",
"mac algo client->server",
"mac algo server->client",
"compression algo client->server",
"compression algo server->client",
"languages client->server",
"languages server->client",
NULL
};
/* tokenize will return a token of strings delimited by ",". the first element has to be freed */
static char **tokenize(const char *chain){
char **tokens;
int n=1;
int i=0;
char *tmp;
char *ptr;
tmp = strdup(chain);
if (tmp == NULL) {
return NULL;
}
ptr = tmp;
while(*ptr){
if(*ptr==','){
n++;
*ptr=0;
}
ptr++;
}
/* now n contains the number of tokens, the first possibly empty if the list was empty too e.g. "" */
tokens=malloc(sizeof(char *) * (n+1) ); /* +1 for the null */
if (tokens == NULL) {
SAFE_FREE(tmp);
return NULL;
}
ptr=tmp;
for(i=0;i<n;i++){
tokens[i]=ptr;
while(*ptr)
ptr++; // find a zero
ptr++; // then go one step further
}
tokens[i]=NULL;
return tokens;
}
/* same as tokenize(), but with spaces instead of ',' */
/* TODO FIXME rewrite me! */
char **space_tokenize(const char *chain){
char **tokens;
int n=1;
int i=0;
char *tmp;
char *ptr;
tmp = strdup(chain);
if (tmp == NULL) {
return NULL;
}
ptr = tmp;
while(*ptr==' ')
++ptr; /* skip initial spaces */
while(*ptr){
if(*ptr==' '){
n++; /* count one token per word */
*ptr=0;
while(*(ptr+1)==' '){ /* don't count if the tokens have more than 2 spaces */
*(ptr++)=0;
}
}
ptr++;
}
/* now n contains the number of tokens, the first possibly empty if the list was empty too e.g. "" */
tokens = malloc(sizeof(char *) * (n + 1)); /* +1 for the null */
if (tokens == NULL) {
SAFE_FREE(tmp);
return NULL;
}
ptr=tmp; /* we don't pass the initial spaces because the "tmp" pointer is needed by the caller */
/* function to free the tokens. */
for(i=0;i<n;i++){
tokens[i]=ptr;
if(i!=n-1){
while(*ptr)
ptr++; // find a zero
while(!*(ptr+1))
++ptr; /* if the zero is followed by other zeros, go through them */
ptr++; // then go one step further
}
}
tokens[i]=NULL;
return tokens;
}
/* find_matching gets 2 parameters : a list of available objects (available_d), separated by colons,*/
/* and a list of preferred objects (preferred_d) */
/* it will return a strduped pointer on the first prefered object found in the available objects list */
char *ssh_find_matching(const char *available_d, const char *preferred_d){
char ** tok_available, **tok_preferred;
int i_avail, i_pref;
char *ret;
if ((available_d == NULL) || (preferred_d == NULL)) {
return NULL; /* don't deal with null args */
}
tok_available = tokenize(available_d);
if (tok_available == NULL) {
return NULL;
}
tok_preferred = tokenize(preferred_d);
if (tok_preferred == NULL) {
SAFE_FREE(tok_available[0]);
SAFE_FREE(tok_available);
}
for(i_pref=0; tok_preferred[i_pref] ; ++i_pref){
for(i_avail=0; tok_available[i_avail]; ++i_avail){
if(!strcmp(tok_available[i_avail],tok_preferred[i_pref])){
/* match */
ret=strdup(tok_available[i_avail]);
/* free the tokens */
free(tok_available[0]);
free(tok_preferred[0]);
free(tok_available);
free(tok_preferred);
return ret;
}
}
}
free(tok_available[0]);
free(tok_preferred[0]);
free(tok_available);
free(tok_preferred);
return NULL;
}
int ssh_get_kex(ssh_session session, int server_kex) {
ssh_string str = NULL;
char *strings[10];
int i;
enter_function();
if (packet_wait(session, SSH2_MSG_KEXINIT, 1) != SSH_OK) {
leave_function();
return -1;
}
if (buffer_get_data(session->in_buffer,session->server_kex.cookie,16) != 16) {
ssh_set_error(session, SSH_FATAL, "get_kex(): no cookie in packet");
leave_function();
return -1;
}
if (hashbufin_add_cookie(session, session->server_kex.cookie) < 0) {
ssh_set_error(session, SSH_FATAL, "get_kex(): adding cookie failed");
leave_function();
return -1;
}
memset(strings, 0, sizeof(char *) * 10);
for (i = 0; i < 10; i++) {
str = buffer_get_ssh_string(session->in_buffer);
if (str == NULL) {
break;
}
if (buffer_add_ssh_string(session->in_hashbuf, str) < 0) {
goto error;
}
strings[i] = string_to_char(str);
if (strings[i] == NULL) {
goto error;
}
string_free(str);
str = NULL;
}
/* copy the server kex info into an array of strings */
if (server_kex) {
session->client_kex.methods = malloc(10 * sizeof(char **));
if (session->client_kex.methods == NULL) {
leave_function();
return -1;
}
for (i = 0; i < 10; i++) {
session->client_kex.methods[i] = strings[i];
}
} else { /* client */
session->server_kex.methods = malloc(10 * sizeof(char **));
if (session->server_kex.methods == NULL) {
leave_function();
return -1;
}
for (i = 0; i < 10; i++) {
session->server_kex.methods[i] = strings[i];
}
}
leave_function();
return 0;
error:
string_free(str);
for (i = 0; i < 10; i++) {
SAFE_FREE(strings[i]);
}
leave_function();
return -1;
}
void ssh_list_kex(ssh_session session, KEX *kex) {
int i = 0;
#ifdef DEBUG_CRYPTO
ssh_print_hexa("session cookie", kex->cookie, 16);
#endif
for(i = 0; i < 10; i++) {
ssh_log(session, SSH_LOG_FUNCTIONS, "%s: %s",
ssh_kex_nums[i], kex->methods[i]);
}
}
/* set_kex basicaly look at the option structure of the session and set the output kex message */
/* it must be aware of the server kex message */
/* it can fail if option is null, not any user specified kex method matches the server one, if not any default kex matches */
int set_kex(ssh_session session){
KEX *server = &session->server_kex;
KEX *client=&session->client_kex;
int i;
const char *wanted;
enter_function();
ssh_get_random(client->cookie,16,0);
client->methods=malloc(10 * sizeof(char **));
if (client->methods == NULL) {
ssh_set_error(session, SSH_FATAL, "No space left");
leave_function();
return -1;
}
memset(client->methods,0,10*sizeof(char **));
for (i=0;i<10;i++){
if(!(wanted=session->wanted_methods[i]))
wanted=default_methods[i];
client->methods[i]=ssh_find_matching(server->methods[i],wanted);
if(!client->methods[i] && i < SSH_LANG_C_S){
ssh_set_error(session,SSH_FATAL,"kex error : did not find one of algos %s in list %s for %s",
wanted,server->methods[i],ssh_kex_nums[i]);
leave_function();
return -1;
} else {
if ((i >= SSH_LANG_C_S) && (client->methods[i] == NULL)) {
/* we can safely do that for languages */
client->methods[i] = strdup("");
if (client->methods[i] == NULL) {
return -1;
}
}
}
}
leave_function();
return 0;
}
/* this function only sends the predefined set of kex methods */
int ssh_send_kex(ssh_session session, int server_kex) {
KEX *kex = (server_kex ? &session->server_kex : &session->client_kex);
ssh_string str = NULL;
int i;
enter_function();
if (buffer_add_u8(session->out_buffer, SSH2_MSG_KEXINIT) < 0) {
goto error;
}
if (buffer_add_data(session->out_buffer, kex->cookie, 16) < 0) {
goto error;
}
if (hashbufout_add_cookie(session) < 0) {
goto error;
}
ssh_list_kex(session, kex);
for (i = 0; i < 10; i++) {
str = string_from_char(kex->methods[i]);
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(session->out_hashbuf, str) < 0) {
goto error;
}
if (buffer_add_ssh_string(session->out_buffer, str) < 0) {
goto error;
}
string_free(str);
}
if (buffer_add_u8(session->out_buffer, 0) < 0) {
goto error;
}
if (buffer_add_u32(session->out_buffer, 0) < 0) {
goto error;
}
if (packet_send(session) != SSH_OK) {
leave_function();
return -1;
}
leave_function();
return 0;
error:
buffer_reinit(session->out_buffer);
buffer_reinit(session->out_hashbuf);
string_free(str);
leave_function();
return -1;
}
/* returns 1 if at least one of the name algos is in the default algorithms table */
int verify_existing_algo(int algo, const char *name){
char *ptr;
if(algo>9 || algo <0)
return -1;
ptr=ssh_find_matching(supported_methods[algo],name);
if(ptr){
free(ptr);
return 1;
}
return 0;
}
/* makes a STRING contating 3 strings : ssh-rsa1,e and n */
/* this is a public key in openssh's format */
static ssh_string make_rsa1_string(ssh_string e, ssh_string n){
ssh_buffer buffer = NULL;
ssh_string rsa = NULL;
ssh_string ret = NULL;
buffer = buffer_new();
rsa = string_from_char("ssh-rsa1");
if (buffer_add_ssh_string(buffer, rsa) < 0) {
goto error;
}
if (buffer_add_ssh_string(buffer, e) < 0) {
goto error;
}
if (buffer_add_ssh_string(buffer, n) < 0) {
goto error;
}
ret = string_new(buffer_get_len(buffer));
if (ret == NULL) {
goto error;
}
string_fill(ret, buffer_get(buffer), buffer_get_len(buffer));
error:
buffer_free(buffer);
string_free(rsa);
return ret;
}
static int build_session_id1(ssh_session session, ssh_string servern,
ssh_string hostn) {
MD5CTX md5 = NULL;
md5 = md5_init();
if (md5 == NULL) {
return -1;
}
#ifdef DEBUG_CRYPTO
ssh_print_hexa("host modulus",string_data(hostn),string_len(hostn));
ssh_print_hexa("server modulus",string_data(servern),string_len(servern));
#endif
md5_update(md5,string_data(hostn),string_len(hostn));
md5_update(md5,string_data(servern),string_len(servern));
md5_update(md5,session->server_kex.cookie,8);
md5_final(session->next_crypto->session_id,md5);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("session_id",session->next_crypto->session_id,MD5_DIGEST_LEN);
#endif
return 0;
}
/* returns 1 if the modulus of k1 is < than the one of k2 */
static int modulus_smaller(ssh_public_key k1, ssh_public_key k2){
bignum n1;
bignum n2;
int res;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t sexp;
sexp=gcry_sexp_find_token(k1->rsa_pub,"n",0);
n1=gcry_sexp_nth_mpi(sexp,1,GCRYMPI_FMT_USG);
gcry_sexp_release(sexp);
sexp=gcry_sexp_find_token(k2->rsa_pub,"n",0);
n2=gcry_sexp_nth_mpi(sexp,1,GCRYMPI_FMT_USG);
gcry_sexp_release(sexp);
#elif defined HAVE_LIBCRYPTO
n1=k1->rsa_pub->n;
n2=k2->rsa_pub->n;
#endif
if(bignum_cmp(n1,n2)<0)
res=1;
else
res=0;
#ifdef HAVE_LIBGCRYPT
bignum_free(n1);
bignum_free(n2);
#endif
return res;
}
#define ABS(A) ( (A)<0 ? -(A):(A) )
static ssh_string encrypt_session_key(ssh_session session, ssh_public_key srvkey,
ssh_public_key hostkey, int slen, int hlen) {
unsigned char buffer[32] = {0};
int i;
ssh_string data1 = NULL;
ssh_string data2 = NULL;
/* first, generate a session key */
ssh_get_random(session->next_crypto->encryptkey, 32, 1);
memcpy(buffer, session->next_crypto->encryptkey, 32);
memcpy(session->next_crypto->decryptkey, session->next_crypto->encryptkey, 32);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("session key",buffer,32);
#endif
/* xor session key with session_id */
for (i = 0; i < 16; i++) {
buffer[i] ^= session->next_crypto->session_id[i];
}
data1 = string_new(32);
if (data1 == NULL) {
return NULL;
}
string_fill(data1, buffer, 32);
if (ABS(hlen - slen) < 128){
ssh_log(session, SSH_LOG_FUNCTIONS,
"Difference between server modulus and host modulus is only %d. "
"It's illegal and may not work",
ABS(hlen - slen));
}
if (modulus_smaller(srvkey, hostkey)) {
data2 = ssh_encrypt_rsa1(session, data1, srvkey);
string_free(data1);
data1 = NULL;
if (data2 == NULL) {
return NULL;
}
data1 = ssh_encrypt_rsa1(session, data2, hostkey);
string_free(data2);
if (data1 == NULL) {
return NULL;
}
} else {
data2 = ssh_encrypt_rsa1(session, data1, hostkey);
string_free(data1);
data1 = NULL;
if (data2 == NULL) {
return NULL;
}
data1 = ssh_encrypt_rsa1(session, data2, srvkey);
string_free(data2);
if (data1 == NULL) {
return NULL;
}
}
return data1;
}
/* SSH-1 functions */
/* 2 SSH_SMSG_PUBLIC_KEY
*
* 8 bytes anti_spoofing_cookie
* 32-bit int server_key_bits
* mp-int server_key_public_exponent
* mp-int server_key_public_modulus
* 32-bit int host_key_bits
* mp-int host_key_public_exponent
* mp-int host_key_public_modulus
* 32-bit int protocol_flags
* 32-bit int supported_ciphers_mask
* 32-bit int supported_authentications_mask
*/
int ssh_get_kex1(ssh_session session) {
ssh_string server_exp = NULL;
ssh_string server_mod = NULL;
ssh_string host_exp = NULL;
ssh_string host_mod = NULL;
ssh_string serverkey = NULL;
ssh_string hostkey = NULL;
ssh_string enc_session = NULL;
ssh_public_key srv = NULL;
ssh_public_key host = NULL;
uint32_t server_bits;
uint32_t host_bits;
uint32_t protocol_flags;
uint32_t supported_ciphers_mask;
uint32_t supported_authentications_mask;
uint16_t bits;
int rc = -1;
int ko;
enter_function();
ssh_log(session, SSH_LOG_PROTOCOL, "Waiting for a SSH_SMSG_PUBLIC_KEY");
if (packet_wait(session, SSH_SMSG_PUBLIC_KEY, 1) != SSH_OK) {
leave_function();
return -1;
}
ssh_log(session, SSH_LOG_PROTOCOL, "Got a SSH_SMSG_PUBLIC_KEY");
if (buffer_get_data(session->in_buffer, session->server_kex.cookie, 8) != 8) {
ssh_set_error(session, SSH_FATAL, "Can't get cookie in buffer");
leave_function();
return -1;
}
buffer_get_u32(session->in_buffer, &server_bits);
server_exp = buffer_get_mpint(session->in_buffer);
if (server_exp == NULL) {
goto error;
}
server_mod = buffer_get_mpint(session->in_buffer);
if (server_mod == NULL) {
goto error;
}
buffer_get_u32(session->in_buffer, &host_bits);
host_exp = buffer_get_mpint(session->in_buffer);
if (host_exp == NULL) {
goto error;
}
host_mod = buffer_get_mpint(session->in_buffer);
if (host_mod == NULL) {
goto error;
}
buffer_get_u32(session->in_buffer, &protocol_flags);
buffer_get_u32(session->in_buffer, &supported_ciphers_mask);
ko = buffer_get_u32(session->in_buffer, &supported_authentications_mask);
if ((ko != sizeof(uint32_t)) || !host_mod || !host_exp
|| !server_mod || !server_exp) {
ssh_log(session, SSH_LOG_RARE, "Invalid SSH_SMSG_PUBLIC_KEY packet");
ssh_set_error(session, SSH_FATAL, "Invalid SSH_SMSG_PUBLIC_KEY packet");
goto error;
}
server_bits = ntohl(server_bits);
host_bits = ntohl(host_bits);
protocol_flags = ntohl(protocol_flags);
supported_ciphers_mask = ntohl(supported_ciphers_mask);
supported_authentications_mask = ntohl(supported_authentications_mask);
ssh_log(session, SSH_LOG_PROTOCOL,
"Server bits: %d; Host bits: %d; Protocol flags: %.8lx; "
"Cipher mask: %.8lx; Auth mask: %.8lx",
server_bits,
host_bits,
(unsigned long int) protocol_flags,
(unsigned long int) supported_ciphers_mask,
(unsigned long int) supported_authentications_mask);
serverkey = make_rsa1_string(server_exp, server_mod);
if (serverkey == NULL) {
goto error;
}
hostkey = make_rsa1_string(host_exp,host_mod);
if (serverkey == NULL) {
goto error;
}
if (build_session_id1(session, server_mod, host_mod) < 0) {
goto error;
}
srv = publickey_from_string(session, serverkey);
if (srv == NULL) {
goto error;
}
host = publickey_from_string(session, hostkey);
if (host == NULL) {
goto error;
}
session->next_crypto->server_pubkey = string_copy(hostkey);
if (session->next_crypto->server_pubkey == NULL) {
goto error;
}
session->next_crypto->server_pubkey_type = "ssh-rsa1";
/* now, we must choose an encryption algo */
/* hardcode 3des */
if (!(supported_ciphers_mask & (1 << SSH_CIPHER_3DES))) {
ssh_set_error(session, SSH_FATAL, "Remote server doesn't accept 3DES");
goto error;
}
ssh_log(session, SSH_LOG_PROTOCOL, "Sending SSH_CMSG_SESSION_KEY");
if (buffer_add_u8(session->out_buffer, SSH_CMSG_SESSION_KEY) < 0) {
goto error;
}
if (buffer_add_u8(session->out_buffer, SSH_CIPHER_3DES) < 0) {
goto error;
}
if (buffer_add_data(session->out_buffer, session->server_kex.cookie, 8) < 0) {
goto error;
}
enc_session = encrypt_session_key(session, srv, host, server_bits, host_bits);
if (enc_session == NULL) {
goto error;
}
bits = string_len(enc_session) * 8 - 7;
ssh_log(session, SSH_LOG_PROTOCOL, "%d bits, %zu bytes encrypted session",
bits, string_len(enc_session));
bits = htons(bits);
/* the encrypted mpint */
if (buffer_add_data(session->out_buffer, &bits, sizeof(uint16_t)) < 0) {
goto error;
}
if (buffer_add_data(session->out_buffer, string_data(enc_session),
string_len(enc_session)) < 0) {
goto error;
}
/* the protocol flags */
if (buffer_add_u32(session->out_buffer, 0) < 0) {
goto error;
}
if (packet_send(session) != SSH_OK) {
goto error;
}
/* we can set encryption */
if (crypt_set_algorithms(session)) {
goto error;
}
session->current_crypto = session->next_crypto;
session->next_crypto = NULL;
ssh_log(session, SSH_LOG_PROTOCOL, "Waiting for a SSH_SMSG_SUCCESS");
if (packet_wait(session,SSH_SMSG_SUCCESS,1) != SSH_OK) {
char buffer[1024] = {0};
snprintf(buffer, sizeof(buffer),
"Key exchange failed: %s", ssh_get_error(session));
ssh_set_error(session, SSH_FATAL, "%s",buffer);
goto error;
}
ssh_log(session, SSH_LOG_PROTOCOL, "received SSH_SMSG_SUCCESS\n");
rc = 0;
error:
string_free(host_mod);
string_free(host_exp);
string_free(server_mod);
string_free(server_exp);
string_free(serverkey);
string_free(hostkey);
publickey_free(srv);
publickey_free(host);
leave_function();
return rc;
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/kex.c
|
C
|
gpl3
| 21,051
|
/*
* options.c - handle pre-connection options
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <pwd.h>
#else
#include <winsock2.h>
#endif
#include <sys/types.h>
#include "libssh/priv.h"
#include "libssh/session.h"
#include "libssh/misc.h"
#ifdef WITH_SERVER
#include "libssh/server.h"
#endif
/**
* @addtogroup ssh_session
* @{
*/
/**
* @brief Duplicate the options of a session structure.
*
* If you make several sessions with the same options this is useful. You
* cannot use twice the same option structure in ssh_session_connect.
*
* @param src The session to use to copy the options.
*
* @param dest The session to copy the options to.
*
* @returns 0 on sucess, -1 on error with errno set.
*
* @see ssh_session_connect()
*/
int ssh_options_copy(ssh_session src, ssh_session *dest) {
ssh_session new;
int i;
if (src == NULL || dest == NULL || *dest == NULL) {
return -1;
}
new = *dest;
if (src->username) {
new->username = strdup(src->username);
if (new->username == NULL) {
return -1;
}
}
if (src->host) {
new->host = strdup(src->host);
if (new->host == NULL) {
return -1;
}
}
if (src->identity) {
struct ssh_iterator *it;
new->identity = ssh_list_new();
if (new->identity == NULL) {
return -1;
}
it = ssh_list_get_iterator(src->identity);
while (it) {
char *id;
int rc;
id = strdup((char *) it->data);
if (id == NULL) {
return -1;
}
rc = ssh_list_append(new->identity, id);
if (rc < 0) {
return -1;
}
it = it->next;
}
}
if (src->sshdir) {
new->sshdir = strdup(src->sshdir);
if (new->sshdir == NULL) {
return -1;
}
}
if (src->knownhosts) {
new->knownhosts = strdup(src->knownhosts);
if (new->knownhosts == NULL) {
return -1;
}
}
for (i = 0; i < 10; ++i) {
if (src->wanted_methods[i]) {
new->wanted_methods[i] = strdup(src->wanted_methods[i]);
if (new->wanted_methods[i] == NULL) {
return -1;
}
}
}
new->fd = src->fd;
new->port = src->port;
new->callbacks = src->callbacks;
new->timeout = src->timeout;
new->timeout_usec = src->timeout_usec;
new->ssh2 = src->ssh2;
new->ssh1 = src->ssh1;
new->log_verbosity = src->log_verbosity;
return 0;
}
int ssh_options_set_algo(ssh_session session, int algo,
const char *list) {
if (!verify_existing_algo(algo, list)) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Setting method: no algorithm for method \"%s\" (%s)\n",
ssh_kex_nums[algo], list);
return -1;
}
SAFE_FREE(session->wanted_methods[algo]);
session->wanted_methods[algo] = strdup(list);
if (session->wanted_methods[algo] == NULL) {
ssh_set_error_oom(session);
return -1;
}
return 0;
}
/**
* @brief This function can set all possible ssh options.
*
* @param session An allocated ssh option structure.
*
* @param type The option type to set. This could be one of the
* following:
*
* - SSH_OPTIONS_HOST:
* The hostname or ip address to connect to (string).
*
* - SSH_OPTIONS_PORT:
* The port to connect to (integer).
*
* - SSH_OPTIONS_PORT_STR:
* The port to connect to (string).
*
* - SSH_OPTIONS_FD:
* The file descriptor to use (socket_t).\n
* \n
* If you wish to open the socket yourself for a reason
* or another, set the file descriptor. Don't forget to
* set the hostname as the hostname is used as a key in
* the known_host mechanism.
*
* - SSH_OPTIONS_USER:
* The username for authentication (string).\n
* \n
* If the value is NULL, the username is set to the
* default username.
*
* - SSH_OPTIONS_SSH_DIR:
* Set the ssh directory (format string).\n
* \n
* If the value is NULL, the directory is set to the
* default ssh directory.\n
* \n
* The ssh directory is used for files like known_hosts
* and identity (private and public key). It may include
* "%s" which will be replaced by the user home
* directory.
*
* - SSH_OPTIONS_KNOWNHOSTS:
* Set the known hosts file name (format string).\n
* \n
* If the value is NULL, the directory is set to the
* default known hosts file, normally
* ~/.ssh/known_hosts.\n
* \n
* The known hosts file is used to certify remote hosts
* are genuine. It may include "%s" which will be
* replaced by the user home directory.
*
* - SSH_OPTIONS_IDENTITY:
* Set the identity file name (format string).\n
* \n
* By default identity, id_dsa and id_rsa are checked.\n
* \n
* The identity file used authenticate with public key.
* It may include "%s" which will be replaced by the
* user home directory.
*
* - SSH_OPTIONS_TIMEOUT:
* Set a timeout for the connection in seconds (integer).
*
* - SSH_OPTIONS_TIMEOUT_USEC:
* Set a timeout for the connection in micro seconds
* (integer).
*
* - SSH_OPTIONS_SSH1:
* Allow or deny the connection to SSH1 servers
* (integer).
*
* - SSH_OPTIONS_SSH2:
* Allow or deny the connection to SSH2 servers
* (integer).
*
* - SSH_OPTIONS_LOG_VERBOSITY:
* Set the session logging verbosity (integer).\n
* \n
* The verbosity of the messages. Every log smaller or
* equal to verbosity will be shown.
* - SSH_LOG_NOLOG: No logging
* - SSH_LOG_RARE: Rare conditions or warnings
* - SSH_LOG_ENTRY: API-accessible entrypoints
* - SSH_LOG_PACKET: Packet id and size
* - SSH_LOG_FUNCTIONS: Function entering and leaving
*
* - SSH_OPTIONS_LOG_VERBOSITY_STR:
* Set the session logging verbosity (string).\n
* \n
* The verbosity of the messages. Every log smaller or
* equal to verbosity will be shown.
* - SSH_LOG_NOLOG: No logging
* - SSH_LOG_RARE: Rare conditions or warnings
* - SSH_LOG_ENTRY: API-accessible entrypoints
* - SSH_LOG_PACKET: Packet id and size
* - SSH_LOG_FUNCTIONS: Function entering and leaving
* \n
* See the corresponding numbers in libssh.h.
*
* - SSH_OPTTIONS_AUTH_CALLBACK:
* Set a callback to use your own authentication function
* (function pointer).
*
* - SSH_OPTTIONS_AUTH_USERDATA:
* Set the user data passed to the authentication
* function (generic pointer).
*
* - SSH_OPTTIONS_LOG_CALLBACK:
* Set a callback to use your own logging function
* (function pointer).
*
* - SSH_OPTTIONS_LOG_USERDATA:
* Set the user data passed to the logging function
* (generic pointer).
*
* - SSH_OPTTIONS_STATUS_CALLBACK:
* Set a callback to show connection status in realtime
* (function pointer).\n
* \n
* @code
* fn(void *arg, float status)
* @endcode
* \n
* During ssh_connect(), libssh will call the callback
* with status from 0.0 to 1.0.
*
* - SSH_OPTTIONS_STATUS_ARG:
* Set the status argument which should be passed to the
* status callback (generic pointer).
*
* - SSH_OPTIONS_CIPHERS_C_S:
* Set the symmetric cipher client to server (string,
* comma-separated list).
*
* - SSH_OPTIONS_CIPHERS_S_C:
* Set the symmetric cipher server to client (string,
* comma-separated list).
*
* - SSH_OPTIONS_COMPRESSION_C_S:
* Set the compression to use for client to server
* communication (string, "none" or "zlib").
*
* - SSH_OPTIONS_COMPRESSION_S_C:
* Set the compression to use for server to client
* communication (string, "none" or "zlib").
*
* - SSH_OPTIONS_PROXYCOMMAND:
* Set the command to be executed in order to connect to
* server.
*
* @param value The value to set. This is a generic pointer and the
* datatype which is used should be set according to the
* type set.
*
* @return 0 on success, < 0 on error.
*/
int ssh_options_set(ssh_session session, enum ssh_options_e type,
const void *value) {
char *p, *q;
long int i;
int rc;
if (session == NULL) {
return -1;
}
switch (type) {
case SSH_OPTIONS_HOST:
q = strdup(value);
if (q == NULL) {
ssh_set_error_oom(session);
return -1;
}
p = strchr(q, '@');
SAFE_FREE(session->host);
if (p) {
*p = '\0';
session->host = strdup(p + 1);
if (session->host == NULL) {
SAFE_FREE(q);
ssh_set_error_oom(session);
return -1;
}
SAFE_FREE(session->username);
session->username = strdup(q);
SAFE_FREE(q);
if (session->username == NULL) {
ssh_set_error_oom(session);
return -1;
}
} else {
session->host = q;
}
break;
case SSH_OPTIONS_PORT:
if (value == NULL) {
session->port = 22 & 0xffff;
} else {
int *x = (int *) value;
session->port = *x & 0xffff;
}
break;
case SSH_OPTIONS_PORT_STR:
if (value == NULL) {
session->port = 22 & 0xffff;
} else {
q = strdup(value);
if (q == NULL) {
ssh_set_error_oom(session);
return -1;
}
i = strtol(q, &p, 10);
if (q == p) {
SAFE_FREE(q);
}
SAFE_FREE(q);
session->port = i & 0xffff;
}
break;
case SSH_OPTIONS_FD:
if (value == NULL) {
session->fd = -1;
} else {
socket_t *x = (socket_t *) value;
session->fd = *x & 0xffff;
}
break;
case SSH_OPTIONS_USER:
SAFE_FREE(session->username);
if (value == NULL) { /* set default username */
q = ssh_get_local_username(session);
if (q == NULL) {
return -1;
}
session->username = q;
} else { /* username provided */
session->username = strdup(value);
if (session->username == NULL) {
ssh_set_error_oom(session);
return -1;
}
}
break;
case SSH_OPTIONS_SSH_DIR:
if (value == NULL) {
SAFE_FREE(session->sshdir);
session->sshdir = ssh_path_expand_tilde("~/.ssh/");
if (session->sshdir == NULL) {
return -1;
}
} else {
SAFE_FREE(session->sshdir);
session->sshdir = ssh_path_expand_tilde(value);
if (session->sshdir == NULL) {
return -1;
}
}
break;
case SSH_OPTIONS_IDENTITY:
case SSH_OPTIONS_ADD_IDENTITY:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
}
q = strdup(value);
if (q == NULL) {
return -1;
}
rc = ssh_list_prepend(session->identity, q);
if (rc < 0) {
return -1;
}
break;
case SSH_OPTIONS_KNOWNHOSTS:
if (value == NULL) {
SAFE_FREE(session->knownhosts);
if (session->sshdir == NULL) {
return -1;
}
session->knownhosts = ssh_path_expand_escape(session, "%d/known_hosts");
if (session->knownhosts == NULL) {
return -1;
}
} else {
SAFE_FREE(session->knownhosts);
session->knownhosts = strdup(value);
if (session->knownhosts == NULL) {
return -1;
}
}
break;
case SSH_OPTIONS_TIMEOUT:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
long *x = (long *) value;
session->timeout = *x & 0xffffffff;
}
break;
case SSH_OPTIONS_TIMEOUT_USEC:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
long *x = (long *) value;
session->timeout_usec = *x & 0xffffffff;
}
break;
case SSH_OPTIONS_SSH1:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
int *x = (int *) value;
session->ssh1 = *x;
}
break;
case SSH_OPTIONS_SSH2:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
int *x = (int *) value;
session->ssh2 = *x & 0xffff;
}
break;
case SSH_OPTIONS_LOG_VERBOSITY:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
int *x = (int *) value;
session->log_verbosity = *x & 0xffff;
}
break;
case SSH_OPTIONS_LOG_VERBOSITY_STR:
if (value == NULL) {
session->log_verbosity = 0 & 0xffff;
} else {
q = strdup(value);
if (q == NULL) {
ssh_set_error_oom(session);
return -1;
}
i = strtol(q, &p, 10);
if (q == p) {
SAFE_FREE(q);
}
SAFE_FREE(q);
session->log_verbosity = i & 0xffff;
}
break;
case SSH_OPTIONS_CIPHERS_C_S:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
if (ssh_options_set_algo(session, SSH_CRYPT_C_S, value) < 0)
return -1;
}
break;
case SSH_OPTIONS_CIPHERS_S_C:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
if (ssh_options_set_algo(session, SSH_CRYPT_S_C, value) < 0)
return -1;
}
break;
case SSH_OPTIONS_COMPRESSION_C_S:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
if (ssh_options_set_algo(session, SSH_COMP_C_S, value) < 0)
return -1;
}
break;
case SSH_OPTIONS_COMPRESSION_S_C:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
if (ssh_options_set_algo(session, SSH_COMP_S_C, value) < 0)
return -1;
}
break;
case SSH_OPTIONS_PROXYCOMMAND:
if (value == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
} else {
SAFE_FREE(session->ProxyCommand);
q = strdup(value);
if (q == NULL) {
return -1;
}
session->ProxyCommand = q;
}
break;
default:
ssh_set_error(session, SSH_REQUEST_DENIED, "Unknown ssh option %d", type);
return -1;
break;
}
return 0;
}
/** @} */
#ifdef WITH_SERVER
/**
* @addtogroup ssh_server
* @{
*/
static int ssh_bind_options_set_algo(ssh_bind sshbind, int algo,
const char *list) {
if (!verify_existing_algo(algo, list)) {
ssh_set_error(sshbind, SSH_REQUEST_DENIED,
"Setting method: no algorithm for method \"%s\" (%s)\n",
ssh_kex_nums[algo], list);
return -1;
}
SAFE_FREE(sshbind->wanted_methods[algo]);
sshbind->wanted_methods[algo] = strdup(list);
if (sshbind->wanted_methods[algo] == NULL) {
ssh_set_error_oom(sshbind);
return -1;
}
return 0;
}
/**
* @brief This function can set all possible ssh bind options.
*
* @param session An allocated ssh option structure.
*
* @param type The option type to set. This could be one of the
* following:
*
* SSH_BIND_OPTIONS_LOG_VERBOSITY:
* Set the session logging verbosity (integer).
*
* The verbosity of the messages. Every log smaller or
* equal to verbosity will be shown.
* SSH_LOG_NOLOG: No logging
* SSH_LOG_RARE: Rare conditions or warnings
* SSH_LOG_ENTRY: API-accessible entrypoints
* SSH_LOG_PACKET: Packet id and size
* SSH_LOG_FUNCTIONS: Function entering and leaving
*
* SSH_BIND_OPTIONS_LOG_VERBOSITY_STR:
* Set the session logging verbosity (integer).
*
* The verbosity of the messages. Every log smaller or
* equal to verbosity will be shown.
* SSH_LOG_NOLOG: No logging
* SSH_LOG_RARE: Rare conditions or warnings
* SSH_LOG_ENTRY: API-accessible entrypoints
* SSH_LOG_PACKET: Packet id and size
* SSH_LOG_FUNCTIONS: Function entering and leaving
*
* SSH_BIND_OPTIONS_BINDADDR:
* Set the bind address.
*
* SSH_BIND_OPTIONS_BINDPORT:
* Set the bind port, default is 22.
*
* SSH_BIND_OPTIONS_HOSTKEY:
* Set the server public key type: ssh-rsa or ssh-dss
* (string).
*
* SSH_BIND_OPTIONS_DSAKEY:
* Set the path to the dsa ssh host key (string).
*
* SSH_BIND_OPTIONS_RSAKEY:
* Set the path to the ssh host rsa key (string).
*
* SSH_BIND_OPTIONS_BANNER:
* Set the server banner sent to clients (string).
*
* @param value The value to set. This is a generic pointer and the
* datatype which is used should be set according to the
* type set.
*
* @return 0 on success, < 0 on error.
*/
int ssh_bind_options_set(ssh_bind sshbind, enum ssh_bind_options_e type,
const void *value) {
char *p, *q;
int i;
if (sshbind == NULL) {
return -1;
}
switch (type) {
case SSH_BIND_OPTIONS_HOSTKEY:
if (value == NULL) {
ssh_set_error_invalid(sshbind, __FUNCTION__);
return -1;
} else {
if (ssh_bind_options_set_algo(sshbind, SSH_HOSTKEYS, value) < 0)
return -1;
}
break;
case SSH_BIND_OPTIONS_BINDADDR:
if (value == NULL) {
ssh_set_error_invalid(sshbind, __FUNCTION__);
return -1;
} else {
SAFE_FREE(sshbind->bindaddr);
sshbind->bindaddr = strdup(value);
if (sshbind->bindaddr == NULL) {
ssh_set_error_oom(sshbind);
return -1;
}
}
break;
case SSH_BIND_OPTIONS_BINDPORT:
if (value == NULL) {
ssh_set_error_invalid(sshbind, __FUNCTION__);
return -1;
} else {
int *x = (int *) value;
sshbind->bindport = *x & 0xffff;
}
break;
case SSH_BIND_OPTIONS_BINDPORT_STR:
if (value == NULL) {
sshbind->bindport = 22 & 0xffff;
} else {
q = strdup(value);
if (q == NULL) {
ssh_set_error_oom(sshbind);
return -1;
}
i = strtol(q, &p, 10);
if (q == p) {
SAFE_FREE(q);
}
SAFE_FREE(q);
sshbind->bindport = i & 0xffff;
}
break;
case SSH_BIND_OPTIONS_LOG_VERBOSITY:
if (value == NULL) {
ssh_set_error_invalid(sshbind, __FUNCTION__);
return -1;
} else {
int *x = (int *) value;
sshbind->log_verbosity = *x & 0xffff;
}
break;
case SSH_BIND_OPTIONS_LOG_VERBOSITY_STR:
if (value == NULL) {
sshbind->log_verbosity = 0;
} else {
q = strdup(value);
if (q == NULL) {
ssh_set_error_oom(sshbind);
return -1;
}
i = strtol(q, &p, 10);
if (q == p) {
SAFE_FREE(q);
}
SAFE_FREE(q);
sshbind->log_verbosity = i & 0xffff;
}
break;
case SSH_BIND_OPTIONS_DSAKEY:
if (value == NULL) {
ssh_set_error_invalid(sshbind, __FUNCTION__);
return -1;
} else {
SAFE_FREE(sshbind->dsakey);
sshbind->dsakey = strdup(value);
if (sshbind->dsakey == NULL) {
ssh_set_error_oom(sshbind);
return -1;
}
}
break;
case SSH_BIND_OPTIONS_RSAKEY:
if (value == NULL) {
ssh_set_error_invalid(sshbind, __FUNCTION__);
return -1;
} else {
SAFE_FREE(sshbind->rsakey);
sshbind->rsakey = strdup(value);
if (sshbind->rsakey == NULL) {
ssh_set_error_oom(sshbind);
return -1;
}
}
break;
case SSH_BIND_OPTIONS_BANNER:
if (value == NULL) {
ssh_set_error_invalid(sshbind, __FUNCTION__);
return -1;
} else {
SAFE_FREE(sshbind->banner);
sshbind->banner = strdup(value);
if (sshbind->banner == NULL) {
ssh_set_error_oom(sshbind);
return -1;
}
}
break;
default:
ssh_set_error(sshbind, SSH_REQUEST_DENIED, "Unknown ssh option %d", type);
return -1;
break;
}
return 0;
}
#endif
/**
* @brief Parse command line arguments.
*
* This is a helper for your application to generate the appropriate
* options from the command line arguments.\n
* The argv array and argc value are changed so that the parsed
* arguments wont appear anymore in them.\n
* The single arguments (without switches) are not parsed. thus,
* myssh -l user localhost\n
* The command wont set the hostname value of options to localhost.
*
* @param session The session to configure.
*
* @param argcptr The pointer to the argument count.
*
* @param argv The arguments list pointer.
*
* @returns 0 on success, < 0 on error.
*
* @see ssh_session_new()
*/
int ssh_options_getopt(ssh_session session, int *argcptr, char **argv) {
char *user = NULL;
char *cipher = NULL;
char *localaddr = NULL;
char *identity = NULL;
char *port = NULL;
char *bindport = NULL;
char **save = NULL;
int i = 0;
int argc = *argcptr;
int debuglevel = 0;
int usersa = 0;
int usedss = 0;
int compress = 0;
int cont = 1;
int current = 0;
#ifdef WITH_SSH1
int ssh1 = 1;
#else
int ssh1 = 0;
#endif
int ssh2 = 1;
#ifdef _MSC_VER
/* Not supported with a Microsoft compiler */
return -1;
#else
int saveoptind = optind; /* need to save 'em */
int saveopterr = opterr;
save = malloc(argc * sizeof(char *));
if (save == NULL) {
ssh_set_error_oom(session);
return -1;
}
opterr = 0; /* shut up getopt */
while(cont && ((i = getopt(argc, argv, "c:i:Cl:p:vb:t:rd12")) != -1)) {
switch(i) {
case 'l':
user = optarg;
break;
case 'p':
port = optarg;
break;
case 't':
bindport = optarg;
break;
case 'v':
debuglevel++;
break;
case 'r':
usersa++;
break;
case 'd':
usedss++;
break;
case 'c':
cipher = optarg;
break;
case 'i':
identity = optarg;
break;
case 'b':
localaddr = optarg;
break;
case 'C':
compress++;
break;
case '2':
ssh2 = 1;
ssh1 = 0;
break;
case '1':
ssh2 = 0;
ssh1 = 1;
break;
default:
{
char opt[3]="- ";
opt[1] = optopt;
save[current] = strdup(opt);
if (save[current] == NULL) {
SAFE_FREE(save);
ssh_set_error_oom(session);
return -1;
}
current++;
if (optarg) {
save[current++] = argv[optind + 1];
}
}
} /* switch */
} /* while */
opterr = saveopterr;
while (optind < argc) {
save[current++] = argv[optind++];
}
if (usersa && usedss) {
ssh_set_error(session, SSH_FATAL, "Either RSA or DSS must be chosen");
cont = 0;
}
ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &debuglevel);
optind = saveoptind;
if(!cont) {
SAFE_FREE(save);
return -1;
}
/* first recopy the save vector into the original's */
for (i = 0; i < current; i++) {
/* don't erase argv[0] */
argv[ i + 1] = save[i];
}
argv[current + 1] = NULL;
*argcptr = current + 1;
SAFE_FREE(save);
/* set a new option struct */
if (compress) {
if (ssh_options_set(session, SSH_OPTIONS_COMPRESSION_C_S, "zlib") < 0) {
cont = 0;
}
if (ssh_options_set(session, SSH_OPTIONS_COMPRESSION_S_C, "zlib") < 0) {
cont = 0;
}
}
if (cont && cipher) {
if (ssh_options_set(session, SSH_OPTIONS_CIPHERS_C_S, cipher) < 0) {
cont = 0;
}
if (cont && ssh_options_set(session, SSH_OPTIONS_CIPHERS_S_C, cipher) < 0) {
cont = 0;
}
}
if (cont && user) {
if (ssh_options_set(session, SSH_OPTIONS_USER, user) < 0) {
cont = 0;
}
}
if (cont && identity) {
if (ssh_options_set(session, SSH_OPTIONS_IDENTITY, identity) < 0) {
cont = 0;
}
}
ssh_options_set(session, SSH_OPTIONS_PORT_STR, port);
ssh_options_set(session, SSH_OPTIONS_SSH1, &ssh1);
ssh_options_set(session, SSH_OPTIONS_SSH2, &ssh2);
if (!cont) {
return SSH_ERROR;
}
return SSH_OK;
#endif
}
/**
* @brief Parse the ssh config file.
*
* This should be the last call of all options, it may overwrite options which
* are already set. It requires that the host name is already set with
* ssh_options_set_host().
*
* @param session SSH session handle
*
* @param filename The options file to use, if NULL the default
* ~/.ssh/config will be used.
*
* @return 0 on success, < 0 on error.
*
* @see ssh_options_set_host()
*/
int ssh_options_parse_config(ssh_session session, const char *filename) {
char *expanded_filename;
int r;
if (session == NULL) {
return -1;
}
if (session->host == NULL) {
ssh_set_error_invalid(session, __FUNCTION__);
return -1;
}
if (session->sshdir == NULL) {
r = ssh_options_set(session, SSH_OPTIONS_SSH_DIR, NULL);
if (r < 0) {
ssh_set_error_oom(session);
return -1;
}
}
/* set default filename */
if (filename == NULL) {
expanded_filename = ssh_path_expand_escape(session, "%d/config");
} else {
expanded_filename = ssh_path_expand_escape(session, filename);
}
if (expanded_filename == NULL) {
return -1;
}
r = ssh_config_parse_file(session, expanded_filename);
if (r < 0) {
goto out;
}
if (filename == NULL) {
r = ssh_config_parse_file(session, "/etc/ssh/ssh_config");
}
out:
free(expanded_filename);
return r;
}
int ssh_options_apply(ssh_session session) {
struct ssh_iterator *it;
char *tmp;
int rc;
if (session->sshdir == NULL) {
rc = ssh_options_set(session, SSH_OPTIONS_SSH_DIR, NULL);
if (rc < 0) {
return -1;
}
}
if (session->knownhosts == NULL) {
tmp = ssh_path_expand_escape(session, "%d/known_hosts");
} else {
tmp = ssh_path_expand_escape(session, session->knownhosts);
}
if (tmp == NULL) {
return -1;
}
free(session->knownhosts);
session->knownhosts = tmp;
if (session->ProxyCommand != NULL) {
tmp = ssh_path_expand_escape(session, session->ProxyCommand);
if (tmp == NULL) {
return -1;
}
free(session->ProxyCommand);
session->ProxyCommand = tmp;
}
for (it = ssh_list_get_iterator(session->identity);
it != NULL;
it = it->next) {
char *id = (char *) it->data;
tmp = ssh_path_expand_escape(session, id);
if (tmp == NULL) {
return -1;
}
free(id);
it->data = tmp;
}
return 0;
}
/* @} */
/* vim: set ts=4 sw=4 et cindent: */
|
zzlydm-fbbs
|
libssh/options.c
|
C
|
gpl3
| 31,085
|
/*
* socket.c - socket functions for the library
*
* This file is part of the SSH Library
*
* Copyright (c) 2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
extern const char **environ;
#endif
#include "libssh/priv.h"
#include "libssh/socket.h"
#include "libssh/buffer.h"
#include "libssh/poll.h"
#include "libssh/session.h"
/** \defgroup ssh_socket SSH Sockets
* \addtogroup ssh_socket
* @{
*/
struct socket {
socket_t fd;
int last_errno;
int data_to_read; /* reading now on socket will
not block */
int data_to_write;
int data_except;
ssh_buffer out_buffer;
ssh_buffer in_buffer;
ssh_session session;
};
/*
* \internal
* \brief inits the socket system (windows specific)
*/
int ssh_socket_init(void) {
#ifdef _WIN32
struct WSAData wsaData;
/* Initiates use of the Winsock DLL by a process. */
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
return -1;
}
ssh_poll_init();
#endif
return 0;
}
/*
* \internal
* \brief creates a new Socket object
*/
struct socket *ssh_socket_new(ssh_session session) {
struct socket *s;
s = malloc(sizeof(struct socket));
if (s == NULL) {
return NULL;
}
s->fd = -1;
s->last_errno = -1;
s->session = session;
s->in_buffer = buffer_new();
if (s->in_buffer == NULL) {
SAFE_FREE(s);
return NULL;
}
s->out_buffer=buffer_new();
if (s->out_buffer == NULL) {
buffer_free(s->in_buffer);
SAFE_FREE(s);
return NULL;
}
s->data_to_read = 0;
s->data_to_write = 0;
s->data_except = 0;
return s;
}
/* \internal
* \brief Deletes a socket object
*/
void ssh_socket_free(struct socket *s){
if (s == NULL) {
return;
}
ssh_socket_close(s);
buffer_free(s->in_buffer);
buffer_free(s->out_buffer);
SAFE_FREE(s);
}
#ifndef _WIN32
int ssh_socket_unix(struct socket *s, const char *path) {
struct sockaddr_un sunaddr;
sunaddr.sun_family = AF_UNIX;
snprintf(sunaddr.sun_path, sizeof(sunaddr.sun_path), "%s", path);
s->fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (s->fd < 0) {
return -1;
}
if (fcntl(s->fd, F_SETFD, 1) == -1) {
close(s->fd);
s->fd = -1;
return -1;
}
if (connect(s->fd, (struct sockaddr *) &sunaddr,
sizeof(sunaddr)) < 0) {
close(s->fd);
s->fd = -1;
return -1;
}
return 0;
}
#endif
/* \internal
* \brief closes a socket
*/
void ssh_socket_close(struct socket *s){
if (ssh_socket_is_open(s)) {
#ifdef _WIN32
closesocket(s->fd);
s->last_errno = WSAGetLastError();
#else
close(s->fd);
s->last_errno = errno;
#endif
s->fd=-1;
}
}
/* \internal
* \brief sets the file descriptor of the socket
*/
void ssh_socket_set_fd(struct socket *s, socket_t fd) {
s->fd = fd;
}
/* \internal
* \brief returns the file descriptor of the socket
*/
socket_t ssh_socket_get_fd(struct socket *s) {
return s->fd;
}
/* \internal
* \brief returns nonzero if the socket is open
*/
int ssh_socket_is_open(struct socket *s) {
return s->fd != -1;
}
/* \internal
* \brief read len bytes from socket into buffer
*/
static int ssh_socket_unbuffered_read(struct socket *s, void *buffer, uint32_t len) {
if (s->data_except)
return -1;
int rc;
while (1) {
rc = recv(s->fd, buffer, len, 0);
if (rc < 0 && errno == EINTR)
continue;
#ifdef _WIN32
s->last_errno = WSAGetLastError();
#else
s->last_errno = errno;
#endif
break;
}
s->data_to_read = 0;
if (rc < 0)
s->data_except = 1;
return rc;
}
/* \internal
* \brief writes len bytes from buffer to socket
*/
static int ssh_socket_unbuffered_write(struct socket *s, const void *buffer,
uint32_t len) {
int w = -1;
if (s->data_except) {
return -1;
}
w = send(s->fd,buffer, len, 0);
#ifdef _WIN32
s->last_errno = WSAGetLastError();
#else
s->last_errno = errno;
#endif
s->data_to_write = 0;
if (w < 0) {
s->data_except = 1;
}
return w;
}
/* \internal
* \brief returns nonzero if the current socket is in the fd_set
*/
int ssh_socket_fd_isset(struct socket *s, fd_set *set) {
if(s->fd == -1) {
return 0;
}
return FD_ISSET(s->fd,set);
}
/* \internal
* \brief sets the current fd in a fd_set and updates the fd_max
*/
void ssh_socket_fd_set(struct socket *s, fd_set *set, int *fd_max) {
if (s->fd == -1)
return;
FD_SET(s->fd,set);
if (s->fd >= *fd_max) {
*fd_max = s->fd + 1;
}
}
/** \internal
* \brief reads blocking until len bytes have been read
*/
int ssh_socket_completeread(struct socket *s, void *buffer, uint32_t len) {
int r = -1;
uint32_t total = 0;
uint32_t toread = len;
if(! ssh_socket_is_open(s)) {
return SSH_ERROR;
}
while((r = ssh_socket_unbuffered_read(s, ((uint8_t*)buffer + total), toread))) {
if (r < 0) {
return SSH_ERROR;
}
total += r;
toread -= r;
if (total == len) {
return len;
}
if (r == 0) {
return 0;
}
}
/* connection closed */
return total;
}
/** \internal
* \brief Blocking write of len bytes
*/
int ssh_socket_completewrite(struct socket *s, const void *buffer, uint32_t len) {
ssh_session session = s->session;
int written = -1;
enter_function();
if(! ssh_socket_is_open(s)) {
leave_function();
return SSH_ERROR;
}
while (len >0) {
written = ssh_socket_unbuffered_write(s, buffer, len);
if (written == 0 || written == -1) {
leave_function();
return SSH_ERROR;
}
len -= written;
buffer = ((uint8_t*)buffer + written);
}
leave_function();
return SSH_OK;
}
/** \internal
* \brief buffered read of data (complete)
* \returns SSH_OK or SSH_ERROR.
* \returns SSH_AGAIN in nonblocking mode
*/
int ssh_socket_read(struct socket *s, void *buffer, int len){
ssh_session session = s->session;
int rc = SSH_ERROR;
enter_function();
rc = ssh_socket_wait_for_data(s, s->session, len);
if (rc != SSH_OK) {
leave_function();
return rc;
}
memcpy(buffer, buffer_get_rest(s->in_buffer), len);
buffer_pass_bytes(s->in_buffer, len);
leave_function();
return SSH_OK;
}
#define WRITE_BUFFERING_THRESHOLD 65536
/** \internal
* \brief buffered write of data
* \returns SSH_OK, or SSH_ERROR
* \warning has no effect on socket before a flush
*/
int ssh_socket_write(struct socket *s, const void *buffer, int len) {
ssh_session session = s->session;
int rc = SSH_ERROR;
enter_function();
if (buffer_add_data(s->out_buffer, buffer, len) < 0) {
return SSH_ERROR;
}
if (buffer_get_rest_len(s->out_buffer) > WRITE_BUFFERING_THRESHOLD) {
rc = ssh_socket_nonblocking_flush(s);
} else {
rc = len;
}
leave_function();
return rc;
}
/** \internal
* \brief wait for data on socket
* \param s socket
* \param session the ssh session
* \param len number of bytes to be read
* \returns SSH_OK bytes are available on socket
* \returns SSH_AGAIN need to call later for data
* \returns SSH_ERROR error happened
*/
int ssh_socket_wait_for_data(struct socket *s, ssh_session session, uint32_t len) {
char buffer[4096] = {0};
char *buf = NULL;
int except;
int can_write;
int to_read;
int r;
enter_function();
to_read = len - buffer_get_rest_len(s->in_buffer);
if (to_read <= 0) {
leave_function();
return SSH_OK;
}
if (session->blocking) {
buf = malloc(to_read);
if (buf == NULL) {
leave_function();
return SSH_ERROR;
}
r = ssh_socket_completeread(session->socket,buf,to_read);
if (r == SSH_ERROR || r == 0) {
ssh_set_error(session, SSH_FATAL,
(r == 0) ? "Connection closed by remote host" :
"Error reading socket");
ssh_socket_close(session->socket);
session->alive = 0;
SAFE_FREE(buf);
leave_function();
return SSH_ERROR;
}
if (buffer_add_data(s->in_buffer,buf,to_read) < 0) {
SAFE_FREE(buf);
leave_function();
return SSH_ERROR;
}
SAFE_FREE(buf);
leave_function();
return SSH_OK;
}
/* nonblocking read */
do {
/* internally sets data_to_read */
r = ssh_socket_poll(s, &can_write, &except);
if (r < 0 || !s->data_to_read) {
leave_function();
return SSH_AGAIN;
}
/* read as much as we can */
if (ssh_socket_is_open(session->socket)) {
r = ssh_socket_unbuffered_read(session->socket, buffer, sizeof(buffer));
} else {
r =- 1;
}
if (r <= 0) {
ssh_set_error(session, SSH_FATAL,
(r == 0) ? "Connection closed by remote host" :
"Error reading socket");
ssh_socket_close(session->socket);
session->alive = 0;
leave_function();
return SSH_ERROR;
}
if (buffer_add_data(s->in_buffer,buffer, (uint32_t) r) < 0) {
leave_function();
return SSH_ERROR;
}
} while(buffer_get_rest_len(s->in_buffer) < len);
leave_function();
return SSH_OK;
}
/* ssh_socket_poll */
int ssh_socket_poll(struct socket *s, int *writeable, int *except) {
ssh_session session = s->session;
ssh_pollfd_t fd[1];
int rc = -1;
enter_function();
if (!ssh_socket_is_open(s)) {
*except = 1;
*writeable = 0;
return 0;
}
fd->fd = s->fd;
fd->events = 0;
if (!s->data_to_read) {
fd->events |= POLLIN;
}
if (!s->data_to_write) {
fd->events |= POLLOUT;
}
/* Make the call, and listen for errors */
rc = ssh_poll(fd, 1, 0);
if (rc < 0) {
ssh_set_error(session, SSH_FATAL, "poll(): %s", strerror(errno));
leave_function();
return -1;
}
if (!s->data_to_read) {
s->data_to_read = fd->revents & POLLIN;
}
if (!s->data_to_write) {
s->data_to_write = fd->revents & POLLOUT;
}
if (!s->data_except) {
s->data_except = fd->revents & POLLERR;
}
*except = s->data_except;
*writeable = s->data_to_write;
leave_function();
return (s->data_to_read || (buffer_get_rest_len(s->in_buffer) > 0));
}
/** \internal
* \brief nonblocking flush of the output buffer
*/
int ssh_socket_nonblocking_flush(struct socket *s) {
ssh_session session = s->session;
int except;
int can_write;
int w;
enter_function();
/* internally sets data_to_write */
if (ssh_socket_poll(s, &can_write, &except) < 0) {
leave_function();
return SSH_ERROR;
}
if (!ssh_socket_is_open(s)) {
session->alive = 0;
/* FIXME use ssh_socket_get_errno */
ssh_set_error(session, SSH_FATAL,
"Writing packet: error on socket (or connection closed): %s",
strerror(errno));
leave_function();
return SSH_ERROR;
}
while(s->data_to_write && buffer_get_rest_len(s->out_buffer) > 0) {
if (ssh_socket_is_open(s)) {
w = ssh_socket_unbuffered_write(s, buffer_get_rest(s->out_buffer),
buffer_get_rest_len(s->out_buffer));
} else {
/* write failed */
w =- 1;
}
if (w < 0) {
session->alive = 0;
ssh_socket_close(s);
/* FIXME use ssh_socket_get_errno() */
ssh_set_error(session, SSH_FATAL,
"Writing packet: error on socket (or connection closed): %s",
strerror(errno));
leave_function();
return SSH_ERROR;
}
buffer_pass_bytes(s->out_buffer, w);
/* refresh the socket status */
if (ssh_socket_poll(session->socket, &can_write, &except) < 0) {
leave_function();
return SSH_ERROR;
}
}
/* Is there some data pending? */
if (buffer_get_rest_len(s->out_buffer) > 0) {
leave_function();
return SSH_AGAIN;
}
/* all data written */
leave_function();
return SSH_OK;
}
/** \internal
* \brief locking flush of the output packet buffer
*/
int ssh_socket_blocking_flush(struct socket *s) {
ssh_session session = s->session;
enter_function();
if (!ssh_socket_is_open(s)) {
session->alive = 0;
leave_function();
return SSH_ERROR;
}
if (s->data_except) {
leave_function();
return SSH_ERROR;
}
if (buffer_get_rest_len(s->out_buffer) == 0) {
leave_function();
return SSH_OK;
}
if (ssh_socket_completewrite(s, buffer_get_rest(s->out_buffer),
buffer_get_rest_len(s->out_buffer)) != SSH_OK) {
session->alive = 0;
ssh_socket_close(s);
/* FIXME use the proper errno */
ssh_set_error(session, SSH_FATAL,
"Writing packet: error on socket (or connection closed): %s",
strerror(errno));
leave_function();
return SSH_ERROR;
}
if (buffer_reinit(s->out_buffer) < 0) {
leave_function();
return SSH_ERROR;
}
leave_function();
return SSH_OK; // no data pending
}
void ssh_socket_set_towrite(struct socket *s) {
s->data_to_write = 1;
}
void ssh_socket_set_toread(struct socket *s) {
s->data_to_read = 1;
}
void ssh_socket_set_except(struct socket *s) {
s->data_except = 1;
}
int ssh_socket_data_available(struct socket *s) {
return s->data_to_read;
}
int ssh_socket_data_writable(struct socket *s) {
return s->data_to_write;
}
int ssh_socket_get_status(struct socket *s) {
int r = 0;
if (s->data_to_read) {
r |= SSH_READ_PENDING;
}
if (s->data_except) {
r |= SSH_CLOSED_ERROR;
}
return r;
}
#ifndef _WIN32
/**
* @internal
* @brief executes a command and redirect input and outputs
* @param command command to execute
* @param in input file descriptor
* @param out output file descriptor
*/
void ssh_execute_command(const char *command, socket_t in, socket_t out){
const char *args[]={"/bin/sh","-c",command,NULL};
/* redirect in and out to stdin, stdout and stderr */
dup2(in, 0);
dup2(out,1);
dup2(out,2);
close(in);
close(out);
execve(args[0],(char * const *)args,(char * const *)environ);
exit(1);
}
/**
* @internal
* @brief Open a socket on a ProxyCommand
* This call will always be nonblocking.
* @param s socket to connect.
* @param command Command to execute.
* @returns SSH_OK socket is being connected.
* @returns SSH_ERROR error while executing the command.
*/
socket_t ssh_socket_connect_proxycommand(ssh_session session,
const char *command){
socket_t fd[2];
int pid;
enter_function();
socketpair(AF_UNIX,SOCK_STREAM,0,fd);
pid = fork();
if(pid == 0){
ssh_execute_command(command,fd[1],fd[1]);
}
close(fd[1]);
ssh_log(session,SSH_LOG_PROTOCOL,"ProxyCommand connection pipe: [%d,%d]",fd[0],fd[1]);
return fd[0];
}
#endif /* _WIN32 */
/** @}
*/
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/socket.c
|
C
|
gpl3
| 15,310
|
AM_CFLAGS = -O2 -pipe -Wall @ENABLE_DEBUG@
AM_CPPFLAGS = -DWITH_SERVER -DWITH_SSH1 -DWITH_SFTP -I../include
lib_LTLIBRARIES = libfbssh.la
libfbssh_la_SOURCES = agent.c auth.c auth1.c base64.c buffer.c callbacks.c \
channels.c channels1.c client.c config.c connect.c \
crc32.c crypt.c dh.c error.c gcrypt_missing.c gzip.c \
init.c kex.c keyfiles.c keys.c log.c match.c messages.c \
misc.c options.c packet.c pcap.c poll.c scp.c server.c \
session.c sftp.c sftpserver.c socket.c string.c wrapper.c
|
zzlydm-fbbs
|
libssh/Makefile.am
|
Makefile
|
gpl3
| 548
|
/*
* misc.c - useful client functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
* Copyright (c) 2008-2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
#define _WIN32_IE 0x0501 //SHGetSpecialFolderPath
#include <winsock2.h> // Must be the first to include
#include <ws2tcpip.h>
#include <shlobj.h>
#include <direct.h>
#else
/* This is needed for a standard getpwuid_r on opensolaris */
#define _POSIX_PTHREAD_SEMANTICS
#include <pwd.h>
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/misc.h"
#include "libssh/session.h"
#ifdef HAVE_LIBGCRYPT
#define GCRYPT_STRING "/gnutls"
#else
#define GCRYPT_STRING ""
#endif
#ifdef HAVE_LIBCRYPTO
#define CRYPTO_STRING "/openssl"
#else
#define CRYPTO_STRING ""
#endif
#if defined(HAVE_LIBZ) && defined(WITH_LIBZ)
#define LIBZ_STRING "/zlib"
#else
#define LIBZ_STRING ""
#endif
/** \defgroup ssh_misc SSH Misc
* \brief Misc functions
*/
/** \addtogroup ssh_misc
* @{ */
#ifdef _WIN32
char *ssh_get_user_home_dir(void) {
char tmp[MAX_PATH] = {0};
char *szPath = NULL;
if (SHGetSpecialFolderPathA(NULL, tmp, CSIDL_PROFILE, TRUE)) {
szPath = malloc(strlen(tmp) + 1);
if (szPath == NULL) {
return NULL;
}
strcpy(szPath, tmp);
return szPath;
}
return NULL;
}
/* we have read access on file */
int ssh_file_readaccess_ok(const char *file) {
if (_access(file, 4) < 0) {
return 0;
}
return 1;
}
#define SSH_USEC_IN_SEC 1000000LL
#define SSH_SECONDS_SINCE_1601 11644473600LL
int gettimeofday(struct timeval *__p, void *__t) {
union {
unsigned long long ns100; /* time since 1 Jan 1601 in 100ns units */
FILETIME ft;
} now;
GetSystemTimeAsFileTime (&now.ft);
__p->tv_usec = (long) ((now.ns100 / 10LL) % SSH_USEC_IN_SEC);
__p->tv_sec = (long)(((now.ns100 / 10LL ) / SSH_USEC_IN_SEC) - SSH_SECONDS_SINCE_1601);
return (0);
}
#else /* _WIN32 */
#ifndef NSS_BUFLEN_PASSWD
#define NSS_BUFLEN_PASSWD 4096
#endif
char *ssh_get_user_home_dir(void) {
char *szPath = NULL;
struct passwd pwd;
struct passwd *pwdbuf;
char buf[NSS_BUFLEN_PASSWD];
int rc;
rc = getpwuid_r(getuid(), &pwd, buf, NSS_BUFLEN_PASSWD, &pwdbuf);
if (rc != 0) {
return NULL;
}
szPath = strdup(pwd.pw_dir);
return szPath;
}
/* we have read access on file */
int ssh_file_readaccess_ok(const char *file) {
if (access(file, R_OK) < 0) {
return 0;
}
return 1;
}
#endif
char *ssh_hostport(const char *host, int port){
char *dest;
size_t len;
if(host==NULL)
return NULL;
/* 3 for []:, 5 for 65536 and 1 for nul */
len=strlen(host) + 3 + 5 + 1;
dest=malloc(len);
if(dest==NULL)
return NULL;
snprintf(dest,len,"[%s]:%d",host,port);
return dest;
}
uint64_t ntohll(uint64_t a) {
#ifdef WORDS_BIGENDIAN
return a;
#else
uint32_t low = (uint32_t)(a & 0xffffffff);
uint32_t high = (uint32_t)(a >> 32);
low = ntohl(low);
high = ntohl(high);
return ((((uint64_t) low) << 32) | ( high));
#endif
}
#ifdef _WIN32
char *ssh_get_local_username(ssh_session session) {
DWORD size = 0;
char *user;
/* get the size */
GetUserName(NULL, &size);
user = malloc(size);
if (user == NULL) {
ssh_set_error_oom(session);
return NULL;
}
if (GetUserName(user, &size)) {
return user;
}
return NULL;
}
#else
char *ssh_get_local_username(ssh_session session) {
struct passwd pwd;
struct passwd *pwdbuf;
char buf[NSS_BUFLEN_PASSWD];
char *name;
int rc;
rc = getpwuid_r(getuid(), &pwd, buf, NSS_BUFLEN_PASSWD, &pwdbuf);
if (rc != 0) {
ssh_set_error(session, SSH_FATAL,
"Couldn't retrieve information for current user!");
return NULL;
}
name = strdup(pwd.pw_name);
if (name == NULL) {
ssh_set_error_oom(session);
return NULL;
}
return name;
}
#endif
/**
* @brief Check if libssh is the required version or get the version
* string.
*
* @param req_version The version required.
*
* @return If the version of libssh is newer than the version
* required it will return a version string.
* NULL if the version is older.
*
* Example:
*
* @code
* if (ssh_version(SSH_VERSION_INT(0,2,1)) == NULL) {
* fprintf(stderr, "libssh version is too old!\n");
* exit(1);
* }
*
* if (debug) {
* printf("libssh %s\n", ssh_version(0));
* }
* @endcode
*/
const char *ssh_version(int req_version) {
if (req_version <= LIBSSH_VERSION_INT) {
return SSH_STRINGIFY(LIBSSH_VERSION) GCRYPT_STRING CRYPTO_STRING
LIBZ_STRING;
}
return NULL;
}
struct ssh_list *ssh_list_new(){
struct ssh_list *ret=malloc(sizeof(struct ssh_list));
if(!ret)
return NULL;
ret->root=ret->end=NULL;
return ret;
}
void ssh_list_free(struct ssh_list *list){
struct ssh_iterator *ptr,*next;
ptr=list->root;
while(ptr){
next=ptr->next;
SAFE_FREE(ptr);
ptr=next;
}
SAFE_FREE(list);
}
struct ssh_iterator *ssh_list_get_iterator(const struct ssh_list *list){
return list->root;
}
static struct ssh_iterator *ssh_iterator_new(const void *data){
struct ssh_iterator *iterator=malloc(sizeof(struct ssh_iterator));
if(!iterator)
return NULL;
iterator->next=NULL;
iterator->data=data;
return iterator;
}
int ssh_list_append(struct ssh_list *list,const void *data){
struct ssh_iterator *iterator=ssh_iterator_new(data);
if(!iterator)
return SSH_ERROR;
if(!list->end){
/* list is empty */
list->root=list->end=iterator;
} else {
/* put it on end of list */
list->end->next=iterator;
list->end=iterator;
}
return SSH_OK;
}
int ssh_list_prepend(struct ssh_list *list, const void *data){
struct ssh_iterator *it = ssh_iterator_new(data);
if (it == NULL) {
return SSH_ERROR;
}
if (list->end == NULL) {
/* list is empty */
list->root = list->end = it;
} else {
/* set as new root */
it->next = list->root;
list->root = it;
}
return SSH_OK;
}
void ssh_list_remove(struct ssh_list *list, struct ssh_iterator *iterator){
struct ssh_iterator *ptr,*prev;
prev=NULL;
ptr=list->root;
while(ptr && ptr != iterator){
prev=ptr;
ptr=ptr->next;
}
if(!ptr){
/* we did not find the element */
return;
}
/* unlink it */
if(prev)
prev->next=ptr->next;
/* if iterator was the head */
if(list->root == iterator)
list->root=iterator->next;
/* if iterator was the tail */
if(list->end == iterator)
list->end = prev;
SAFE_FREE(iterator);
}
/** @internal
* @brief Removes the top element of the list and returns the data value attached
* to it
* @param list the ssh_list
* @returns pointer to the element being stored in head, or
* NULL if the list is empty.
*/
const void *_ssh_list_pop_head(struct ssh_list *list){
struct ssh_iterator *iterator=list->root;
const void *data;
if(!list->root)
return NULL;
data=iterator->data;
list->root=iterator->next;
if(list->end==iterator)
list->end=NULL;
SAFE_FREE(iterator);
return data;
}
/**
* @brief Parse directory component.
*
* dirname breaks a null-terminated pathname string into a directory component.
* In the usual case, ssh_dirname() returns the string up to, but not including,
* the final '/'. Trailing '/' characters are not counted as part of the
* pathname. The caller must free the memory.
*
* @param path The path to parse.
*
* @return The dirname of path or NULL if we can't allocate memory. If path
* does not contain a slash, c_dirname() returns the string ".". If
* path is the string "/", it returns the string "/". If path is
* NULL or an empty string, "." is returned.
*/
char *ssh_dirname (const char *path) {
char *new = NULL;
unsigned int len;
if (path == NULL || *path == '\0') {
return strdup(".");
}
len = strlen(path);
/* Remove trailing slashes */
while(len > 0 && path[len - 1] == '/') --len;
/* We have only slashes */
if (len == 0) {
return strdup("/");
}
/* goto next slash */
while(len > 0 && path[len - 1] != '/') --len;
if (len == 0) {
return strdup(".");
} else if (len == 1) {
return strdup("/");
}
/* Remove slashes again */
while(len > 0 && path[len - 1] == '/') --len;
new = malloc(len + 1);
if (new == NULL) {
return NULL;
}
strncpy(new, path, len);
new[len] = '\0';
return new;
}
/**
* @brief basename - parse filename component.
*
* basename breaks a null-terminated pathname string into a filename component.
* ssh_basename() returns the component following the final '/'. Trailing '/'
* characters are not counted as part of the pathname.
*
* @param path The path to parse.
*
* @return The filename of path or NULL if we can't allocate memory. If path
* is a the string "/", basename returns the string "/". If path is
* NULL or an empty string, "." is returned.
*/
char *ssh_basename (const char *path) {
char *new = NULL;
const char *s;
unsigned int len;
if (path == NULL || *path == '\0') {
return strdup(".");
}
len = strlen(path);
/* Remove trailing slashes */
while(len > 0 && path[len - 1] == '/') --len;
/* We have only slashes */
if (len == 0) {
return strdup("/");
}
while(len > 0 && path[len - 1] != '/') --len;
if (len > 0) {
s = path + len;
len = strlen(s);
while(len > 0 && s[len - 1] == '/') --len;
} else {
return strdup(path);
}
new = malloc(len + 1);
if (new == NULL) {
return NULL;
}
strncpy(new, s, len);
new[len] = '\0';
return new;
}
/**
* @brief Attempts to create a directory with the given pathname.
*
* This is the portable version of mkdir, mode is ignored on Windows systems.
*
* @param pathname The path name to create the directory.
*
* @param mode The permissions to use.
*
* @return 0 on success, < 0 on error with errno set.
*/
int ssh_mkdir(const char *pathname, mode_t mode) {
int r;
#ifdef _WIN32
r = _mkdir(pathname);
#else
r = mkdir(pathname, mode);
#endif
return r;
}
/**
* @brief Expand a directory starting with a tilde '~'
*
* @param[in] session The ssh session to use.
*
* @param[in] d The directory to expand.
*
* @return The expanded directory, NULL on error.
*/
char *ssh_path_expand_tilde(const char *d) {
char *h, *r;
const char *p;
size_t ld;
size_t lh = 0;
if (d[0] != '~') {
return strdup(d);
}
d++;
/* handle ~user/path */
p = strchr(d, '/');
if (p != NULL && p > d) {
#ifdef _WIN32
return strdup(d);
#else
struct passwd *pw;
size_t s = p - d;
char u[128];
if (s > sizeof(u)) {
return NULL;
}
memcpy(u, d, s);
u[s] = '\0';
pw = getpwnam(u);
if (pw == NULL) {
return NULL;
}
ld = strlen(p);
h = strdup(pw->pw_dir);
#endif
} else {
ld = strlen(d);
p = (char *) d;
h = ssh_get_user_home_dir();
}
if (h == NULL) {
return NULL;
}
lh = strlen(h);
r = malloc(ld + lh + 1);
if (r == NULL) {
return NULL;
}
if (lh > 0) {
memcpy(r, h, lh);
}
memcpy(r + lh, p, ld);
return r;
}
char *ssh_path_expand_escape(ssh_session session, const char *s) {
#define MAX_BUF_SIZE 4096
char host[NI_MAXHOST];
char buf[MAX_BUF_SIZE];
char *r, *x = NULL;
const char *p;
size_t i, l;
if (strlen(s) > MAX_BUF_SIZE) {
ssh_set_error(session, SSH_FATAL, "string to expand too long");
return NULL;
}
r = ssh_path_expand_tilde(s);
if (r == NULL) {
ssh_set_error_oom(session);
return NULL;
}
p = r;
buf[0] = '\0';
for (i = 0; *p != '\0'; p++) {
if (*p != '%') {
buf[i] = *p;
i++;
if (i > MAX_BUF_SIZE) {
return NULL;
}
buf[i] = '\0';
continue;
}
p++;
if (*p == '\0') {
break;
}
switch (*p) {
case 'd':
x = strdup(session->sshdir);
break;
case 'u':
x = ssh_get_local_username(session);
break;
case 'l':
if (gethostname(host, sizeof(host) == 0)) {
x = strdup(host);
}
break;
case 'h':
x = strdup(session->host);
break;
case 'r':
x = strdup(session->username);
break;
default:
ssh_set_error(session, SSH_FATAL,
"Wrong escape sequence detected");
return NULL;
}
if (x == NULL) {
ssh_set_error_oom(session);
return NULL;
}
i += strlen(x);
if (i > MAX_BUF_SIZE) {
ssh_set_error(session, SSH_FATAL,
"String too long");
return NULL;
}
l = strlen(buf);
strcat(buf + l, x);
SAFE_FREE(x);
}
free(r);
return strdup(buf);
#undef MAX_BUF_SIZE
}
/* @} */
/* vim: set ts=4 sw=4 et cindent: */
|
zzlydm-fbbs
|
libssh/misc.c
|
C
|
gpl3
| 14,273
|
/*
* keys.c - decoding a public key or signature and verifying them
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2005 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_LIBCRYPTO
#include <openssl/dsa.h>
#include <openssl/rsa.h>
#endif
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/server.h"
#include "libssh/buffer.h"
#include "libssh/agent.h"
#include "libssh/session.h"
#include "libssh/keys.h"
#include "libssh/dh.h"
#include "libssh/messages.h"
#include "libssh/string.h"
/** \addtogroup ssh_auth
* @{
*/
/* Public key decoding functions */
const char *ssh_type_to_char(int type) {
switch (type) {
case TYPE_DSS:
return "ssh-dss";
case TYPE_RSA:
return "ssh-rsa";
case TYPE_RSA1:
return "ssh-rsa1";
default:
return NULL;
}
}
int ssh_type_from_name(const char *name) {
if (strcmp(name, "rsa1") == 0) {
return TYPE_RSA1;
} else if (strcmp(name, "rsa") == 0) {
return TYPE_RSA;
} else if (strcmp(name, "dsa") == 0) {
return TYPE_DSS;
} else if (strcmp(name, "ssh-rsa1") == 0) {
return TYPE_RSA1;
} else if (strcmp(name, "ssh-rsa") == 0) {
return TYPE_RSA;
} else if (strcmp(name, "ssh-dss") == 0) {
return TYPE_DSS;
}
return -1;
}
ssh_public_key publickey_make_dss(ssh_session session, ssh_buffer buffer) {
ssh_string p = NULL;
ssh_string q = NULL;
ssh_string g = NULL;
ssh_string pubkey = NULL;
ssh_public_key key = NULL;
key = malloc(sizeof(struct ssh_public_key_struct));
if (key == NULL) {
buffer_free(buffer);
return NULL;
}
key->type = TYPE_DSS;
key->type_c = ssh_type_to_char(key->type);
p = buffer_get_ssh_string(buffer);
q = buffer_get_ssh_string(buffer);
g = buffer_get_ssh_string(buffer);
pubkey = buffer_get_ssh_string(buffer);
buffer_free(buffer); /* we don't need it anymore */
if (p == NULL || q == NULL || g == NULL || pubkey == NULL) {
ssh_set_error(session, SSH_FATAL, "Invalid DSA public key");
goto error;
}
#ifdef HAVE_LIBGCRYPT
gcry_sexp_build(&key->dsa_pub, NULL,
"(public-key(dsa(p %b)(q %b)(g %b)(y %b)))",
string_len(p), string_data(p),
string_len(q), string_data(q),
string_len(g), string_data(g),
string_len(pubkey), string_data(pubkey));
if (key->dsa_pub == NULL) {
goto error;
}
#elif defined HAVE_LIBCRYPTO
key->dsa_pub = DSA_new();
if (key->dsa_pub == NULL) {
goto error;
}
key->dsa_pub->p = make_string_bn(p);
key->dsa_pub->q = make_string_bn(q);
key->dsa_pub->g = make_string_bn(g);
key->dsa_pub->pub_key = make_string_bn(pubkey);
if (key->dsa_pub->p == NULL ||
key->dsa_pub->q == NULL ||
key->dsa_pub->g == NULL ||
key->dsa_pub->pub_key == NULL) {
goto error;
}
#endif /* HAVE_LIBCRYPTO */
#ifdef DEBUG_CRYPTO
ssh_print_hexa("p", string_data(p), string_len(p));
ssh_print_hexa("q", string_data(q), string_len(q));
ssh_print_hexa("g", string_data(g), string_len(g));
#endif
string_burn(p);
string_free(p);
string_burn(q);
string_free(q);
string_burn(g);
string_free(g);
string_burn(pubkey);
string_free(pubkey);
return key;
error:
string_burn(p);
string_free(p);
string_burn(q);
string_free(q);
string_burn(g);
string_free(g);
string_burn(pubkey);
string_free(pubkey);
publickey_free(key);
return NULL;
}
ssh_public_key publickey_make_rsa(ssh_session session, ssh_buffer buffer,
int type) {
ssh_string e = NULL;
ssh_string n = NULL;
ssh_public_key key = NULL;
key = malloc(sizeof(struct ssh_public_key_struct));
if (key == NULL) {
buffer_free(buffer);
return NULL;
}
key->type = type;
key->type_c = ssh_type_to_char(key->type);
e = buffer_get_ssh_string(buffer);
n = buffer_get_ssh_string(buffer);
buffer_free(buffer); /* we don't need it anymore */
if(e == NULL || n == NULL) {
ssh_set_error(session, SSH_FATAL, "Invalid RSA public key");
goto error;
}
#ifdef HAVE_LIBGCRYPT
gcry_sexp_build(&key->rsa_pub, NULL,
"(public-key(rsa(n %b)(e %b)))",
string_len(n), string_data(n),
string_len(e),string_data(e));
if (key->rsa_pub == NULL) {
goto error;
}
#elif HAVE_LIBCRYPTO
key->rsa_pub = RSA_new();
if (key->rsa_pub == NULL) {
goto error;
}
key->rsa_pub->e = make_string_bn(e);
key->rsa_pub->n = make_string_bn(n);
if (key->rsa_pub->e == NULL ||
key->rsa_pub->n == NULL) {
goto error;
}
#endif
#ifdef DEBUG_CRYPTO
ssh_print_hexa("e", string_data(e), string_len(e));
ssh_print_hexa("n", string_data(n), string_len(n));
#endif
string_burn(e);
string_free(e);
string_burn(n);
string_free(n);
return key;
error:
string_burn(e);
string_free(e);
string_burn(n);
string_free(n);
publickey_free(key);
return NULL;
}
void publickey_free(ssh_public_key key) {
if (key == NULL) {
return;
}
switch(key->type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(key->dsa_pub);
#elif HAVE_LIBCRYPTO
DSA_free(key->dsa_pub);
#endif
break;
case TYPE_RSA:
case TYPE_RSA1:
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(key->rsa_pub);
#elif defined HAVE_LIBCRYPTO
RSA_free(key->rsa_pub);
#endif
break;
default:
break;
}
SAFE_FREE(key);
}
ssh_public_key publickey_from_string(ssh_session session, ssh_string pubkey_s) {
ssh_buffer tmpbuf = NULL;
ssh_string type_s = NULL;
char *type_c = NULL;
int type;
tmpbuf = buffer_new();
if (tmpbuf == NULL) {
return NULL;
}
if (buffer_add_data(tmpbuf, string_data(pubkey_s), string_len(pubkey_s)) < 0) {
goto error;
}
type_s = buffer_get_ssh_string(tmpbuf);
if (type_s == NULL) {
ssh_set_error(session,SSH_FATAL,"Invalid public key format");
goto error;
}
type_c = string_to_char(type_s);
string_free(type_s);
if (type_c == NULL) {
goto error;
}
type = ssh_type_from_name(type_c);
SAFE_FREE(type_c);
switch (type) {
case TYPE_DSS:
return publickey_make_dss(session, tmpbuf);
case TYPE_RSA:
case TYPE_RSA1:
return publickey_make_rsa(session, tmpbuf, type);
}
ssh_set_error(session, SSH_FATAL, "Unknown public key protocol %s",
ssh_type_to_char(type));
error:
buffer_free(tmpbuf);
return NULL;
}
/** \brief Makes a PUBLIC_KEY object out of a PRIVATE_KEY object
* \param prv the Private key
* \returns the public key
* \see publickey_to_string()
*/
ssh_public_key publickey_from_privatekey(ssh_private_key prv) {
ssh_public_key key = NULL;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t sexp;
const char *tmp = NULL;
size_t size;
ssh_string p = NULL;
ssh_string q = NULL;
ssh_string g = NULL;
ssh_string y = NULL;
ssh_string e = NULL;
ssh_string n = NULL;
#endif /* HAVE_LIBGCRYPT */
key = malloc(sizeof(struct ssh_public_key_struct));
if (key == NULL) {
return NULL;
}
key->type = prv->type;
switch(key->type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
sexp = gcry_sexp_find_token(prv->dsa_priv, "p", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
p = string_new(size);
if (p == NULL) {
goto error;
}
string_fill(p,(char *) tmp, size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(prv->dsa_priv,"q",0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp,1,&size);
q = string_new(size);
if (q == NULL) {
goto error;
}
string_fill(q,(char *) tmp,size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(prv->dsa_priv, "g", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp,1,&size);
g = string_new(size);
if (g == NULL) {
goto error;
}
string_fill(g,(char *) tmp,size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(prv->dsa_priv,"y",0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp,1,&size);
y = string_new(size);
if (y == NULL) {
goto error;
}
string_fill(y,(char *) tmp,size);
gcry_sexp_release(sexp);
gcry_sexp_build(&key->dsa_pub, NULL,
"(public-key(dsa(p %b)(q %b)(g %b)(y %b)))",
string_len(p), string_data(p),
string_len(q), string_data(q),
string_len(g), string_data(g),
string_len(y), string_data(y));
string_burn(p);
string_free(p);
string_burn(q);
string_free(q);
string_burn(g);
string_free(g);
string_burn(y);
string_free(y);
#elif defined HAVE_LIBCRYPTO
key->dsa_pub = DSA_new();
if (key->dsa_pub == NULL) {
goto error;
}
key->dsa_pub->p = BN_dup(prv->dsa_priv->p);
key->dsa_pub->q = BN_dup(prv->dsa_priv->q);
key->dsa_pub->g = BN_dup(prv->dsa_priv->g);
key->dsa_pub->pub_key = BN_dup(prv->dsa_priv->pub_key);
if (key->dsa_pub->p == NULL ||
key->dsa_pub->q == NULL ||
key->dsa_pub->g == NULL ||
key->dsa_pub->pub_key == NULL) {
goto error;
}
#endif /* HAVE_LIBCRYPTO */
break;
case TYPE_RSA:
case TYPE_RSA1:
#ifdef HAVE_LIBGCRYPT
sexp = gcry_sexp_find_token(prv->rsa_priv, "n", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
n = string_new(size);
if (n == NULL) {
goto error;
}
string_fill(n, (char *) tmp, size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(prv->rsa_priv, "e", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
e = string_new(size);
if (e == NULL) {
goto error;
}
string_fill(e, (char *) tmp, size);
gcry_sexp_release(sexp);
gcry_sexp_build(&key->rsa_pub, NULL,
"(public-key(rsa(n %b)(e %b)))",
string_len(n), string_data(n),
string_len(e), string_data(e));
if (key->rsa_pub == NULL) {
goto error;
}
string_burn(e);
string_free(e);
string_burn(n);
string_free(n);
#elif defined HAVE_LIBCRYPTO
key->rsa_pub = RSA_new();
if (key->rsa_pub == NULL) {
goto error;
}
key->rsa_pub->e = BN_dup(prv->rsa_priv->e);
key->rsa_pub->n = BN_dup(prv->rsa_priv->n);
if (key->rsa_pub->e == NULL ||
key->rsa_pub->n == NULL) {
goto error;
}
#endif
break;
}
key->type_c = ssh_type_to_char(prv->type);
return key;
error:
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(sexp);
string_burn(p);
string_free(p);
string_burn(q);
string_free(q);
string_burn(g);
string_free(g);
string_burn(y);
string_free(y);
string_burn(e);
string_free(e);
string_burn(n);
string_free(n);
#endif
publickey_free(key);
return NULL;
}
#ifdef HAVE_LIBGCRYPT
static int dsa_public_to_string(gcry_sexp_t key, ssh_buffer buffer) {
#elif defined HAVE_LIBCRYPTO
static int dsa_public_to_string(DSA *key, ssh_buffer buffer) {
#endif
ssh_string p = NULL;
ssh_string q = NULL;
ssh_string g = NULL;
ssh_string n = NULL;
int rc = -1;
#ifdef HAVE_LIBGCRYPT
const char *tmp = NULL;
size_t size;
gcry_sexp_t sexp;
sexp = gcry_sexp_find_token(key, "p", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
p = string_new(size);
if (p == NULL) {
goto error;
}
string_fill(p, (char *) tmp, size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(key, "q", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
q = string_new(size);
if (q == NULL) {
goto error;
}
string_fill(q, (char *) tmp, size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(key, "g", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
g = string_new(size);
if (g == NULL) {
goto error;
}
string_fill(g, (char *) tmp, size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(key, "y", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
n = string_new(size);
if (n == NULL) {
goto error;
}
string_fill(n, (char *) tmp, size);
#elif defined HAVE_LIBCRYPTO
p = make_bignum_string(key->p);
q = make_bignum_string(key->q);
g = make_bignum_string(key->g);
n = make_bignum_string(key->pub_key);
if (p == NULL || q == NULL || g == NULL || n == NULL) {
goto error;
}
#endif /* HAVE_LIBCRYPTO */
if (buffer_add_ssh_string(buffer, p) < 0) {
goto error;
}
if (buffer_add_ssh_string(buffer, q) < 0) {
goto error;
}
if (buffer_add_ssh_string(buffer, g) < 0) {
goto error;
}
if (buffer_add_ssh_string(buffer, n) < 0) {
goto error;
}
rc = 0;
error:
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(sexp);
#endif
string_burn(p);
string_free(p);
string_burn(q);
string_free(q);
string_burn(g);
string_free(g);
string_burn(n);
string_free(n);
return rc;
}
#ifdef HAVE_LIBGCRYPT
static int rsa_public_to_string(gcry_sexp_t key, ssh_buffer buffer) {
#elif defined HAVE_LIBCRYPTO
static int rsa_public_to_string(RSA *key, ssh_buffer buffer) {
#endif
ssh_string e = NULL;
ssh_string n = NULL;
int rc = -1;
#ifdef HAVE_LIBGCRYPT
const char *tmp;
size_t size;
gcry_sexp_t sexp;
sexp = gcry_sexp_find_token(key, "n", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
n = string_new(size);
if (n == NULL) {
goto error;
}
string_fill(n, (char *) tmp, size);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(key, "e", 0);
if (sexp == NULL) {
goto error;
}
tmp = gcry_sexp_nth_data(sexp, 1, &size);
e = string_new(size);
if (e == NULL) {
goto error;
}
string_fill(e, (char *) tmp, size);
#elif defined HAVE_LIBCRYPTO
e = make_bignum_string(key->e);
n = make_bignum_string(key->n);
if (e == NULL || n == NULL) {
goto error;
}
#endif
if (buffer_add_ssh_string(buffer, e) < 0) {
goto error;
}
if (buffer_add_ssh_string(buffer, n) < 0) {
goto error;
}
rc = 0;
error:
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(sexp);
#endif
string_burn(e);
string_free(e);
string_burn(n);
string_free(n);
return rc;
}
/** \brief makes a SSH String out of a PUBLIC_KEY object
* \param key the public key
* \returns a SSH String containing the public key
* \see string_free()
*/
ssh_string publickey_to_string(ssh_public_key key) {
ssh_string type = NULL;
ssh_string ret = NULL;
ssh_buffer buf = NULL;
buf = buffer_new();
if (buf == NULL) {
return NULL;
}
type = string_from_char(key->type_c);
if (type == NULL) {
goto error;
}
if (buffer_add_ssh_string(buf, type) < 0) {
goto error;
}
switch (key->type) {
case TYPE_DSS:
if (dsa_public_to_string(key->dsa_pub, buf) < 0) {
goto error;
}
break;
case TYPE_RSA:
case TYPE_RSA1:
if (rsa_public_to_string(key->rsa_pub, buf) < 0) {
goto error;
}
break;
}
ret = string_new(buffer_get_len(buf));
if (ret == NULL) {
goto error;
}
string_fill(ret, buffer_get(buf), buffer_get_len(buf));
error:
buffer_free(buf);
string_free(type);
return ret;
}
/* Signature decoding functions */
static ssh_string signature_to_string(SIGNATURE *sign) {
unsigned char buffer[40] = {0};
ssh_buffer tmpbuf = NULL;
ssh_string str = NULL;
ssh_string tmp = NULL;
ssh_string rs = NULL;
int rc = -1;
#ifdef HAVE_LIBGCRYPT
const char *r = NULL;
const char *s = NULL;
gcry_sexp_t sexp;
size_t size = 0;
#elif defined HAVE_LIBCRYPTO
ssh_string r = NULL;
ssh_string s = NULL;
#endif
tmpbuf = buffer_new();
if (tmpbuf == NULL) {
return NULL;
}
tmp = string_from_char(ssh_type_to_char(sign->type));
if (tmp == NULL) {
buffer_free(tmpbuf);
return NULL;
}
if (buffer_add_ssh_string(tmpbuf, tmp) < 0) {
buffer_free(tmpbuf);
string_free(tmp);
return NULL;
}
string_free(tmp);
switch(sign->type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
sexp = gcry_sexp_find_token(sign->dsa_sign, "r", 0);
if (sexp == NULL) {
buffer_free(tmpbuf);
return NULL;
}
r = gcry_sexp_nth_data(sexp, 1, &size);
if (*r == 0) { /* libgcrypt put 0 when first bit is set */
size--;
r++;
}
memcpy(buffer, r + size - 20, 20);
gcry_sexp_release(sexp);
sexp = gcry_sexp_find_token(sign->dsa_sign, "s", 0);
if (sexp == NULL) {
buffer_free(tmpbuf);
return NULL;
}
s = gcry_sexp_nth_data(sexp,1,&size);
if (*s == 0) {
size--;
s++;
}
memcpy(buffer+ 20, s + size - 20, 20);
gcry_sexp_release(sexp);
#elif defined HAVE_LIBCRYPTO
r = make_bignum_string(sign->dsa_sign->r);
if (r == NULL) {
buffer_free(tmpbuf);
return NULL;
}
s = make_bignum_string(sign->dsa_sign->s);
if (s == NULL) {
buffer_free(tmpbuf);
string_free(r);
return NULL;
}
memcpy(buffer, (char *)string_data(r) + string_len(r) - 20, 20);
memcpy(buffer + 20, (char *)string_data(s) + string_len(s) - 20, 20);
string_free(r);
string_free(s);
#endif /* HAVE_LIBCRYPTO */
rs = string_new(40);
if (rs == NULL) {
buffer_free(tmpbuf);
return NULL;
}
string_fill(rs, buffer, 40);
rc = buffer_add_ssh_string(tmpbuf, rs);
string_free(rs);
if (rc < 0) {
buffer_free(tmpbuf);
return NULL;
}
break;
case TYPE_RSA:
case TYPE_RSA1:
#ifdef HAVE_LIBGCRYPT
sexp = gcry_sexp_find_token(sign->rsa_sign, "s", 0);
if (sexp == NULL) {
buffer_free(tmpbuf);
return NULL;
}
s = gcry_sexp_nth_data(sexp,1,&size);
if (*s == 0) {
size--;
s++;
}
rs = string_new(size);
if (rs == NULL) {
buffer_free(tmpbuf);
return NULL;
}
string_fill(rs, (char *) s, size);
rc = buffer_add_ssh_string(tmpbuf, rs);
gcry_sexp_release(sexp);
string_free(rs);
if (rc < 0) {
buffer_free(tmpbuf);
return NULL;
}
#elif defined HAVE_LIBCRYPTO
if (buffer_add_ssh_string(tmpbuf,sign->rsa_sign) < 0) {
buffer_free(tmpbuf);
return NULL;
}
#endif
break;
}
str = string_new(buffer_get_len(tmpbuf));
if (str == NULL) {
buffer_free(tmpbuf);
return NULL;
}
string_fill(str, buffer_get(tmpbuf), buffer_get_len(tmpbuf));
buffer_free(tmpbuf);
return str;
}
/* TODO : split this function in two so it becomes smaller */
SIGNATURE *signature_from_string(ssh_session session, ssh_string signature,
ssh_public_key pubkey, int needed_type) {
SIGNATURE *sign = NULL;
ssh_buffer tmpbuf = NULL;
ssh_string rs = NULL;
ssh_string type_s = NULL;
ssh_string e = NULL;
char *type_c = NULL;
int type;
int len;
int rsalen;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t sig;
#elif defined HAVE_LIBCRYPTO
DSA_SIG *sig = NULL;
ssh_string r = NULL;
ssh_string s = NULL;
#endif
sign = malloc(sizeof(SIGNATURE));
if (sign == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
return NULL;
}
tmpbuf = buffer_new();
if (tmpbuf == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
signature_free(sign);
return NULL;
}
if (buffer_add_data(tmpbuf, string_data(signature), string_len(signature)) < 0) {
signature_free(sign);
buffer_free(tmpbuf);
return NULL;
}
type_s = buffer_get_ssh_string(tmpbuf);
if (type_s == NULL) {
ssh_set_error(session, SSH_FATAL, "Invalid signature packet");
signature_free(sign);
buffer_free(tmpbuf);
return NULL;
}
type_c = string_to_char(type_s);
string_free(type_s);
if (type_c == NULL) {
signature_free(sign);
buffer_free(tmpbuf);
return NULL;
}
type = ssh_type_from_name(type_c);
SAFE_FREE(type_c);
if (needed_type != type) {
ssh_set_error(session, SSH_FATAL, "Invalid signature type: %s",
ssh_type_to_char(type));
signature_free(sign);
buffer_free(tmpbuf);
return NULL;
}
switch(needed_type) {
case TYPE_DSS:
rs = buffer_get_ssh_string(tmpbuf);
buffer_free(tmpbuf);
/* 40 is the dual signature blob len. */
if (rs == NULL || string_len(rs) != 40) {
string_free(rs);
signature_free(sign);
return NULL;
}
/* we make use of strings (because we have all-made functions to convert
* them to bignums (ou pas ;) */
#ifdef HAVE_LIBGCRYPT
if (gcry_sexp_build(&sig, NULL, "(sig-val(dsa(r %b)(s %b)))",
20 ,string_data(rs), 20,(unsigned char *)string_data(rs) + 20)) {
string_free(rs);
signature_free(sign);
return NULL;
}
#elif defined HAVE_LIBCRYPTO
r = string_new(20);
s = string_new(20);
if (r == NULL || s == NULL) {
string_free(r);
string_free(s);
string_free(rs);
signature_free(sign);
return NULL;
}
string_fill(r, string_data(rs), 20);
string_fill(s, (char *)string_data(rs) + 20, 20);
sig = DSA_SIG_new();
if (sig == NULL) {
string_free(r);
string_free(s);
string_free(rs);
signature_free(sign);
return NULL;
}
sig->r = make_string_bn(r); /* is that really portable ? Openssh's hack isn't better */
sig->s = make_string_bn(s);
string_free(r);
string_free(s);
if (sig->r == NULL || sig->s == NULL) {
string_free(rs);
DSA_SIG_free(sig);
signature_free(sign);
return NULL;
}
#endif
#ifdef DEBUG_CRYPTO
ssh_print_hexa("r", string_data(rs), 20);
ssh_print_hexa("s", (const unsigned char *)string_data(rs) + 20, 20);
#endif
string_free(rs);
sign->type = TYPE_DSS;
sign->dsa_sign = sig;
return sign;
case TYPE_RSA:
e = buffer_get_ssh_string(tmpbuf);
buffer_free(tmpbuf);
if (e == NULL) {
signature_free(sign);
return NULL;
}
len = string_len(e);
#ifdef HAVE_LIBGCRYPT
rsalen = (gcry_pk_get_nbits(pubkey->rsa_pub) + 7) / 8;
#elif defined HAVE_LIBCRYPTO
rsalen = RSA_size(pubkey->rsa_pub);
#endif
if (len > rsalen) {
string_free(e);
signature_free(sign);
ssh_set_error(session, SSH_FATAL, "Signature too big! %d instead of %d",
len, rsalen);
return NULL;
}
if (len < rsalen) {
ssh_log(session, SSH_LOG_RARE, "RSA signature len %d < %d",
len, rsalen);
}
sign->type = TYPE_RSA;
#ifdef HAVE_LIBGCRYPT
if (gcry_sexp_build(&sig, NULL, "(sig-val(rsa(s %b)))",
string_len(e), string_data(e))) {
signature_free(sign);
string_free(e);
return NULL;
}
sign->rsa_sign = sig;
#elif defined HAVE_LIBCRYPTO
sign->rsa_sign = e;
#endif
#ifdef DEBUG_CRYPTO
ssh_log(session, SSH_LOG_FUNCTIONS, "len e: %d", len);
ssh_print_hexa("RSA signature", string_data(e), len);
#endif
#ifdef HAVE_LIBGCRYPT
string_free(e);
#endif
return sign;
default:
return NULL;
}
return NULL;
}
void signature_free(SIGNATURE *sign) {
if (sign == NULL) {
return;
}
switch(sign->type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(sign->dsa_sign);
#elif defined HAVE_LIBCRYPTO
DSA_SIG_free(sign->dsa_sign);
#endif
break;
case TYPE_RSA:
case TYPE_RSA1:
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(sign->rsa_sign);
#elif defined HAVE_LIBCRYPTO
SAFE_FREE(sign->rsa_sign);
#endif
break;
default:
/* FIXME Passing NULL segfaults */
#if 0
ssh_log(NULL, SSH_LOG_RARE, "Freeing a signature with no type!\n"); */
#endif
break;
}
SAFE_FREE(sign);
}
#ifdef HAVE_LIBCRYPTO
/*
* Maybe the missing function from libcrypto
*
* I think now, maybe it's a bad idea to name it has it should have be
* named in libcrypto
*/
static ssh_string RSA_do_sign(const unsigned char *payload, int len, RSA *privkey) {
ssh_string sign = NULL;
unsigned char *buffer = NULL;
unsigned int size;
buffer = malloc(RSA_size(privkey));
if (buffer == NULL) {
return NULL;
}
if (RSA_sign(NID_sha1, payload, len, buffer, &size, privkey) == 0) {
SAFE_FREE(buffer);
return NULL;
}
sign = string_new(size);
if (sign == NULL) {
SAFE_FREE(buffer);
return NULL;
}
string_fill(sign, buffer, size);
SAFE_FREE(buffer);
return sign;
}
#endif
#ifndef _WIN32
ssh_string ssh_do_sign_with_agent(ssh_session session,
struct ssh_buffer_struct *buf, struct ssh_public_key_struct *publickey) {
struct ssh_buffer_struct *sigbuf = NULL;
struct ssh_string_struct *signature = NULL;
struct ssh_string_struct *session_id = NULL;
struct ssh_crypto_struct *crypto = NULL;
if (session->current_crypto) {
crypto = session->current_crypto;
} else {
crypto = session->next_crypto;
}
/* prepend session identifier */
session_id = string_new(SHA_DIGEST_LEN);
if (session_id == NULL) {
return NULL;
}
string_fill(session_id, crypto->session_id, SHA_DIGEST_LEN);
sigbuf = buffer_new();
if (sigbuf == NULL) {
string_free(session_id);
return NULL;
}
if (buffer_add_ssh_string(sigbuf, session_id) < 0) {
buffer_free(sigbuf);
string_free(session_id);
return NULL;
}
string_free(session_id);
/* append out buffer */
if (buffer_add_buffer(sigbuf, buf) < 0) {
buffer_free(sigbuf);
return NULL;
}
/* create signature */
signature = agent_sign_data(session, sigbuf, publickey);
buffer_free(sigbuf);
return signature;
}
#endif /* _WIN32 */
/*
* This function concats in a buffer the values needed to do a signature
* verification. */
ssh_buffer ssh_userauth_build_digest(ssh_session session, ssh_message msg, char *service) {
/*
The value of 'signature' is a signature by the corresponding private
key over the following data, in the following order:
string session identifier
byte SSH_MSG_USERAUTH_REQUEST
string user name
string service name
string "publickey"
boolean TRUE
string public key algorithm name
string public key to be used for authentication
*/
struct ssh_crypto_struct *crypto = session->current_crypto ? session->current_crypto :
session->next_crypto;
ssh_buffer buffer = NULL;
ssh_string session_id = NULL;
uint8_t type = SSH2_MSG_USERAUTH_REQUEST;
ssh_string username = string_from_char(msg->auth_request.username);
ssh_string servicename = string_from_char(service);
ssh_string method = string_from_char("publickey");
uint8_t has_sign = 1;
ssh_string algo = string_from_char(msg->auth_request.public_key->type_c);
ssh_string publickey = publickey_to_string(msg->auth_request.public_key);
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
session_id = string_new(SHA_DIGEST_LEN);
if (session_id == NULL) {
buffer_free(buffer);
buffer = NULL;
goto error;
}
string_fill(session_id, crypto->session_id, SHA_DIGEST_LEN);
if(buffer_add_ssh_string(buffer, session_id) < 0 ||
buffer_add_u8(buffer, type) < 0 ||
buffer_add_ssh_string(buffer, username) < 0 ||
buffer_add_ssh_string(buffer, servicename) < 0 ||
buffer_add_ssh_string(buffer, method) < 0 ||
buffer_add_u8(buffer, has_sign) < 0 ||
buffer_add_ssh_string(buffer, algo) < 0 ||
buffer_add_ssh_string(buffer, publickey) < 0) {
buffer_free(buffer);
buffer = NULL;
goto error;
}
error:
if(session_id) string_free(session_id);
if(username) string_free(username);
if(servicename) string_free(servicename);
if(method) string_free(method);
if(algo) string_free(algo);
if(publickey) string_free(publickey);
return buffer;
}
/*
* This function signs the session id (known as H) as a string then
* the content of sigbuf */
ssh_string ssh_do_sign(ssh_session session, ssh_buffer sigbuf,
ssh_private_key privatekey) {
struct ssh_crypto_struct *crypto = session->current_crypto ? session->current_crypto :
session->next_crypto;
unsigned char hash[SHA_DIGEST_LEN + 1] = {0};
ssh_string session_str = NULL;
ssh_string signature = NULL;
SIGNATURE *sign = NULL;
SHACTX ctx = NULL;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t gcryhash;
#endif
session_str = string_new(SHA_DIGEST_LEN);
if (session_str == NULL) {
return NULL;
}
string_fill(session_str, crypto->session_id, SHA_DIGEST_LEN);
ctx = sha1_init();
if (ctx == NULL) {
string_free(session_str);
return NULL;
}
sha1_update(ctx, session_str, string_len(session_str) + 4);
string_free(session_str);
sha1_update(ctx, buffer_get(sigbuf), buffer_get_len(sigbuf));
sha1_final(hash + 1,ctx);
hash[0] = 0;
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Hash being signed with dsa", hash + 1, SHA_DIGEST_LEN);
#endif
sign = malloc(sizeof(SIGNATURE));
if (sign == NULL) {
return NULL;
}
switch(privatekey->type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
if (gcry_sexp_build(&gcryhash, NULL, "%b", SHA_DIGEST_LEN + 1, hash) ||
gcry_pk_sign(&sign->dsa_sign, gcryhash, privatekey->dsa_priv)) {
ssh_set_error(session, SSH_FATAL, "Signing: libcrypt error");
gcry_sexp_release(gcryhash);
signature_free(sign);
return NULL;
}
#elif defined HAVE_LIBCRYPTO
sign->dsa_sign = DSA_do_sign(hash + 1, SHA_DIGEST_LEN,
privatekey->dsa_priv);
if (sign->dsa_sign == NULL) {
ssh_set_error(session, SSH_FATAL, "Signing: openssl error");
signature_free(sign);
return NULL;
}
#ifdef DEBUG_CRYPTO
ssh_print_bignum("r", sign->dsa_sign->r);
ssh_print_bignum("s", sign->dsa_sign->s);
#endif
#endif /* HAVE_LIBCRYPTO */
sign->rsa_sign = NULL;
break;
case TYPE_RSA:
#ifdef HAVE_LIBGCRYPT
if (gcry_sexp_build(&gcryhash, NULL, "(data(flags pkcs1)(hash sha1 %b))",
SHA_DIGEST_LEN, hash + 1) ||
gcry_pk_sign(&sign->rsa_sign, gcryhash, privatekey->rsa_priv)) {
ssh_set_error(session, SSH_FATAL, "Signing: libcrypt error");
gcry_sexp_release(gcryhash);
signature_free(sign);
return NULL;
}
#elif defined HAVE_LIBCRYPTO
sign->rsa_sign = RSA_do_sign(hash + 1, SHA_DIGEST_LEN,
privatekey->rsa_priv);
if (sign->rsa_sign == NULL) {
ssh_set_error(session, SSH_FATAL, "Signing: openssl error");
signature_free(sign);
return NULL;
}
#endif
sign->dsa_sign = NULL;
break;
}
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(gcryhash);
#endif
sign->type = privatekey->type;
signature = signature_to_string(sign);
signature_free(sign);
return signature;
}
ssh_string ssh_encrypt_rsa1(ssh_session session, ssh_string data, ssh_public_key key) {
ssh_string str = NULL;
size_t len = string_len(data);
size_t size = 0;
#ifdef HAVE_LIBGCRYPT
const char *tmp = NULL;
gcry_sexp_t ret_sexp;
gcry_sexp_t data_sexp;
if (gcry_sexp_build(&data_sexp, NULL, "(data(flags pkcs1)(value %b))",
len, string_data(data))) {
ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
return NULL;
}
if (gcry_pk_encrypt(&ret_sexp, data_sexp, key->rsa_pub)) {
gcry_sexp_release(data_sexp);
ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
return NULL;
}
gcry_sexp_release(data_sexp);
data_sexp = gcry_sexp_find_token(ret_sexp, "a", 0);
if (data_sexp == NULL) {
ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
gcry_sexp_release(ret_sexp);
return NULL;
}
tmp = gcry_sexp_nth_data(data_sexp, 1, &size);
if (*tmp == 0) {
size--;
tmp++;
}
str = string_new(size);
if (str == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
gcry_sexp_release(data_sexp);
gcry_sexp_release(ret_sexp);
return NULL;
}
string_fill(str, tmp, size);
gcry_sexp_release(data_sexp);
gcry_sexp_release(ret_sexp);
#elif defined HAVE_LIBCRYPTO
size = RSA_size(key->rsa_pub);
str = string_new(size);
if (str == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
return NULL;
}
if (RSA_public_encrypt(len, string_data(data), string_data(str), key->rsa_pub,
RSA_PKCS1_PADDING) < 0) {
string_free(str);
return NULL;
}
#endif
return str;
}
/* this function signs the session id */
ssh_string ssh_sign_session_id(ssh_session session, ssh_private_key privatekey) {
struct ssh_crypto_struct *crypto=session->current_crypto ? session->current_crypto :
session->next_crypto;
unsigned char hash[SHA_DIGEST_LEN + 1] = {0};
ssh_string signature = NULL;
SIGNATURE *sign = NULL;
SHACTX ctx = NULL;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t data_sexp;
#endif
ctx = sha1_init();
if (ctx == NULL) {
return NULL;
}
sha1_update(ctx,crypto->session_id,SHA_DIGEST_LEN);
sha1_final(hash + 1,ctx);
hash[0] = 0;
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Hash being signed with dsa",hash+1,SHA_DIGEST_LEN);
#endif
sign = malloc(sizeof(SIGNATURE));
if (sign == NULL) {
return NULL;
}
switch(privatekey->type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
if (gcry_sexp_build(&data_sexp, NULL, "%b", SHA_DIGEST_LEN + 1, hash) ||
gcry_pk_sign(&sign->dsa_sign, data_sexp, privatekey->dsa_priv)) {
ssh_set_error(session, SSH_FATAL, "Signing: libgcrypt error");
gcry_sexp_release(data_sexp);
signature_free(sign);
return NULL;
}
#elif defined HAVE_LIBCRYPTO
sign->dsa_sign = DSA_do_sign(hash + 1, SHA_DIGEST_LEN,
privatekey->dsa_priv);
if (sign->dsa_sign == NULL) {
ssh_set_error(session, SSH_FATAL, "Signing: openssl error");
signature_free(sign);
return NULL;
}
#ifdef DEBUG_CRYPTO
ssh_print_bignum("r",sign->dsa_sign->r);
ssh_print_bignum("s",sign->dsa_sign->s);
#endif
#endif /* HAVE_LIBCRYPTO */
sign->rsa_sign = NULL;
break;
case TYPE_RSA:
#ifdef HAVE_LIBGCRYPT
if (gcry_sexp_build(&data_sexp, NULL, "(data(flags pkcs1)(hash sha1 %b))",
SHA_DIGEST_LEN, hash + 1) ||
gcry_pk_sign(&sign->rsa_sign, data_sexp, privatekey->rsa_priv)) {
ssh_set_error(session, SSH_FATAL, "Signing: libgcrypt error");
gcry_sexp_release(data_sexp);
signature_free(sign);
return NULL;
}
#elif defined HAVE_LIBCRYPTO
sign->rsa_sign = RSA_do_sign(hash + 1, SHA_DIGEST_LEN,
privatekey->rsa_priv);
if (sign->rsa_sign == NULL) {
ssh_set_error(session, SSH_FATAL, "Signing: openssl error");
signature_free(sign);
return NULL;
}
#endif
sign->dsa_sign = NULL;
break;
}
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(data_sexp);
#endif
sign->type = privatekey->type;
signature = signature_to_string(sign);
signature_free(sign);
return signature;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/keys.c
|
C
|
gpl3
| 36,197
|
/*
* channels1.c - Support for SSH-1 type channels
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/ssh1.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#ifdef WITH_SSH1
/*
* This is a big hack. In fact, SSH1 doesn't make a clever use of channels.
* The whole packets concerning shells are sent outside of a channel.
* Thus, an inside limitation of this behaviour is that you can't only
* request one shell.
* The question is stil how they managed to imbed two "channel" into one
* protocol.
*/
int channel_open_session1(ssh_channel chan) {
/*
* We guess we are requesting an *exec* channel. It can only have one exec
* channel. So we abort with an error if we need more than one.
*/
ssh_session session = chan->session;
if (session->exec_channel_opened) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"SSH1 supports only one execution channel. "
"One has already been opened");
return -1;
}
session->exec_channel_opened = 1;
chan->open = 1;
chan->local_maxpacket = 32000;
chan->local_window = 64000;
ssh_log(session, SSH_LOG_PACKET, "Opened a SSH1 channel session");
return 0;
}
/* 10 SSH_CMSG_REQUEST_PTY
*
* string TERM environment variable value (e.g. vt100)
* 32-bit int terminal height, rows (e.g., 24)
* 32-bit int terminal width, columns (e.g., 80)
* 32-bit int terminal width, pixels (0 if no graphics) (e.g., 480)
* 32-bit int terminal height, pixels (0 if no graphics) (e.g., 640)
* n bytes tty modes encoded in binary
* Some day, someone should have a look at that nasty tty encoded. It's
* much simplier under ssh2. I just hope the defaults values are ok ...
*/
int channel_request_pty_size1(ssh_channel channel, const char *terminal, int col,
int row) {
ssh_session session = channel->session;
ssh_string str = NULL;
str = string_from_char(terminal);
if (str == NULL) {
return -1;
}
if (buffer_add_u8(session->out_buffer, SSH_CMSG_REQUEST_PTY) < 0 ||
buffer_add_ssh_string(session->out_buffer, str) < 0) {
string_free(str);
return -1;
}
string_free(str);
if (buffer_add_u32(session->out_buffer, ntohl(row)) < 0 ||
buffer_add_u32(session->out_buffer, ntohl(col)) < 0 ||
buffer_add_u32(session->out_buffer, 0) < 0 || /* x */
buffer_add_u32(session->out_buffer, 0) < 0 || /* y */
buffer_add_u8(session->out_buffer, 0) < 0) { /* tty things */
return -1;
}
ssh_log(session, SSH_LOG_FUNCTIONS, "Opening a ssh1 pty");
if (packet_send(session) != SSH_OK ||
packet_read(session) != SSH_OK ||
packet_translate(session) != SSH_OK) {
return -1;
}
switch (session->in_packet.type) {
case SSH_SMSG_SUCCESS:
ssh_log(session, SSH_LOG_RARE, "PTY: Success");
return 0;
break;
case SSH_SMSG_FAILURE:
ssh_set_error(session, SSH_REQUEST_DENIED,
"Server denied PTY allocation");
ssh_log(session, SSH_LOG_RARE, "PTY: denied\n");
break;
default:
ssh_log(session, SSH_LOG_RARE, "PTY: error\n");
ssh_set_error(session, SSH_FATAL,
"Received unexpected packet type %d",
session->in_packet.type);
return -1;
}
return -1;
}
int channel_change_pty_size1(ssh_channel channel, int cols, int rows) {
ssh_session session = channel->session;
if (buffer_add_u8(session->out_buffer, SSH_CMSG_WINDOW_SIZE) < 0 ||
buffer_add_u32(session->out_buffer, ntohl(rows)) < 0 ||
buffer_add_u32(session->out_buffer, ntohl(cols)) < 0 ||
buffer_add_u32(session->out_buffer, 0) < 0 ||
buffer_add_u32(session->out_buffer, 0) < 0) {
return -1;
}
if (packet_send(session)) {
return -1;
}
ssh_log(session, SSH_LOG_RARE, "Change pty size send");
if (packet_wait(session, SSH_SMSG_SUCCESS, 1) != SSH_OK) {
return -1;
}
switch (session->in_packet.type) {
case SSH_SMSG_SUCCESS:
ssh_log(session, SSH_LOG_RARE, "pty size changed");
return 0;
case SSH_SMSG_FAILURE:
ssh_log(session, SSH_LOG_RARE, "pty size change denied");
ssh_set_error(session, SSH_REQUEST_DENIED, "pty size change denied");
return -1;
}
ssh_set_error(session, SSH_FATAL, "Received unexpected packet type %d",
session->in_packet.type);
return -1;
}
int channel_request_shell1(ssh_channel channel) {
ssh_session session = channel->session;
if (buffer_add_u8(session->out_buffer,SSH_CMSG_EXEC_SHELL) < 0) {
return -1;
}
if (packet_send(session) != SSH_OK) {
return -1;
}
ssh_log(session, SSH_LOG_RARE, "Launched a shell");
return 0;
}
int channel_request_exec1(ssh_channel channel, const char *cmd) {
ssh_session session = channel->session;
ssh_string command = NULL;
command = string_from_char(cmd);
if (command == NULL) {
return -1;
}
if (buffer_add_u8(session->out_buffer, SSH_CMSG_EXEC_CMD) < 0 ||
buffer_add_ssh_string(session->out_buffer, command) < 0) {
string_free(command);
return -1;
}
string_free(command);
if(packet_send(session) != SSH_OK) {
return -1;
}
ssh_log(session, SSH_LOG_RARE, "Executing %s ...", cmd);
return 0;
}
static int channel_rcv_data1(ssh_session session, int is_stderr) {
ssh_channel channel = session->channels;
ssh_string str = NULL;
str = buffer_get_ssh_string(session->in_buffer);
if (str == NULL) {
ssh_log(session, SSH_LOG_FUNCTIONS, "Invalid data packet !\n");
return -1;
}
ssh_log(session, SSH_LOG_RARE,
"Adding %zu bytes data in %d",
string_len(str), is_stderr);
if (channel_default_bufferize(channel, string_data(str), string_len(str),
is_stderr) < 0) {
string_free(str);
return -1;
}
string_free(str);
return 0;
}
static int channel_rcv_close1(ssh_session session) {
ssh_channel channel = session->channels;
uint32_t status;
buffer_get_u32(session->in_buffer, &status);
/*
* It's much more than a channel closing. spec says it's the last
* message sent by server (strange)
*/
/* actually status is lost somewhere */
channel->open = 0;
channel->remote_eof = 1;
if (buffer_add_u8(session->out_buffer, SSH_CMSG_EXIT_CONFIRMATION) < 0) {
return -1;
}
if (packet_send(session) != SSH_OK) {
return -1;
}
return 0;
}
int channel_handle1(ssh_session session, int type) {
ssh_log(session, SSH_LOG_RARE, "Channel_handle1(%d)", type);
switch (type) {
case SSH_SMSG_STDOUT_DATA:
if (channel_rcv_data1(session,0) < 0) {
return -1;
}
break;
case SSH_SMSG_STDERR_DATA:
if (channel_rcv_data1(session,1) < 0) {
return -1;
}
break;
case SSH_SMSG_EXITSTATUS:
if (channel_rcv_close1(session) < 0) {
return -1;
}
break;
default:
ssh_log(session, SSH_LOG_FUNCTIONS, "Unexepected message %d", type);
}
return 0;
}
int channel_write1(ssh_channel channel, const void *data, int len) {
ssh_session session = channel->session;
int origlen = len;
int effectivelen;
const unsigned char *ptr=data;
while (len > 0) {
if (buffer_add_u8(session->out_buffer, SSH_CMSG_STDIN_DATA) < 0) {
return -1;
}
effectivelen = len > 32000 ? 32000 : len;
if (buffer_add_u32(session->out_buffer, htonl(effectivelen)) < 0 ||
buffer_add_data(session->out_buffer, ptr, effectivelen) < 0) {
return -1;
}
ptr += effectivelen;
len -= effectivelen;
if (packet_send(session) != SSH_OK) {
return -1;
}
}
return origlen;
}
#endif /* WITH_SSH1 */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/channels1.c
|
C
|
gpl3
| 8,740
|
/*
* keyfiles.c - private and public key handling for authentication.
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/buffer.h"
#include "libssh/keyfiles.h"
#include "libssh/session.h"
#include "libssh/wrapper.h"
#include "libssh/misc.h"
#include "libssh/keys.h"
/*todo: remove this include */
#include "libssh/string.h"
#ifdef HAVE_LIBGCRYPT
#include <gcrypt.h>
#elif defined HAVE_LIBCRYPTO
#include <openssl/pem.h>
#include <openssl/dsa.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
#endif /* HAVE_LIBCRYPTO */
#define MAXLINESIZE 80
#define RSA_HEADER_BEGIN "-----BEGIN RSA PRIVATE KEY-----"
#define RSA_HEADER_END "-----END RSA PRIVATE KEY-----"
#define DSA_HEADER_BEGIN "-----BEGIN DSA PRIVATE KEY-----"
#define DSA_HEADER_END "-----END DSA PRIVATE KEY-----"
#ifdef HAVE_LIBGCRYPT
#define MAX_KEY_SIZE 32
#define MAX_PASSPHRASE_SIZE 1024
#define ASN1_INTEGER 2
#define ASN1_SEQUENCE 48
#define PKCS5_SALT_LEN 8
static int load_iv(char *header, unsigned char *iv, int iv_len) {
int i;
int j;
int k;
memset(iv, 0, iv_len);
for (i = 0; i < iv_len; i++) {
if ((header[2*i] >= '0') && (header[2*i] <= '9'))
j = header[2*i] - '0';
else if ((header[2*i] >= 'A') && (header[2*i] <= 'F'))
j = header[2*i] - 'A' + 10;
else if ((header[2*i] >= 'a') && (header[2*i] <= 'f'))
j = header[2*i] - 'a' + 10;
else
return -1;
if ((header[2*i+1] >= '0') && (header[2*i+1] <= '9'))
k = header[2*i+1] - '0';
else if ((header[2*i+1] >= 'A') && (header[2*i+1] <= 'F'))
k = header[2*i+1] - 'A' + 10;
else if ((header[2*i+1] >= 'a') && (header[2*i+1] <= 'f'))
k = header[2*i+1] - 'a' + 10;
else
return -1;
iv[i] = (j << 4) + k;
}
return 0;
}
static uint32_t char_to_u32(unsigned char *data, uint32_t size) {
uint32_t ret;
uint32_t i;
for (i = 0, ret = 0; i < size; ret = ret << 8, ret += data[i++])
;
return ret;
}
static uint32_t asn1_get_len(ssh_buffer buffer) {
uint32_t len;
unsigned char tmp[4];
if (buffer_get_data(buffer,tmp,1) == 0) {
return 0;
}
if (tmp[0] > 127) {
len = tmp[0] & 127;
if (len > 4) {
return 0; /* Length doesn't fit in u32. Can this really happen? */
}
if (buffer_get_data(buffer,tmp,len) == 0) {
return 0;
}
len = char_to_u32(tmp, len);
} else {
len = char_to_u32(tmp, 1);
}
return len;
}
static ssh_string asn1_get_int(ssh_buffer buffer) {
ssh_string str;
unsigned char type;
uint32_t size;
if (buffer_get_data(buffer, &type, 1) == 0 || type != ASN1_INTEGER) {
return NULL;
}
size = asn1_get_len(buffer);
if (size == 0) {
return NULL;
}
str = string_new(size);
if (str == NULL) {
return NULL;
}
if (buffer_get_data(buffer, str->string, size) == 0) {
string_free(str);
return NULL;
}
return str;
}
static int asn1_check_sequence(ssh_buffer buffer) {
unsigned char *j = NULL;
unsigned char tmp;
int i;
uint32_t size;
uint32_t padding;
if (buffer_get_data(buffer, &tmp, 1) == 0 || tmp != ASN1_SEQUENCE) {
return 0;
}
size = asn1_get_len(buffer);
if ((padding = buffer_get_len(buffer) - buffer->pos - size) > 0) {
for (i = buffer_get_len(buffer) - buffer->pos - size,
j = (unsigned char*)buffer_get(buffer) + size + buffer->pos;
i;
i--, j++)
{
if (*j != padding) { /* padding is allowed */
return 0; /* but nothing else */
}
}
}
return 1;
}
static int read_line(char *data, unsigned int len, FILE *fp) {
char tmp;
unsigned int i;
for (i = 0; fread(&tmp, 1, 1, fp) && tmp != '\n' && i < len; data[i++] = tmp)
;
if (tmp == '\n') {
return i;
}
if (i >= len) {
return -1;
}
return 0;
}
static int passphrase_to_key(char *data, unsigned int datalen,
unsigned char *salt, unsigned char *key, unsigned int keylen) {
MD5CTX md;
unsigned char digest[MD5_DIGEST_LEN] = {0};
unsigned int i;
unsigned int j;
unsigned int md_not_empty;
for (j = 0, md_not_empty = 0; j < keylen; ) {
md = md5_init();
if (md == NULL) {
return -1;
}
if (md_not_empty) {
md5_update(md, digest, MD5_DIGEST_LEN);
} else {
md_not_empty = 1;
}
md5_update(md, data, datalen);
if (salt) {
md5_update(md, salt, PKCS5_SALT_LEN);
}
md5_final(digest, md);
for (i = 0; j < keylen && i < MD5_DIGEST_LEN; j++, i++) {
if (key) {
key[j] = digest[i];
}
}
}
return 0;
}
static int privatekey_decrypt(int algo, int mode, unsigned int key_len,
unsigned char *iv, unsigned int iv_len,
ssh_buffer data, ssh_auth_callback cb,
void *userdata,
const char *desc)
{
char passphrase[MAX_PASSPHRASE_SIZE] = {0};
unsigned char key[MAX_KEY_SIZE] = {0};
unsigned char *tmp = NULL;
gcry_cipher_hd_t cipher;
int rc = -1;
if (!algo) {
return -1;
}
if (cb) {
rc = (*cb)(desc, passphrase, MAX_PASSPHRASE_SIZE, 0, 0, userdata);
if (rc < 0) {
return -1;
}
} else if (cb == NULL && userdata != NULL) {
snprintf(passphrase, MAX_PASSPHRASE_SIZE, "%s", (char *) userdata);
}
if (passphrase_to_key(passphrase, strlen(passphrase), iv, key, key_len) < 0) {
return -1;
}
if (gcry_cipher_open(&cipher, algo, mode, 0)
|| gcry_cipher_setkey(cipher, key, key_len)
|| gcry_cipher_setiv(cipher, iv, iv_len)
|| (tmp = malloc(buffer_get_len(data) * sizeof (char))) == NULL
|| gcry_cipher_decrypt(cipher, tmp, buffer_get_len(data),
buffer_get(data), buffer_get_len(data))) {
gcry_cipher_close(cipher);
return -1;
}
memcpy(buffer_get(data), tmp, buffer_get_len(data));
SAFE_FREE(tmp);
gcry_cipher_close(cipher);
return 0;
}
static int privatekey_dek_header(char *header, unsigned int header_len,
int *algo, int *mode, unsigned int *key_len, unsigned char **iv,
unsigned int *iv_len) {
unsigned int iv_pos;
if (header_len > 13 && !strncmp("DES-EDE3-CBC", header, 12))
{
*algo = GCRY_CIPHER_3DES;
iv_pos = 13;
*mode = GCRY_CIPHER_MODE_CBC;
*key_len = 24;
*iv_len = 8;
}
else if (header_len > 8 && !strncmp("DES-CBC", header, 7))
{
*algo = GCRY_CIPHER_DES;
iv_pos = 8;
*mode = GCRY_CIPHER_MODE_CBC;
*key_len = 8;
*iv_len = 8;
}
else if (header_len > 12 && !strncmp("AES-128-CBC", header, 11))
{
*algo = GCRY_CIPHER_AES128;
iv_pos = 12;
*mode = GCRY_CIPHER_MODE_CBC;
*key_len = 16;
*iv_len = 16;
}
else if (header_len > 12 && !strncmp("AES-192-CBC", header, 11))
{
*algo = GCRY_CIPHER_AES192;
iv_pos = 12;
*mode = GCRY_CIPHER_MODE_CBC;
*key_len = 24;
*iv_len = 16;
}
else if (header_len > 12 && !strncmp("AES-256-CBC", header, 11))
{
*algo = GCRY_CIPHER_AES256;
iv_pos = 12;
*mode = GCRY_CIPHER_MODE_CBC;
*key_len = 32;
*iv_len = 16;
} else {
return -1;
}
*iv = malloc(*iv_len);
if (*iv == NULL) {
return -1;
}
return load_iv(header + iv_pos, *iv, *iv_len);
}
static ssh_buffer privatekey_file_to_buffer(FILE *fp, int type,
ssh_auth_callback cb, void *userdata, const char *desc) {
ssh_buffer buffer = NULL;
ssh_buffer out = NULL;
char buf[MAXLINESIZE] = {0};
unsigned char *iv = NULL;
const char *header_begin;
const char *header_end;
unsigned int header_begin_size;
unsigned int header_end_size;
unsigned int key_len = 0;
unsigned int iv_len = 0;
int algo = 0;
int mode = 0;
int len;
buffer = buffer_new();
if (buffer == NULL) {
return NULL;
}
switch(type) {
case TYPE_DSS:
header_begin = DSA_HEADER_BEGIN;
header_end = DSA_HEADER_END;
break;
case TYPE_RSA:
header_begin = RSA_HEADER_BEGIN;
header_end = RSA_HEADER_END;
break;
default:
buffer_free(buffer);
return NULL;
}
header_begin_size = strlen(header_begin);
header_end_size = strlen(header_end);
while (read_line(buf, MAXLINESIZE, fp) &&
strncmp(buf, header_begin, header_begin_size))
;
len = read_line(buf, MAXLINESIZE, fp);
if (len > 11 && strncmp("Proc-Type: 4,ENCRYPTED", buf, 11) == 0) {
len = read_line(buf, MAXLINESIZE, fp);
if (len > 10 && strncmp("DEK-Info: ", buf, 10) == 0) {
if ((privatekey_dek_header(buf + 10, len - 10, &algo, &mode, &key_len,
&iv, &iv_len) < 0)
|| read_line(buf, MAXLINESIZE, fp)) {
buffer_free(buffer);
SAFE_FREE(iv);
return NULL;
}
} else {
buffer_free(buffer);
SAFE_FREE(iv);
return NULL;
}
} else {
if (buffer_add_data(buffer, buf, len) < 0) {
buffer_free(buffer);
SAFE_FREE(iv);
return NULL;
}
}
while ((len = read_line(buf,MAXLINESIZE,fp)) &&
strncmp(buf, header_end, header_end_size) != 0) {
if (len == -1) {
buffer_free(buffer);
SAFE_FREE(iv);
return NULL;
}
if (buffer_add_data(buffer, buf, len) < 0) {
buffer_free(buffer);
SAFE_FREE(iv);
return NULL;
}
}
if (strncmp(buf,header_end,header_end_size) != 0) {
buffer_free(buffer);
SAFE_FREE(iv);
return NULL;
}
if (buffer_add_data(buffer, "\0", 1) < 0) {
buffer_free(buffer);
SAFE_FREE(iv);
return NULL;
}
out = base64_to_bin(buffer_get(buffer));
buffer_free(buffer);
if (out == NULL) {
SAFE_FREE(iv);
return NULL;
}
if (algo) {
if (privatekey_decrypt(algo, mode, key_len, iv, iv_len, out,
cb, userdata, desc) < 0) {
buffer_free(out);
SAFE_FREE(iv);
return NULL;
}
}
SAFE_FREE(iv);
return out;
}
static int read_rsa_privatekey(FILE *fp, gcry_sexp_t *r,
ssh_auth_callback cb, void *userdata, const char *desc) {
ssh_string n = NULL;
ssh_string e = NULL;
ssh_string d = NULL;
ssh_string p = NULL;
ssh_string q = NULL;
ssh_string unused1 = NULL;
ssh_string unused2 = NULL;
ssh_string u = NULL;
ssh_string v = NULL;
ssh_buffer buffer = NULL;
int rc = 1;
buffer = privatekey_file_to_buffer(fp, TYPE_RSA, cb, userdata, desc);
if (buffer == NULL) {
return 0;
}
if (!asn1_check_sequence(buffer)) {
buffer_free(buffer);
return 0;
}
v = asn1_get_int(buffer);
if (ntohl(v->size) != 1 || v->string[0] != 0) {
buffer_free(buffer);
return 0;
}
n = asn1_get_int(buffer);
e = asn1_get_int(buffer);
d = asn1_get_int(buffer);
q = asn1_get_int(buffer);
p = asn1_get_int(buffer);
unused1 = asn1_get_int(buffer);
unused2 = asn1_get_int(buffer);
u = asn1_get_int(buffer);
buffer_free(buffer);
if (n == NULL || e == NULL || d == NULL || p == NULL || q == NULL ||
unused1 == NULL || unused2 == NULL|| u == NULL) {
rc = 0;
goto error;
}
if (gcry_sexp_build(r, NULL,
"(private-key(rsa(n %b)(e %b)(d %b)(p %b)(q %b)(u %b)))",
ntohl(n->size), n->string,
ntohl(e->size), e->string,
ntohl(d->size), d->string,
ntohl(p->size), p->string,
ntohl(q->size), q->string,
ntohl(u->size), u->string)) {
rc = 0;
}
error:
string_free(n);
string_free(e);
string_free(d);
string_free(p);
string_free(q);
string_free(unused1);
string_free(unused2);
string_free(u);
string_free(v);
return rc;
}
static int read_dsa_privatekey(FILE *fp, gcry_sexp_t *r, ssh_auth_callback cb,
void *userdata, const char *desc) {
ssh_buffer buffer = NULL;
ssh_string p = NULL;
ssh_string q = NULL;
ssh_string g = NULL;
ssh_string y = NULL;
ssh_string x = NULL;
ssh_string v = NULL;
int rc = 1;
buffer = privatekey_file_to_buffer(fp, TYPE_DSS, cb, userdata, desc);
if (buffer == NULL) {
return 0;
}
if (!asn1_check_sequence(buffer)) {
buffer_free(buffer);
return 0;
}
v = asn1_get_int(buffer);
if (ntohl(v->size) != 1 || v->string[0] != 0) {
buffer_free(buffer);
return 0;
}
p = asn1_get_int(buffer);
q = asn1_get_int(buffer);
g = asn1_get_int(buffer);
y = asn1_get_int(buffer);
x = asn1_get_int(buffer);
buffer_free(buffer);
if (p == NULL || q == NULL || g == NULL || y == NULL || x == NULL) {
rc = 0;
goto error;
}
if (gcry_sexp_build(r, NULL,
"(private-key(dsa(p %b)(q %b)(g %b)(y %b)(x %b)))",
ntohl(p->size), p->string,
ntohl(q->size), q->string,
ntohl(g->size), g->string,
ntohl(y->size), y->string,
ntohl(x->size), x->string)) {
rc = 0;
}
error:
string_free(p);
string_free(q);
string_free(g);
string_free(y);
string_free(x);
string_free(v);
return rc;
}
#endif /* HAVE_LIBGCRYPT */
#ifdef HAVE_LIBCRYPTO
static int pem_get_password(char *buf, int size, int rwflag, void *userdata) {
ssh_session session = userdata;
/* unused flag */
(void) rwflag;
ZERO_STRUCTP(buf);
ssh_log(session, SSH_LOG_RARE,
"Trying to call external authentication function");
if (session && session->callbacks->auth_function) {
if (session->callbacks->auth_function("Passphrase for private key:", buf, size, 0, 0,
session->callbacks->userdata) < 0) {
return 0;
}
return strlen(buf);
}
return 0;
}
#endif /* HAVE_LIBCRYPTO */
static int privatekey_type_from_file(FILE *fp) {
char buffer[MAXLINESIZE] = {0};
if (!fgets(buffer, MAXLINESIZE, fp)) {
return 0;
}
fseek(fp, 0, SEEK_SET);
if (strncmp(buffer, DSA_HEADER_BEGIN, strlen(DSA_HEADER_BEGIN)) == 0) {
return TYPE_DSS;
}
if (strncmp(buffer, RSA_HEADER_BEGIN, strlen(RSA_HEADER_BEGIN)) == 0) {
return TYPE_RSA;
}
return 0;
}
/** \addtogroup ssh_auth
* @{
*/
/* TODO : implement it to read both DSA and RSA at once */
/** \brief Reads a SSH private key from a file
* \param session SSH Session
* \param filename Filename containing the private key
* \param type Type of the private key. One of TYPE_DSS or TYPE_RSA. Pass 0 to automatically detect the type.
* \param passphrase Passphrase to decrypt the private key. Set to null if none is needed or it is unknown.
* \returns a PRIVATE_KEY object containing the private key, or NULL if it failed.
* \see privatekey_free()
* \see publickey_from_privatekey()
*/
ssh_private_key privatekey_from_file(ssh_session session, const char *filename,
int type, const char *passphrase) {
ssh_auth_callback auth_cb = NULL;
ssh_private_key privkey = NULL;
void *auth_ud = NULL;
FILE *file = NULL;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t dsa = NULL;
gcry_sexp_t rsa = NULL;
int valid;
#elif defined HAVE_LIBCRYPTO
DSA *dsa = NULL;
RSA *rsa = NULL;
#endif
ssh_log(session, SSH_LOG_RARE, "Trying to open %s", filename);
file = fopen(filename,"r");
if (file == NULL) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Error opening %s: %s", filename, strerror(errno));
return NULL;
}
ssh_log(session, SSH_LOG_RARE, "Trying to read %s, passphase=%s, authcb=%s",
filename, passphrase ? "true" : "false",
session->callbacks && session->callbacks->auth_function ? "true" : "false");
if (type == 0) {
type = privatekey_type_from_file(file);
if (type == 0) {
fclose(file);
ssh_set_error(session, SSH_FATAL, "Invalid private key file.");
return NULL;
}
}
switch (type) {
case TYPE_DSS:
if (passphrase == NULL) {
if (session->callbacks && session->callbacks->auth_function) {
auth_cb = session->callbacks->auth_function;
auth_ud = session->callbacks->userdata;
#ifdef HAVE_LIBGCRYPT
valid = read_dsa_privatekey(file, &dsa, auth_cb, auth_ud,
"Passphrase for private key:");
} else { /* authcb */
valid = read_dsa_privatekey(file, &dsa, NULL, NULL, NULL);
} /* authcb */
} else { /* passphrase */
valid = read_dsa_privatekey(file, &dsa, NULL,
(void *) passphrase, NULL);
}
fclose(file);
if (!valid) {
ssh_set_error(session, SSH_FATAL, "Parsing private key %s", filename);
#elif defined HAVE_LIBCRYPTO
dsa = PEM_read_DSAPrivateKey(file, NULL, pem_get_password, session);
} else { /* authcb */
/* openssl uses it's own callback to get the passphrase here */
dsa = PEM_read_DSAPrivateKey(file, NULL, NULL, NULL);
} /* authcb */
} else { /* passphrase */
dsa = PEM_read_DSAPrivateKey(file, NULL, NULL, (void *) passphrase);
}
fclose(file);
if (dsa == NULL) {
ssh_set_error(session, SSH_FATAL,
"Parsing private key %s: %s",
filename, ERR_error_string(ERR_get_error(), NULL));
#endif
return NULL;
}
break;
case TYPE_RSA:
if (passphrase == NULL) {
if (session->callbacks && session->callbacks->auth_function) {
auth_cb = session->callbacks->auth_function;
auth_ud = session->callbacks->userdata;
#ifdef HAVE_LIBGCRYPT
valid = read_rsa_privatekey(file, &rsa, auth_cb, auth_ud,
"Passphrase for private key:");
} else { /* authcb */
valid = read_rsa_privatekey(file, &rsa, NULL, NULL, NULL);
} /* authcb */
} else { /* passphrase */
valid = read_rsa_privatekey(file, &rsa, NULL,
(void *) passphrase, NULL);
}
fclose(file);
if (!valid) {
ssh_set_error(session,SSH_FATAL, "Parsing private key %s", filename);
#elif defined HAVE_LIBCRYPTO
rsa = PEM_read_RSAPrivateKey(file, NULL, pem_get_password, session);
} else { /* authcb */
/* openssl uses it's own callback to get the passphrase here */
rsa = PEM_read_RSAPrivateKey(file, NULL, NULL, NULL);
} /* authcb */
} else { /* passphrase */
rsa = PEM_read_RSAPrivateKey(file, NULL, NULL, (void *) passphrase);
}
fclose(file);
if (rsa == NULL) {
ssh_set_error(session, SSH_FATAL,
"Parsing private key %s: %s",
filename, ERR_error_string(ERR_get_error(),NULL));
#endif
return NULL;
}
break;
default:
fclose(file);
ssh_set_error(session, SSH_FATAL, "Invalid private key type %d", type);
return NULL;
} /* switch */
privkey = malloc(sizeof(struct ssh_private_key_struct));
if (privkey == NULL) {
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(dsa);
gcry_sexp_release(rsa);
#elif defined HAVE_LIBCRYPTO
DSA_free(dsa);
RSA_free(rsa);
#endif
return NULL;
}
privkey->type = type;
privkey->dsa_priv = dsa;
privkey->rsa_priv = rsa;
return privkey;
}
/**
* @brief returns the type of a private key
* @param privatekey[in] the private key handle
* @returns one of TYPE_RSA,TYPE_DSS,TYPE_RSA1
* @returns 0 if the type is unknown
* @see privatekey_from_file
* @see ssh_userauth_offer_pubkey
*/
int ssh_privatekey_type(ssh_private_key privatekey){
if (privatekey==NULL)
return 0;
return privatekey->type;
}
/* same that privatekey_from_file() but without any passphrase things. */
ssh_private_key _privatekey_from_file(void *session, const char *filename,
int type) {
ssh_private_key privkey = NULL;
FILE *file = NULL;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t dsa = NULL;
gcry_sexp_t rsa = NULL;
int valid;
#elif defined HAVE_LIBCRYPTO
DSA *dsa = NULL;
RSA *rsa = NULL;
#endif
file = fopen(filename,"r");
if (file == NULL) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Error opening %s: %s", filename, strerror(errno));
return NULL;
}
switch (type) {
case TYPE_DSS:
#ifdef HAVE_LIBGCRYPT
valid = read_dsa_privatekey(file, &dsa, NULL, NULL, NULL);
fclose(file);
if (!valid) {
ssh_set_error(session, SSH_FATAL, "Parsing private key %s", filename);
#elif defined HAVE_LIBCRYPTO
dsa = PEM_read_DSAPrivateKey(file, NULL, NULL, NULL);
fclose(file);
if (dsa == NULL) {
ssh_set_error(session, SSH_FATAL,
"Parsing private key %s: %s",
filename, ERR_error_string(ERR_get_error(), NULL));
#endif
return NULL;
}
break;
case TYPE_RSA:
#ifdef HAVE_LIBGCRYPT
valid = read_rsa_privatekey(file, &rsa, NULL, NULL, NULL);
fclose(file);
if (!valid) {
ssh_set_error(session, SSH_FATAL, "Parsing private key %s", filename);
#elif defined HAVE_LIBCRYPTO
rsa = PEM_read_RSAPrivateKey(file, NULL, NULL, NULL);
fclose(file);
if (rsa == NULL) {
ssh_set_error(session, SSH_FATAL,
"Parsing private key %s: %s",
filename, ERR_error_string(ERR_get_error(), NULL));
#endif
return NULL;
}
break;
default:
ssh_set_error(session, SSH_FATAL, "Invalid private key type %d", type);
return NULL;
}
privkey = malloc(sizeof(struct ssh_private_key_struct));
if (privkey == NULL) {
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(dsa);
gcry_sexp_release(rsa);
#elif defined HAVE_LIBCRYPTO
DSA_free(dsa);
RSA_free(rsa);
#endif
return NULL;
}
privkey->type = type;
privkey->dsa_priv = dsa;
privkey->rsa_priv = rsa;
return privkey;
}
/** \brief deallocate a private key
* \param prv a PRIVATE_KEY object
*/
void privatekey_free(ssh_private_key prv) {
if (prv == NULL) {
return;
}
#ifdef HAVE_LIBGCRYPT
gcry_sexp_release(prv->dsa_priv);
gcry_sexp_release(prv->rsa_priv);
#elif defined HAVE_LIBCRYPTO
DSA_free(prv->dsa_priv);
RSA_free(prv->rsa_priv);
#endif
memset(prv, 0, sizeof(struct ssh_private_key_struct));
SAFE_FREE(prv);
}
/**
* @brief Write a public key to a file.
*
* @param[in] session The ssh session to use.
*
* @param[in] file The filename to write the key into.
*
* @param[in] pubkey The public key to write.
*
* @param[in] type The type of the public key.
*
* @return 0 on success, -1 on error.
*/
int ssh_publickey_to_file(ssh_session session, const char *file,
ssh_string pubkey, int type) {
FILE *fp;
char *user;
char buffer[1024];
char host[256];
unsigned char *pubkey_64;
size_t len;
int rc;
pubkey_64 = bin_to_base64(pubkey->string, string_len(pubkey));
if (pubkey_64 == NULL) {
return -1;
}
user = ssh_get_local_username(session);
if (user == NULL) {
SAFE_FREE(pubkey_64);
return -1;
}
rc = gethostname(host, sizeof(host));
if (rc < 0) {
SAFE_FREE(user);
SAFE_FREE(pubkey_64);
return -1;
}
snprintf(buffer, sizeof(buffer), "%s %s %s@%s\n",
ssh_type_to_char(type),
pubkey_64,
user,
host);
SAFE_FREE(pubkey_64);
SAFE_FREE(user);
ssh_log(session, SSH_LOG_RARE, "Trying to write public key file: %s", file);
ssh_log(session, SSH_LOG_PACKET, "public key file content: %s", buffer);
fp = fopen(file, "w+");
if (fp == NULL) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Error opening %s: %s", file, strerror(errno));
return -1;
}
len = strlen(buffer);
if (fwrite(buffer, len, 1, fp) != 1 || ferror(fp)) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Unable to write to %s", file);
fclose(fp);
unlink(file);
return -1;
}
fclose(fp);
return 0;
}
/** \brief Retrieve a public key from a file
* \param session the SSH session
* \param filename Filename of the key
* \param type Pointer to a integer. If it is not null, it contains the type of the key after execution.
* \return a SSH String containing the public key, or NULL if it failed.
* \see string_free()
* \see publickey_from_privatekey()
*/
ssh_string publickey_from_file(ssh_session session, const char *filename,
int *type) {
ssh_buffer buffer = NULL;
char buf[4096] = {0};
ssh_string str = NULL;
char *ptr = NULL;
int key_type;
int fd = -1;
int r;
fd = open(filename, O_RDONLY);
if (fd < 0) {
ssh_set_error(session, SSH_REQUEST_DENIED, "Public key file doesn't exist");
return NULL;
}
if (read(fd, buf, 8) != 8) {
close(fd);
ssh_set_error(session, SSH_REQUEST_DENIED, "Invalid public key file");
return NULL;
}
buf[7] = '\0';
key_type = ssh_type_from_name(buf);
if (key_type == -1) {
close(fd);
ssh_set_error(session, SSH_REQUEST_DENIED, "Invalid public key file");
return NULL;
}
r = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (r <= 0) {
ssh_set_error(session, SSH_REQUEST_DENIED, "Invalid public key file");
return NULL;
}
buf[r] = 0;
ptr = strchr(buf, ' ');
/* eliminate the garbage at end of file */
if (ptr) {
*ptr = '\0';
}
buffer = base64_to_bin(buf);
if (buffer == NULL) {
ssh_set_error(session, SSH_REQUEST_DENIED, "Invalid public key file");
return NULL;
}
str = string_new(buffer_get_len(buffer));
if (str == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
buffer_free(buffer);
return NULL;
}
string_fill(str, buffer_get(buffer), buffer_get_len(buffer));
buffer_free(buffer);
if (type) {
*type = key_type;
}
return str;
}
/**
* @brief Try to read the public key from a given file.
*
* @param[in] session The ssh session to use.
*
* @param[in] keyfile The name of the private keyfile.
*
* @param[out] publickey A ssh_string to store the public key.
*
* @param[out] type A pointer to an integer to store the type.
*
* @return 0 on success, -1 on error or the private key doesn't
* exist, 1 if the public key doesn't exist.
*/
int ssh_try_publickey_from_file(ssh_session session, const char *keyfile,
ssh_string *publickey, int *type) {
char *pubkey_file;
size_t len;
ssh_string pubkey_string;
int pubkey_type;
if (session == NULL || keyfile == NULL || publickey == NULL || type == NULL) {
return -1;
}
if (session->sshdir == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_SSH_DIR, NULL) < 0) {
return -1;
}
}
ssh_log(session, SSH_LOG_PACKET, "Trying to open privatekey %s", keyfile);
if (!ssh_file_readaccess_ok(keyfile)) {
ssh_log(session, SSH_LOG_PACKET, "Failed to open privatekey %s", keyfile);
return -1;
}
len = strlen(keyfile) + 5;
pubkey_file = malloc(len);
if (pubkey_file == NULL) {
return -1;
}
snprintf(pubkey_file, len, "%s.pub", keyfile);
ssh_log(session, SSH_LOG_PACKET, "Trying to open publickey %s",
pubkey_file);
if (!ssh_file_readaccess_ok(pubkey_file)) {
ssh_log(session, SSH_LOG_PACKET, "Failed to open publickey %s",
pubkey_file);
SAFE_FREE(pubkey_file);
return 1;
}
ssh_log(session, SSH_LOG_PACKET, "Success opening public and private key");
/*
* We are sure both the private and public key file is readable. We return
* the public as a string, and the private filename as an argument
*/
pubkey_string = publickey_from_file(session, pubkey_file, &pubkey_type);
if (pubkey_string == NULL) {
ssh_log(session, SSH_LOG_PACKET,
"Wasn't able to open public key file %s: %s",
pubkey_file,
ssh_get_error(session));
SAFE_FREE(pubkey_file);
return -1;
}
SAFE_FREE(pubkey_file);
*publickey = pubkey_string;
*type = pubkey_type;
return 0;
}
ssh_string try_publickey_from_file(ssh_session session, struct ssh_keys_struct keytab,
char **privkeyfile, int *type) {
const char *priv;
const char *pub;
char *new;
ssh_string pubkey=NULL;
pub = keytab.publickey;
if (pub == NULL) {
return NULL;
}
priv = keytab.privatekey;
if (priv == NULL) {
return NULL;
}
if (session->sshdir == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_SSH_DIR, NULL) < 0) {
return NULL;
}
}
ssh_log(session, SSH_LOG_PACKET, "Trying to open publickey %s", pub);
if (!ssh_file_readaccess_ok(pub)) {
ssh_log(session, SSH_LOG_PACKET, "Failed to open publickey %s", pub);
goto error;
}
ssh_log(session, SSH_LOG_PACKET, "Trying to open privatekey %s", priv);
if (!ssh_file_readaccess_ok(priv)) {
ssh_log(session, SSH_LOG_PACKET, "Failed to open privatekey %s", priv);
goto error;
}
ssh_log(session, SSH_LOG_PACKET, "Success opening public and private key");
/*
* We are sure both the private and public key file is readable. We return
* the public as a string, and the private filename as an argument
*/
pubkey = publickey_from_file(session, pub, type);
if (pubkey == NULL) {
ssh_log(session, SSH_LOG_PACKET,
"Wasn't able to open public key file %s: %s",
pub,
ssh_get_error(session));
goto error;
}
new = realloc(*privkeyfile, strlen(priv) + 1);
if (new == NULL) {
string_free(pubkey);
goto error;
}
strcpy(new, priv);
*privkeyfile = new;
error:
return pubkey;
}
static int alldigits(const char *s) {
while (*s) {
if (isdigit(*s)) {
s++;
} else {
return 0;
}
}
return 1;
}
/** @}
*/
/** \addtogroup ssh_session
* @{ */
/**
* \brief Lowercase a string.
* \param str String to lowercase.
* \return The malloced lowered string or NULL on error.
* \internal
*/
static char *lowercase(const char* str) {
char *new, *p;
if (str == NULL) {
return NULL;
}
new = strdup(str);
if (new == NULL) {
return NULL;
}
for (p = new; *p; p++) {
*p = tolower(*p);
}
return new;
}
/** \brief frees a token array
* \internal
*/
static void tokens_free(char **tokens) {
if (tokens == NULL) {
return;
}
SAFE_FREE(tokens[0]);
/* It's not needed to free other pointers because tokens generated by
* space_tokenize fit all in one malloc
*/
SAFE_FREE(tokens);
}
/** \brief returns one line of known host file
* will return a token array containing (host|ip) keytype key
* \param file pointer to the known host file. Could be pointing to NULL at start
* \param filename file name of the known host file
* \param found_type pointer to a string to be set with the found key type
* \internal
* \returns NULL if no match was found or the file was not found
* \returns found_type type of key (ie "dsa","ssh-rsa1"). Don't free that value.
*/
static char **ssh_get_knownhost_line(ssh_session session, FILE **file,
const char *filename, const char **found_type) {
char buffer[4096] = {0};
char *ptr;
char **tokens;
enter_function();
if(*file == NULL){
*file = fopen(filename,"r");
if (*file == NULL) {
leave_function();
return NULL;
}
}
while (fgets(buffer, sizeof(buffer), *file)) {
ptr = strchr(buffer, '\n');
if (ptr) {
*ptr = '\0';
}
ptr = strchr(buffer,'\r');
if (ptr) {
*ptr = '\0';
}
if (!buffer[0] || buffer[0] == '#') {
continue; /* skip empty lines */
}
tokens = space_tokenize(buffer);
if (tokens == NULL) {
fclose(*file);
*file = NULL;
leave_function();
return NULL;
}
if(!tokens[0] || !tokens[1] || !tokens[2]) {
/* it should have at least 3 tokens */
tokens_free(tokens);
continue;
}
*found_type = tokens[1];
if (tokens[3]) {
/* openssh rsa1 format has 4 tokens on the line. Recognize it
by the fact that everything is all digits */
if (tokens[4]) {
/* that's never valid */
tokens_free(tokens);
continue;
}
if (alldigits(tokens[1]) && alldigits(tokens[2]) && alldigits(tokens[3])) {
*found_type = "ssh-rsa1";
} else {
/* 3 tokens only, not four */
tokens_free(tokens);
continue;
}
}
leave_function();
return tokens;
}
fclose(*file);
*file = NULL;
/* we did not find anything, end of file*/
leave_function();
return NULL;
}
/**
* \brief Check the public key in the known host line matches the
* public key of the currently connected server.
* \param tokens list of tokens in the known_hosts line.
* \return 1 if the key matches
* \return 0 if the key doesn't match
* \return -1 on error
*/
static int check_public_key(ssh_session session, char **tokens) {
ssh_string pubkey = session->current_crypto->server_pubkey;
ssh_buffer pubkey_buffer;
char *pubkey_64;
/* ok we found some public key in known hosts file. now un-base64it */
if (alldigits(tokens[1])) {
/* openssh rsa1 format */
bignum tmpbn;
ssh_string tmpstring;
unsigned int len;
int i;
pubkey_buffer = buffer_new();
if (pubkey_buffer == NULL) {
return -1;
}
tmpstring = string_from_char("ssh-rsa1");
if (tmpstring == NULL) {
buffer_free(pubkey_buffer);
return -1;
}
if (buffer_add_ssh_string(pubkey_buffer, tmpstring) < 0) {
buffer_free(pubkey_buffer);
string_free(tmpstring);
return -1;
}
string_free(tmpstring);
for (i = 2; i < 4; i++) { /* e, then n */
tmpbn = NULL;
bignum_dec2bn(tokens[i], &tmpbn);
if (tmpbn == NULL) {
buffer_free(pubkey_buffer);
return -1;
}
/* for some reason, make_bignum_string does not work
because of the padding which it does --kv */
/* tmpstring = make_bignum_string(tmpbn); */
/* do it manually instead */
len = bignum_num_bytes(tmpbn);
tmpstring = malloc(4 + len);
if (tmpstring == NULL) {
buffer_free(pubkey_buffer);
bignum_free(tmpbn);
return -1;
}
/* TODO: fix the hardcoding */
tmpstring->size = htonl(len);
#ifdef HAVE_LIBGCRYPT
bignum_bn2bin(tmpbn, len, tmpstring->string);
#elif defined HAVE_LIBCRYPTO
bignum_bn2bin(tmpbn, tmpstring->string);
#endif
bignum_free(tmpbn);
if (buffer_add_ssh_string(pubkey_buffer, tmpstring) < 0) {
buffer_free(pubkey_buffer);
string_free(tmpstring);
bignum_free(tmpbn);
return -1;
}
string_free(tmpstring);
}
} else {
/* ssh-dss or ssh-rsa */
pubkey_64 = tokens[2];
pubkey_buffer = base64_to_bin(pubkey_64);
}
if (pubkey_buffer == NULL) {
ssh_set_error(session, SSH_FATAL,
"Verifying that server is a known host: base64 error");
return -1;
}
if (buffer_get_len(pubkey_buffer) != string_len(pubkey)) {
buffer_free(pubkey_buffer);
return 0;
}
/* now test that they are identical */
if (memcmp(buffer_get(pubkey_buffer), pubkey->string,
buffer_get_len(pubkey_buffer)) != 0) {
buffer_free(pubkey_buffer);
return 0;
}
buffer_free(pubkey_buffer);
return 1;
}
/**
* \brief checks if a hostname matches a openssh-style hashed known host
* \param host host to check
* \param hashed hashed value
* \returns 1 if it matches
* \returns 0 otherwise
*/
static int match_hashed_host(ssh_session session, const char *host,
const char *sourcehash) {
/* Openssh hash structure :
* |1|base64 encoded salt|base64 encoded hash
* hash is produced that way :
* hash := HMAC_SHA1(key=salt,data=host)
*/
unsigned char buffer[256] = {0};
ssh_buffer salt;
ssh_buffer hash;
HMACCTX mac;
char *source;
char *b64hash;
int match;
unsigned int size;
enter_function();
if (strncmp(sourcehash, "|1|", 3) != 0) {
return 0;
}
source = strdup(sourcehash + 3);
if (source == NULL) {
leave_function();
return 0;
}
b64hash = strchr(source, '|');
if (b64hash == NULL) {
/* Invalid hash */
SAFE_FREE(source);
leave_function();
return 0;
}
*b64hash = '\0';
b64hash++;
salt = base64_to_bin(source);
if (salt == NULL) {
SAFE_FREE(source);
leave_function();
return 0;
}
hash = base64_to_bin(b64hash);
SAFE_FREE(source);
if (hash == NULL) {
buffer_free(salt);
leave_function();
return 0;
}
mac = hmac_init(buffer_get(salt), buffer_get_len(salt), HMAC_SHA1);
if (mac == NULL) {
buffer_free(salt);
buffer_free(hash);
leave_function();
return 0;
}
size = sizeof(buffer);
hmac_update(mac, host, strlen(host));
hmac_final(mac, buffer, &size);
if (size == buffer_get_len(hash) &&
memcmp(buffer, buffer_get(hash), size) == 0) {
match = 1;
} else {
match = 0;
}
buffer_free(salt);
buffer_free(hash);
ssh_log(session, SSH_LOG_PACKET,
"Matching a hashed host: %s match=%d", host, match);
leave_function();
return match;
}
/* How it's working :
* 1- we open the known host file and bitch if it doesn't exist
* 2- we need to examine each line of the file, until going on state SSH_SERVER_KNOWN_OK:
* - there's a match. if the key is good, state is SSH_SERVER_KNOWN_OK,
* else it's SSH_SERVER_KNOWN_CHANGED (or SSH_SERVER_FOUND_OTHER)
* - there's no match : no change
*/
/**
* \brief Check if the server is known.
* Checks the user's known host file for a previous connection to the
* current server.
*
* \param session ssh session
*
* \return SSH_SERVER_KNOWN_OK: The server is known and has not changed\n
* SSH_SERVER_KNOWN_CHANGED: The server key has changed. Either you are
* under attack or the administrator changed
* the key. You HAVE to warn the user about
* a possible attack\n
* SSH_SERVER_FOUND_OTHER: The server gave use a key of a type while
* we had an other type recorded. It is a
* possible attack \n
* SSH_SERVER_NOT_KNOWN: The server is unknown. User should confirm
* the MD5 is correct\n
* SSH_SERVER_FILE_NOT_FOUND:The known host file does not exist. The
* host is thus unknown. File will be created
* if host key is accepted\n
* SSH_SERVER_ERROR: Some error happened
*
* \see ssh_options_set()
* \see ssh_get_pubkey_hash()
*
* \bug There is no current way to remove or modify an entry into the known
* host table.
*/
int ssh_is_server_known(ssh_session session) {
FILE *file = NULL;
char **tokens;
char *host;
char *hostport;
const char *type;
int match;
int ret = SSH_SERVER_NOT_KNOWN;
enter_function();
if (session->knownhosts == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_KNOWNHOSTS, NULL) < 0) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Can't find a known_hosts file");
leave_function();
return SSH_SERVER_FILE_NOT_FOUND;
}
}
if (session->host == NULL) {
ssh_set_error(session, SSH_FATAL,
"Can't verify host in known hosts if the hostname isn't known");
leave_function();
return SSH_SERVER_ERROR;
}
host = lowercase(session->host);
hostport = ssh_hostport(host,session->port);
if (host == NULL || hostport == NULL) {
ssh_set_error_oom(session);
SAFE_FREE(host);
SAFE_FREE(hostport);
leave_function();
return SSH_SERVER_ERROR;
}
do {
tokens = ssh_get_knownhost_line(session, &file,
session->knownhosts, &type);
/* End of file, return the current state */
if (tokens == NULL) {
break;
}
match = match_hashed_host(session, host, tokens[0]);
if (match == 0){
match = match_hostname(hostport, tokens[0], strlen(tokens[0]));
}
if (match == 0) {
match = match_hostname(host, tokens[0], strlen(tokens[0]));
}
if (match == 0) {
match = match_hashed_host(session, hostport, tokens[0]);
}
if (match) {
/* We got a match. Now check the key type */
if (strcmp(session->current_crypto->server_pubkey_type, type) != 0) {
/* Different type. We don't override the known_changed error which is
* more important */
if (ret != SSH_SERVER_KNOWN_CHANGED)
ret = SSH_SERVER_FOUND_OTHER;
tokens_free(tokens);
continue;
}
/* so we know the key type is good. We may get a good key or a bad key. */
match = check_public_key(session, tokens);
tokens_free(tokens);
if (match < 0) {
ret = SSH_SERVER_ERROR;
break;
} else if (match == 1) {
ret = SSH_SERVER_KNOWN_OK;
break;
} else if(match == 0) {
/* We override the status with the wrong key state */
ret = SSH_SERVER_KNOWN_CHANGED;
}
} else {
tokens_free(tokens);
}
} while (1);
SAFE_FREE(host);
SAFE_FREE(hostport);
if (file != NULL) {
fclose(file);
}
/* Return the current state at end of file */
leave_function();
return ret;
}
/**
* @brief Write the current server as known in the known hosts file.
*
* This will create the known hosts file if it does not exist. You generaly use
* it when ssh_is_server_known() answered SSH_SERVER_NOT_KNOWN.
*
* @param[in] session The ssh session to use.
*
* @return SSH_OK on success, SSH_ERROR on error.
*/
int ssh_write_knownhost(ssh_session session) {
ssh_string pubkey = session->current_crypto->server_pubkey;
unsigned char *pubkey_64;
char buffer[4096] = {0};
FILE *file;
char *dir;
char *host;
char *hostport;
size_t len = 0;
if (session->host == NULL) {
ssh_set_error(session, SSH_FATAL,
"Can't write host in known hosts if the hostname isn't known");
return SSH_ERROR;
}
host = lowercase(session->host);
/* If using a nonstandard port, save the host in the [host]:port format */
if(session->port != 22){
hostport = ssh_hostport(host,session->port);
SAFE_FREE(host);
host=hostport;
hostport=NULL;
}
if (session->knownhosts == NULL) {
if (ssh_options_set(session, SSH_OPTIONS_KNOWNHOSTS, NULL) < 0) {
ssh_set_error(session, SSH_FATAL, "Can't find a known_hosts file");
return -1;
}
}
/* Check if ~/.ssh exists and create it if not */
dir = ssh_dirname(session->knownhosts);
if (dir == NULL) {
ssh_set_error(session, SSH_FATAL, "%s", strerror(errno));
return -1;
}
if (! ssh_file_readaccess_ok(dir)) {
if (ssh_mkdir(dir, 0700) < 0) {
ssh_set_error(session, SSH_FATAL,
"Cannot create %s directory.", dir);
SAFE_FREE(dir);
return -1;
}
}
SAFE_FREE(dir);
file = fopen(session->knownhosts, "a");
if (file == NULL) {
ssh_set_error(session, SSH_FATAL,
"Couldn't open known_hosts file %s for appending: %s",
session->knownhosts, strerror(errno));
SAFE_FREE(host);
return -1;
}
if (strcmp(session->current_crypto->server_pubkey_type, "ssh-rsa1") == 0) {
/* openssh uses a different format for ssh-rsa1 keys.
Be compatible --kv */
ssh_public_key key;
char *e_string = NULL;
char *n_string = NULL;
bignum e = NULL;
bignum n = NULL;
int rsa_size;
#ifdef HAVE_LIBGCRYPT
gcry_sexp_t sexp;
#endif
key = publickey_from_string(session, pubkey);
if (key == NULL) {
fclose(file);
SAFE_FREE(host);
return -1;
}
#ifdef HAVE_LIBGCRYPT
sexp = gcry_sexp_find_token(key->rsa_pub, "e", 0);
if (sexp == NULL) {
publickey_free(key);
fclose(file);
SAFE_FREE(host);
return -1;
}
e = gcry_sexp_nth_mpi(sexp, 1, GCRYMPI_FMT_USG);
gcry_sexp_release(sexp);
if (e == NULL) {
publickey_free(key);
fclose(file);
SAFE_FREE(host);
return -1;
}
sexp = gcry_sexp_find_token(key->rsa_pub, "n", 0);
if (sexp == NULL) {
publickey_free(key);
bignum_free(e);
fclose(file);
SAFE_FREE(host);
return -1;
}
n = gcry_sexp_nth_mpi(sexp, 1, GCRYMPI_FMT_USG);
gcry_sexp_release(sexp);
if (n == NULL) {
publickey_free(key);
bignum_free(e);
fclose(file);
SAFE_FREE(host);
return -1;
}
rsa_size = (gcry_pk_get_nbits(key->rsa_pub) + 7) / 8;
#elif defined HAVE_LIBCRYPTO
e = key->rsa_pub->e;
n = key->rsa_pub->n;
rsa_size = RSA_size(key->rsa_pub);
#endif
e_string = bignum_bn2dec(e);
n_string = bignum_bn2dec(n);
if (e_string == NULL || n_string == NULL) {
#ifdef HAVE_LIBGCRYPT
bignum_free(e);
bignum_free(n);
SAFE_FREE(e_string);
SAFE_FREE(n_string);
#elif defined HAVE_LIBCRYPTO
OPENSSL_free(e_string);
OPENSSL_free(n_string);
#endif
publickey_free(key);
fclose(file);
SAFE_FREE(host);
return -1;
}
snprintf(buffer, sizeof(buffer),
"%s %d %s %s\n",
host,
rsa_size << 3,
e_string,
n_string);
#ifdef HAVE_LIBGCRYPT
bignum_free(e);
bignum_free(n);
SAFE_FREE(e_string);
SAFE_FREE(n_string);
#elif defined HAVE_LIBCRYPTO
OPENSSL_free(e_string);
OPENSSL_free(n_string);
#endif
publickey_free(key);
} else {
pubkey_64 = bin_to_base64(pubkey->string, string_len(pubkey));
if (pubkey_64 == NULL) {
fclose(file);
SAFE_FREE(host);
return -1;
}
snprintf(buffer, sizeof(buffer),
"%s %s %s\n",
host,
session->current_crypto->server_pubkey_type,
pubkey_64);
SAFE_FREE(pubkey_64);
}
SAFE_FREE(host);
len = strlen(buffer);
if (fwrite(buffer, len, 1, file) != 1 || ferror(file)) {
fclose(file);
return -1;
}
fclose(file);
return 0;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/keyfiles.c
|
C
|
gpl3
| 46,504
|
/*
* gcrypt_missing.c - routines that are in OpenSSL but not in libgcrypt.
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2006 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdlib.h>
#include "libssh/priv.h"
#ifdef HAVE_LIBGCRYPT
int my_gcry_dec2bn(bignum *bn, const char *data) {
int count;
*bn = bignum_new();
if (*bn == NULL) {
return 0;
}
gcry_mpi_set_ui(*bn, 0);
for (count = 0; data[count]; count++) {
gcry_mpi_mul_ui(*bn, *bn, 10);
gcry_mpi_add_ui(*bn, *bn, data[count] - '0');
}
return count;
}
char *my_gcry_bn2dec(bignum bn) {
bignum bndup, num, ten;
char *ret;
int count, count2;
int size, rsize;
char decnum;
size = gcry_mpi_get_nbits(bn) * 3;
rsize = size / 10 + size / 1000 + 2;
ret = malloc(rsize + 1);
if (ret == NULL) {
return NULL;
}
if (!gcry_mpi_cmp_ui(bn, 0)) {
strcpy(ret, "0");
} else {
ten = bignum_new();
if (ten == NULL) {
SAFE_FREE(ret);
return NULL;
}
num = bignum_new();
if (num == NULL) {
SAFE_FREE(ret);
bignum_free(ten);
return NULL;
}
for (bndup = gcry_mpi_copy(bn), bignum_set_word(ten, 10), count = rsize;
count; count--) {
gcry_mpi_div(bndup, num, bndup, ten, 0);
for (decnum = 0, count2 = gcry_mpi_get_nbits(num); count2;
decnum *= 2, decnum += (gcry_mpi_test_bit(num, count2 - 1) ? 1 : 0),
count2--)
;
ret[count - 1] = decnum + '0';
}
for (count = 0; count < rsize && ret[count] == '0'; count++)
;
for (count2 = 0; count2 < rsize - count; ++count2) {
ret[count2] = ret[count2 + count];
}
ret[count2] = 0;
bignum_free(num);
bignum_free(bndup);
bignum_free(ten);
}
return ret;
}
#endif
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/gcrypt_missing.c
|
C
|
gpl3
| 2,577
|
/*
* packet.c - packet building functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/ssh1.h"
#include "libssh/crypto.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/socket.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#include "libssh/messages.h"
#include "libssh/pcap.h"
/* XXX include selected mac size */
static int macsize=SHA_DIGEST_LEN;
/* in nonblocking mode, socket_read will read as much as it can, and return */
/* SSH_OK if it has read at least len bytes, otherwise, SSH_AGAIN. */
/* in blocking mode, it will read at least len bytes and will block until it's ok. */
#define PACKET_STATE_INIT 0
#define PACKET_STATE_SIZEREAD 1
static int packet_read2(ssh_session session) {
unsigned int blocksize = (session->current_crypto ?
session->current_crypto->in_cipher->blocksize : 8);
int current_macsize = session->current_crypto ? macsize : 0;
unsigned char mac[30] = {0};
char buffer[16] = {0};
void *packet=NULL;
int to_be_read;
int rc = SSH_ERROR;
uint32_t len;
uint8_t padding;
enter_function();
if (session->alive == 0) {
/* The error message was already set into this session */
leave_function();
return SSH_ERROR;
}
switch(session->packet_state) {
case PACKET_STATE_INIT:
memset(&session->in_packet, 0, sizeof(PACKET));
if (session->in_buffer) {
if (buffer_reinit(session->in_buffer) < 0) {
goto error;
}
} else {
session->in_buffer = buffer_new();
if (session->in_buffer == NULL) {
goto error;
}
}
rc = ssh_socket_wait_for_data(session->socket, session, blocksize);
if (rc != SSH_OK) {
goto error;
}
rc = SSH_ERROR;
/* can't fail since we're sure there is enough data in socket buffer */
ssh_socket_read(session->socket, buffer, blocksize);
len = packet_decrypt_len(session, buffer);
if (buffer_add_data(session->in_buffer, buffer, blocksize) < 0) {
goto error;
}
if(len > MAX_PACKET_LEN) {
ssh_set_error(session, SSH_FATAL,
"read_packet(): Packet len too high(%u %.4x)", len, len);
goto error;
}
to_be_read = len - blocksize + sizeof(uint32_t);
if (to_be_read < 0) {
/* remote sshd sends invalid sizes? */
ssh_set_error(session, SSH_FATAL,
"given numbers of bytes left to be read < 0 (%d)!", to_be_read);
goto error;
}
/* saves the status of the current operations */
session->in_packet.len = len;
session->packet_state = PACKET_STATE_SIZEREAD;
case PACKET_STATE_SIZEREAD:
len = session->in_packet.len;
to_be_read = len - blocksize + sizeof(uint32_t) + current_macsize;
/* if to_be_read is zero, the whole packet was blocksize bytes. */
if (to_be_read != 0) {
rc = ssh_socket_wait_for_data(session->socket,session,to_be_read);
if (rc != SSH_OK) {
goto error;
}
rc = SSH_ERROR;
packet = malloc(to_be_read);
if (packet == NULL) {
ssh_set_error(session, SSH_FATAL, "No space left");
goto error;
}
ssh_socket_read(session->socket,packet,to_be_read-current_macsize);
ssh_log(session,SSH_LOG_PACKET,"Read a %d bytes packet",len);
if (buffer_add_data(session->in_buffer, packet,
to_be_read - current_macsize) < 0) {
SAFE_FREE(packet);
goto error;
}
SAFE_FREE(packet);
}
if (session->current_crypto) {
/*
* decrypt the rest of the packet (blocksize bytes already
* have been decrypted)
*/
if (packet_decrypt(session,
((uint8_t*)buffer_get(session->in_buffer) + blocksize),
buffer_get_len(session->in_buffer) - blocksize) < 0) {
ssh_set_error(session, SSH_FATAL, "Decrypt error");
goto error;
}
#ifdef WITH_PCAP
if(session->pcap_ctx){
ssh_pcap_context_write(session->pcap_ctx,
SSH_PCAP_DIR_IN, buffer_get(session->in_buffer),
buffer_get_len(session->in_buffer),
buffer_get_len(session->in_buffer));
}
#endif
ssh_socket_read(session->socket, mac, macsize);
if (packet_hmac_verify(session, session->in_buffer, mac) < 0) {
ssh_set_error(session, SSH_FATAL, "HMAC error");
goto error;
}
}
#ifdef WITH_PCAP
else {
/* No crypto */
if(session->pcap_ctx){
ssh_pcap_context_write(session->pcap_ctx,
SSH_PCAP_DIR_IN, buffer_get(session->in_buffer),
buffer_get_len(session->in_buffer),
buffer_get_len(session->in_buffer));
}
}
#endif
buffer_pass_bytes(session->in_buffer, sizeof(uint32_t));
/* pass the size which has been processed before */
if (buffer_get_u8(session->in_buffer, &padding) == 0) {
ssh_set_error(session, SSH_FATAL, "Packet too short to read padding");
goto error;
}
ssh_log(session, SSH_LOG_PACKET,
"%hhd bytes padding, %d bytes left in buffer",
padding, buffer_get_rest_len(session->in_buffer));
if (padding > buffer_get_rest_len(session->in_buffer)) {
ssh_set_error(session, SSH_FATAL,
"Invalid padding: %d (%d resting)",
padding,
buffer_get_rest_len(session->in_buffer));
#ifdef DEBUG_CRYPTO
ssh_print_hexa("incrimined packet",
buffer_get(session->in_buffer),
buffer_get_len(session->in_buffer));
#endif
goto error;
}
buffer_pass_bytes_end(session->in_buffer, padding);
ssh_log(session, SSH_LOG_PACKET,
"After padding, %d bytes left in buffer",
buffer_get_rest_len(session->in_buffer));
#if defined(HAVE_LIBZ) && defined(WITH_LIBZ)
if (session->current_crypto && session->current_crypto->do_compress_in) {
ssh_log(session, SSH_LOG_PACKET, "Decompressing in_buffer ...");
if (decompress_buffer(session, session->in_buffer, MAX_PACKET_LEN) < 0) {
goto error;
}
}
#endif
session->recv_seq++;
session->packet_state = PACKET_STATE_INIT;
leave_function();
return SSH_OK;
}
ssh_set_error(session, SSH_FATAL,
"Invalid state into packet_read2(): %d",
session->packet_state);
error:
leave_function();
return rc;
}
#ifdef WITH_SSH1
/* a slighty modified packet_read2() for SSH-1 protocol */
static int packet_read1(ssh_session session) {
void *packet = NULL;
int rc = SSH_ERROR;
int to_be_read;
uint32_t padding;
uint32_t crc;
uint32_t len;
enter_function();
if(!session->alive) {
goto error;
}
switch (session->packet_state){
case PACKET_STATE_INIT:
memset(&session->in_packet, 0, sizeof(PACKET));
if (session->in_buffer) {
if (buffer_reinit(session->in_buffer) < 0) {
goto error;
}
} else {
session->in_buffer = buffer_new();
if (session->in_buffer == NULL) {
goto error;
}
}
rc = ssh_socket_read(session->socket, &len, sizeof(uint32_t));
if (rc != SSH_OK) {
goto error;
}
rc = SSH_ERROR;
/* len is not encrypted */
len = ntohl(len);
if (len > MAX_PACKET_LEN) {
ssh_set_error(session, SSH_FATAL,
"read_packet(): Packet len too high (%u %.8x)", len, len);
goto error;
}
ssh_log(session, SSH_LOG_PACKET, "Reading a %d bytes packet", len);
session->in_packet.len = len;
session->packet_state = PACKET_STATE_SIZEREAD;
case PACKET_STATE_SIZEREAD:
len = session->in_packet.len;
/* SSH-1 has a fixed padding lenght */
padding = 8 - (len % 8);
to_be_read = len + padding;
/* it is _not_ possible that to_be_read be < 8. */
packet = malloc(to_be_read);
if (packet == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
goto error;
}
rc = ssh_socket_read(session->socket, packet, to_be_read);
if(rc != SSH_OK) {
SAFE_FREE(packet);
goto error;
}
rc = SSH_ERROR;
if (buffer_add_data(session->in_buffer,packet,to_be_read) < 0) {
SAFE_FREE(packet);
goto error;
}
SAFE_FREE(packet);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("read packet:", buffer_get(session->in_buffer),
buffer_get_len(session->in_buffer));
#endif
if (session->current_crypto) {
/*
* We decrypt everything, missing the lenght part (which was
* previously read, unencrypted, and is not part of the buffer
*/
if (packet_decrypt(session,
buffer_get(session->in_buffer),
buffer_get_len(session->in_buffer)) < 0) {
ssh_set_error(session, SSH_FATAL, "Packet decrypt error");
goto error;
}
}
#ifdef DEBUG_CRYPTO
ssh_print_hexa("read packet decrypted:", buffer_get(session->in_buffer),
buffer_get_len(session->in_buffer));
#endif
ssh_log(session, SSH_LOG_PACKET, "%d bytes padding", padding);
if(((len + padding) != buffer_get_rest_len(session->in_buffer)) ||
((len + padding) < sizeof(uint32_t))) {
ssh_log(session, SSH_LOG_RARE, "no crc32 in packet");
ssh_set_error(session, SSH_FATAL, "no crc32 in packet");
goto error;
}
memcpy(&crc,
(unsigned char *)buffer_get_rest(session->in_buffer) + (len+padding) - sizeof(uint32_t),
sizeof(uint32_t));
buffer_pass_bytes_end(session->in_buffer, sizeof(uint32_t));
crc = ntohl(crc);
if (ssh_crc32(buffer_get_rest(session->in_buffer),
(len + padding) - sizeof(uint32_t)) != crc) {
#ifdef DEBUG_CRYPTO
ssh_print_hexa("crc32 on",buffer_get_rest(session->in_buffer),
len + padding - sizeof(uint32_t));
#endif
ssh_log(session, SSH_LOG_RARE, "Invalid crc32");
ssh_set_error(session, SSH_FATAL,
"Invalid crc32: expected %.8x, got %.8x",
crc,
ssh_crc32(buffer_get_rest(session->in_buffer),
len + padding - sizeof(uint32_t)));
goto error;
}
/* pass the padding */
buffer_pass_bytes(session->in_buffer, padding);
ssh_log(session, SSH_LOG_PACKET, "The packet is valid");
/* TODO FIXME
#if defined(HAVE_LIBZ) && defined(WITH_LIBZ)
if(session->current_crypto && session->current_crypto->do_compress_in){
decompress_buffer(session,session->in_buffer);
}
#endif
*/
session->recv_seq++;
session->packet_state=PACKET_STATE_INIT;
leave_function();
return SSH_OK;
} /* switch */
ssh_set_error(session, SSH_FATAL,
"Invalid state into packet_read1(): %d",
session->packet_state);
error:
leave_function();
return rc;
}
#endif /* WITH_SSH1 */
/* that's where i'd like C to be object ... */
int packet_read(ssh_session session) {
#ifdef WITH_SSH1
if (session->version == 1) {
return packet_read1(session);
}
#endif
return packet_read2(session);
}
int packet_translate(ssh_session session) {
enter_function();
memset(&session->in_packet, 0, sizeof(PACKET));
if(session->in_buffer == NULL) {
leave_function();
return SSH_ERROR;
}
ssh_log(session, SSH_LOG_PACKET, "Final size %d",
buffer_get_rest_len(session->in_buffer));
if(buffer_get_u8(session->in_buffer, &session->in_packet.type) == 0) {
ssh_set_error(session, SSH_FATAL, "Packet too short to read type");
leave_function();
return SSH_ERROR;
}
ssh_log(session, SSH_LOG_PACKET, "Type %hhd", session->in_packet.type);
session->in_packet.valid = 1;
leave_function();
return SSH_OK;
}
/*
* Write the the bufferized output. If the session is blocking, or
* enforce_blocking is set, the call may block. Otherwise, it won't block.
* Return SSH_OK if everything has been sent, SSH_AGAIN if there are still
* things to send on buffer, SSH_ERROR if there is an error.
*/
int packet_flush(ssh_session session, int enforce_blocking) {
if (enforce_blocking || session->blocking) {
return ssh_socket_blocking_flush(session->socket);
}
return ssh_socket_nonblocking_flush(session->socket);
}
/*
* This function places the outgoing packet buffer into an outgoing
* socket buffer
*/
static int packet_write(ssh_session session) {
int rc = SSH_ERROR;
enter_function();
ssh_socket_write(session->socket,
buffer_get(session->out_buffer),
buffer_get_len(session->out_buffer));
rc = packet_flush(session, 0);
leave_function();
return rc;
}
static int packet_send2(ssh_session session) {
unsigned int blocksize = (session->current_crypto ?
session->current_crypto->out_cipher->blocksize : 8);
uint32_t currentlen = buffer_get_len(session->out_buffer);
unsigned char *hmac = NULL;
char padstring[32] = {0};
int rc = SSH_ERROR;
uint32_t finallen;
uint8_t padding;
enter_function();
ssh_log(session, SSH_LOG_PACKET,
"Writing on the wire a packet having %u bytes before", currentlen);
#if defined(HAVE_LIBZ) && defined(WITH_LIBZ)
if (session->current_crypto && session->current_crypto->do_compress_out) {
ssh_log(session, SSH_LOG_PACKET, "Compressing in_buffer ...");
if (compress_buffer(session,session->out_buffer) < 0) {
goto error;
}
currentlen = buffer_get_len(session->out_buffer);
}
#endif
padding = (blocksize - ((currentlen +5) % blocksize));
if(padding < 4) {
padding += blocksize;
}
if (session->current_crypto) {
ssh_get_random(padstring, padding, 0);
} else {
memset(padstring,0,padding);
}
finallen = htonl(currentlen + padding + 1);
ssh_log(session, SSH_LOG_PACKET,
"%d bytes after comp + %d padding bytes = %lu bytes packet",
currentlen, padding, (long unsigned int) ntohl(finallen));
if (buffer_prepend_data(session->out_buffer, &padding, sizeof(uint8_t)) < 0) {
goto error;
}
if (buffer_prepend_data(session->out_buffer, &finallen, sizeof(uint32_t)) < 0) {
goto error;
}
if (buffer_add_data(session->out_buffer, padstring, padding) < 0) {
goto error;
}
#ifdef WITH_PCAP
if(session->pcap_ctx){
ssh_pcap_context_write(session->pcap_ctx,SSH_PCAP_DIR_OUT,
buffer_get(session->out_buffer),buffer_get_len(session->out_buffer)
,buffer_get_len(session->out_buffer));
}
#endif
hmac = packet_encrypt(session, buffer_get(session->out_buffer),
buffer_get_len(session->out_buffer));
if (hmac) {
if (buffer_add_data(session->out_buffer, hmac, 20) < 0) {
goto error;
}
}
rc = packet_write(session);
session->send_seq++;
if (buffer_reinit(session->out_buffer) < 0) {
rc = SSH_ERROR;
}
error:
leave_function();
return rc; /* SSH_OK, AGAIN or ERROR */
}
#ifdef WITH_SSH1
static int packet_send1(ssh_session session) {
unsigned int blocksize = (session->current_crypto ?
session->current_crypto->out_cipher->blocksize : 8);
uint32_t currentlen = buffer_get_len(session->out_buffer) + sizeof(uint32_t);
char padstring[32] = {0};
int rc = SSH_ERROR;
uint32_t finallen;
uint32_t crc;
uint8_t padding;
enter_function();
ssh_log(session,SSH_LOG_PACKET,"Sending a %d bytes long packet",currentlen);
/* TODO FIXME
#if defined(HAVE_LIBZ) && defined(WITH_LIBZ)
if (session->current_crypto && session->current_crypto->do_compress_out) {
if (compress_buffer(session, session->out_buffer) < 0) {
goto error;
}
currentlen = buffer_get_len(session->out_buffer);
}
#endif
*/
padding = blocksize - (currentlen % blocksize);
if (session->current_crypto) {
ssh_get_random(padstring, padding, 0);
} else {
memset(padstring, 0, padding);
}
finallen = htonl(currentlen);
ssh_log(session, SSH_LOG_PACKET,
"%d bytes after comp + %d padding bytes = %d bytes packet",
currentlen, padding, ntohl(finallen));
if (buffer_prepend_data(session->out_buffer, &padstring, padding) < 0) {
goto error;
}
if (buffer_prepend_data(session->out_buffer, &finallen, sizeof(uint32_t)) < 0) {
goto error;
}
crc = ssh_crc32((char *)buffer_get(session->out_buffer) + sizeof(uint32_t),
buffer_get_len(session->out_buffer) - sizeof(uint32_t));
if (buffer_add_u32(session->out_buffer, ntohl(crc)) < 0) {
goto error;
}
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Clear packet", buffer_get(session->out_buffer),
buffer_get_len(session->out_buffer));
#endif
packet_encrypt(session, (unsigned char *)buffer_get(session->out_buffer) + sizeof(uint32_t),
buffer_get_len(session->out_buffer) - sizeof(uint32_t));
#ifdef DEBUG_CRYPTO
ssh_print_hexa("encrypted packet",buffer_get(session->out_buffer),
buffer_get_len(session->out_buffer));
#endif
if (ssh_socket_write(session->socket, buffer_get(session->out_buffer),
buffer_get_len(session->out_buffer)) == SSH_ERROR) {
goto error;
}
rc = packet_flush(session, 0);
session->send_seq++;
if (buffer_reinit(session->out_buffer) < 0) {
rc = SSH_ERROR;
}
error:
leave_function();
return rc; /* SSH_OK, AGAIN or ERROR */
}
#endif /* WITH_SSH1 */
int packet_send(ssh_session session) {
#ifdef WITH_SSH1
if (session->version == 1) {
return packet_send1(session);
}
#endif
return packet_send2(session);
}
void packet_parse(ssh_session session) {
ssh_string error_s = NULL;
char *error = NULL;
uint32_t type = session->in_packet.type;
uint32_t tmp;
#ifdef WITH_SSH1
if (session->version == 1) {
/* SSH-1 */
switch(type) {
case SSH_MSG_DISCONNECT:
ssh_log(session, SSH_LOG_PACKET, "Received SSH_MSG_DISCONNECT");
ssh_set_error(session, SSH_FATAL, "Received SSH_MSG_DISCONNECT");
ssh_socket_close(session->socket);
session->alive = 0;
return;
case SSH_SMSG_STDOUT_DATA:
case SSH_SMSG_STDERR_DATA:
case SSH_SMSG_EXITSTATUS:
channel_handle1(session,type);
return;
case SSH_MSG_DEBUG:
case SSH_MSG_IGNORE:
break;
default:
ssh_log(session, SSH_LOG_PACKET,
"Unexpected message code %d", type);
}
return;
} else {
#endif /* WITH_SSH1 */
switch(type) {
case SSH2_MSG_DISCONNECT:
buffer_get_u32(session->in_buffer, &tmp);
error_s = buffer_get_ssh_string(session->in_buffer);
if (error_s == NULL) {
return;
}
error = string_to_char(error_s);
string_free(error_s);
if (error == NULL) {
return;
}
ssh_log(session, SSH_LOG_PACKET, "Received SSH_MSG_DISCONNECT\n");
ssh_set_error(session, SSH_FATAL,
"Received SSH_MSG_DISCONNECT: %s",error);
SAFE_FREE(error);
ssh_socket_close(session->socket);
session->alive = 0;
return;
case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
case SSH2_MSG_CHANNEL_DATA:
case SSH2_MSG_CHANNEL_EXTENDED_DATA:
case SSH2_MSG_CHANNEL_REQUEST:
case SSH2_MSG_CHANNEL_EOF:
case SSH2_MSG_CHANNEL_CLOSE:
channel_handle(session,type);
return;
case SSH2_MSG_IGNORE:
case SSH2_MSG_DEBUG:
return;
case SSH2_MSG_SERVICE_REQUEST:
case SSH2_MSG_USERAUTH_REQUEST:
case SSH2_MSG_CHANNEL_OPEN:
message_handle(session,type);
return;
case SSH2_MSG_GLOBAL_REQUEST:
ssh_global_request_handle(session);
return;
default:
ssh_log(session, SSH_LOG_RARE, "Received unhandled packet %d", type);
}
#ifdef WITH_SSH1
}
#endif
}
#ifdef WITH_SSH1
static int packet_wait1(ssh_session session, int type, int blocking) {
enter_function();
ssh_log(session, SSH_LOG_PROTOCOL, "packet_wait1 waiting for %d", type);
do {
if ((packet_read1(session) != SSH_OK) ||
(packet_translate(session) != SSH_OK)) {
leave_function();
return SSH_ERROR;
}
ssh_log(session, SSH_LOG_PACKET, "packet_wait1() received a type %d packet",
session->in_packet.type);
switch (session->in_packet.type) {
case SSH_MSG_DISCONNECT:
packet_parse(session);
leave_function();
return SSH_ERROR;
case SSH_SMSG_STDOUT_DATA:
case SSH_SMSG_STDERR_DATA:
case SSH_SMSG_EXITSTATUS:
if (channel_handle1(session,type) < 0) {
leave_function();
return SSH_ERROR;
}
break;
case SSH_MSG_DEBUG:
case SSH_MSG_IGNORE:
break;
/* case SSH2_MSG_CHANNEL_CLOSE:
packet_parse(session);
break;;
*/
default:
if (type && (type != session->in_packet.type)) {
ssh_set_error(session, SSH_FATAL,
"packet_wait1(): Received a %d type packet, but expected %d\n",
session->in_packet.type, type);
leave_function();
return SSH_ERROR;
}
leave_function();
return SSH_OK;
}
if (blocking == 0) {
leave_function();
return SSH_OK;
}
} while(1);
leave_function();
return SSH_OK;
}
#endif /* WITH_SSH1 */
static int packet_wait2(ssh_session session, int type, int blocking) {
int rc = SSH_ERROR;
enter_function();
do {
rc = packet_read2(session);
if (rc != SSH_OK) {
leave_function();
return rc;
}
if (packet_translate(session) != SSH_OK) {
leave_function();
return SSH_ERROR;
}
switch (session->in_packet.type) {
case SSH2_MSG_DISCONNECT:
packet_parse(session);
ssh_log(session, SSH_LOG_PACKET, "received disconnect packet");
leave_function();
return SSH_ERROR;
case SSH2_MSG_GLOBAL_REQUEST:
case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
case SSH2_MSG_CHANNEL_DATA:
case SSH2_MSG_CHANNEL_EXTENDED_DATA:
case SSH2_MSG_CHANNEL_REQUEST:
case SSH2_MSG_CHANNEL_EOF:
case SSH2_MSG_CHANNEL_CLOSE:
case SSH2_MSG_SERVICE_REQUEST:
case SSH2_MSG_USERAUTH_REQUEST:
case SSH2_MSG_CHANNEL_OPEN:
packet_parse(session);
break;
case SSH2_MSG_IGNORE:
case SSH2_MSG_DEBUG:
break;
default:
if (type && (type != session->in_packet.type)) {
ssh_set_error(session, SSH_FATAL,
"packet_wait2(): Received a %d type packet, but expected a %d\n",
session->in_packet.type, type);
leave_function();
return SSH_ERROR;
}
leave_function();
return SSH_OK;
}
if (blocking == 0) {
leave_function();
return SSH_OK; //shouldn't it return SSH_AGAIN here ?
}
} while(1);
leave_function();
return SSH_OK;
}
int packet_wait(ssh_session session, int type, int block) {
#ifdef WITH_SSH1
if (session->version == 1) {
return packet_wait1(session, type, block);
}
#endif
return packet_wait2(session, type, block);
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/packet.c
|
C
|
gpl3
| 24,129
|
/*
* poll.c - poll wrapper
*
* This file is part of the SSH Library
*
* Copyright (c) 2009-2010 by Andreas Schneider <mail@cynapses.org>
* Copyright (c) 2003-2009 by Aris Adamantiadis
* Copyright (c) 2009 Aleksandar Kanchev
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* vim: ts=2 sw=2 et cindent
*/
#include "config.h"
#include <errno.h>
#include "libssh/priv.h"
#include "libssh/libssh.h"
#include "libssh/poll.h"
#ifndef SSH_POLL_CTX_CHUNK
#define SSH_POLL_CTX_CHUNK 5
#endif
struct ssh_poll_handle_struct {
ssh_poll_ctx ctx;
union {
socket_t fd;
size_t idx;
} x;
short events;
ssh_poll_callback cb;
void *cb_data;
};
struct ssh_poll_ctx_struct {
ssh_poll_handle *pollptrs;
ssh_pollfd_t *pollfds;
size_t polls_allocated;
size_t polls_used;
size_t chunk_size;
};
#ifdef HAVE_POLL
#include <poll.h>
void ssh_poll_init(void) {
return;
}
int ssh_poll(ssh_pollfd_t *fds, nfds_t nfds, int timeout) {
return poll((struct pollfd *) fds, nfds, timeout);
}
#else /* HAVE_POLL */
#include <sys/types.h>
#ifdef _WIN32
#ifndef STRICT
#define STRICT
#endif
#include <time.h>
#include <windows.h>
#include <winsock2.h>
#define WS2_LIBRARY "ws2_32.dll"
typedef int (*poll_fn)(ssh_pollfd_t *, nfds_t, int);
static poll_fn win_poll;
static HINSTANCE hlib;
#else
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/time.h>
#endif
static int bsd_poll(ssh_pollfd_t *fds, nfds_t nfds, int timeout) {
fd_set readfds, writefds, exceptfds;
struct timeval tv, *ptv;
socket_t max_fd;
int rc;
nfds_t i;
if (fds == NULL) {
errno = EFAULT;
return -1;
}
FD_ZERO (&readfds);
FD_ZERO (&writefds);
FD_ZERO (&exceptfds);
/* compute fd_sets and find largest descriptor */
for (max_fd = -1, i = 0; i < nfds; i++) {
if (fds[i].fd < 0) {
continue;
}
if (fds[i].events & (POLLIN | POLLRDNORM)) {
FD_SET (fds[i].fd, &readfds);
}
if (fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND)) {
FD_SET (fds[i].fd, &writefds);
}
if (fds[i].events & (POLLPRI | POLLRDBAND)) {
FD_SET (fds[i].fd, &exceptfds);
}
if (fds[i].fd >= max_fd &&
(fds[i].events & (POLLIN | POLLOUT | POLLPRI |
POLLRDNORM | POLLRDBAND |
POLLWRNORM | POLLWRBAND))) {
max_fd = fds[i].fd;
}
}
if (max_fd == -1) {
errno = EINVAL;
return -1;
}
if (timeout < 0) {
ptv = NULL;
} else {
ptv = &tv;
if (timeout == 0) {
tv.tv_sec = 0;
tv.tv_usec = 0;
} else {
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
}
}
rc = select (max_fd + 1, &readfds, &writefds, &exceptfds, ptv);
if (rc < 0) {
return -1;
}
for (rc = 0, i = 0; i < nfds; i++)
if (fds[i].fd >= 0) {
fds[i].revents = 0;
if (FD_ISSET(fds[i].fd, &readfds)) {
int save_errno = errno;
char data[64] = {0};
/* support for POLLHUP */
#ifdef _WIN32
if ((recv(fds[i].fd, data, 64, MSG_PEEK) == -1) &&
(errno == WSAESHUTDOWN || errno == WSAECONNRESET ||
errno == WSAECONNABORTED || errno == WSAENETRESET)) {
#else
if ((recv(fds[i].fd, data, 64, MSG_PEEK) == -1) &&
(errno == ESHUTDOWN || errno == ECONNRESET ||
errno == ECONNABORTED || errno == ENETRESET)) {
#endif
fds[i].revents |= POLLHUP;
} else {
fds[i].revents |= fds[i].events & (POLLIN | POLLRDNORM);
}
errno = save_errno;
}
if (FD_ISSET(fds[i].fd, &writefds)) {
fds[i].revents |= fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND);
}
if (FD_ISSET(fds[i].fd, &exceptfds)) {
fds[i].revents |= fds[i].events & (POLLPRI | POLLRDBAND);
}
if (fds[i].revents & ~POLLHUP) {
rc++;
}
} else {
fds[i].revents = POLLNVAL;
}
return rc;
}
void ssh_poll_init(void) {
poll_fn wsa_poll = NULL;
hlib = LoadLibrary(WS2_LIBRARY);
if (hlib != NULL) {
wsa_poll = (poll_fn) GetProcAddress(hlib, "WSAPoll");
}
if (wsa_poll == NULL) {
win_poll = bsd_poll;
} else {
win_poll = wsa_poll;
}
}
int ssh_poll(ssh_pollfd_t *fds, nfds_t nfds, int timeout) {
return win_poll(fds, nfds, timeout);
}
#endif /* HAVE_POLL */
/**
* @brief Allocate a new poll object, which could be used within a poll context.
*
* @param fd Socket that will be polled.
* @param events Poll events that will be monitored for the socket. i.e.
* POLLIN, POLLPRI, POLLOUT, POLLERR, POLLHUP, POLLNVAL
* @param cb Function to be called if any of the events are set.
* @param userdata Userdata to be passed to the callback function. NULL if
* not needed.
*
* @return A new poll object, NULL on error
*/
ssh_poll_handle ssh_poll_new(socket_t fd, short events, ssh_poll_callback cb,
void *userdata) {
ssh_poll_handle p;
p = malloc(sizeof(struct ssh_poll_handle_struct));
if (p != NULL) {
p->ctx = NULL;
p->x.fd = fd;
p->events = events;
p->cb = cb;
p->cb_data = userdata;
}
return p;
}
/**
* @brief Free a poll object.
*
* @param p Pointer to an already allocated poll object.
*/
void ssh_poll_free(ssh_poll_handle p) {
SAFE_FREE(p);
}
/**
* @brief Get the poll context of a poll object.
*
* @param p Pointer to an already allocated poll object.
*
* @return Poll context or NULL if the poll object isn't attached.
*/
ssh_poll_ctx ssh_poll_get_ctx(ssh_poll_handle p) {
return p->ctx;
}
/**
* @brief Get the events of a poll object.
*
* @param p Pointer to an already allocated poll object.
*
* @return Poll events.
*/
short ssh_poll_get_events(ssh_poll_handle p) {
return p->events;
}
/**
* @brief Set the events of a poll object. The events will also be propagated
* to an associated poll context.
*
* @param p Pointer to an already allocated poll object.
* @param events Poll events.
*/
void ssh_poll_set_events(ssh_poll_handle p, short events) {
p->events = events;
if (p->ctx != NULL) {
p->ctx->pollfds[p->x.idx].events = events;
}
}
/**
* @brief Add extra events to a poll object. Duplicates are ignored.
* The events will also be propagated to an associated poll context.
*
* @param p Pointer to an already allocated poll object.
* @param events Poll events.
*/
void ssh_poll_add_events(ssh_poll_handle p, short events) {
ssh_poll_set_events(p, ssh_poll_get_events(p) | events);
}
/**
* @brief Remove events from a poll object. Non-existent are ignored.
* The events will also be propagated to an associated poll context.
*
* @param p Pointer to an already allocated poll object.
* @param events Poll events.
*/
void ssh_poll_remove_events(ssh_poll_handle p, short events) {
ssh_poll_set_events(p, ssh_poll_get_events(p) & ~events);
}
/**
* @brief Get the raw socket of a poll object.
*
* @param p Pointer to an already allocated poll object.
*
* @return Raw socket.
*/
socket_t ssh_poll_get_fd(ssh_poll_handle p) {
if (p->ctx != NULL) {
return p->ctx->pollfds[p->x.idx].fd;
}
return p->x.fd;
}
/**
* @brief Set the callback of a poll object.
*
* @param p Pointer to an already allocated poll object.
* @param cb Function to be called if any of the events are set.
* @param userdata Userdata to be passed to the callback function. NULL if
* not needed.
*/
void ssh_poll_set_callback(ssh_poll_handle p, ssh_poll_callback cb, void *userdata) {
if (cb != NULL) {
p->cb = cb;
p->cb_data = userdata;
}
}
/**
* @brief Create a new poll context. It could be associated with many poll object
* which are going to be polled at the same time as the poll context. You
* would need a single poll context per thread.
*
* @param chunk_size The size of the memory chunk that will be allocated, when
* more memory is needed. This is for efficiency reasons,
* i.e. don't allocate memory for each new poll object, but
* for the next 5. Set it to 0 if you want to use the
* library's default value.
*/
ssh_poll_ctx ssh_poll_ctx_new(size_t chunk_size) {
ssh_poll_ctx ctx;
ctx = malloc(sizeof(struct ssh_poll_ctx_struct));
if (ctx != NULL) {
if (!chunk_size) {
chunk_size = SSH_POLL_CTX_CHUNK;
}
ctx->chunk_size = chunk_size;
ctx->pollptrs = NULL;
ctx->pollfds = NULL;
ctx->polls_allocated = 0;
ctx->polls_used = 0;
}
return ctx;
}
/**
* @brief Free a poll context.
*
* @param ctx Pointer to an already allocated poll context.
*/
void ssh_poll_ctx_free(ssh_poll_ctx ctx) {
if (ctx->polls_allocated > 0) {
register size_t i, used;
used = ctx->polls_used;
for (i = 0; i < used; ) {
ssh_poll_handle p = ctx->pollptrs[i];
int fd = ctx->pollfds[i].fd;
/* force poll object removal */
if (p->cb(p, fd, POLLERR, p->cb_data) < 0) {
used = ctx->polls_used;
} else {
i++;
}
}
SAFE_FREE(ctx->pollptrs);
SAFE_FREE(ctx->pollfds);
}
SAFE_FREE(ctx);
}
static int ssh_poll_ctx_resize(ssh_poll_ctx ctx, size_t new_size) {
ssh_poll_handle *pollptrs;
ssh_pollfd_t *pollfds;
pollptrs = realloc(ctx->pollptrs, sizeof(ssh_poll_handle *) * new_size);
if (pollptrs == NULL) {
return -1;
}
pollfds = realloc(ctx->pollfds, sizeof(ssh_pollfd_t) * new_size);
if (pollfds == NULL) {
ctx->pollptrs = realloc(pollptrs, sizeof(ssh_poll_handle *) * ctx->polls_allocated);
return -1;
}
ctx->pollptrs = pollptrs;
ctx->pollfds = pollfds;
ctx->polls_allocated = new_size;
return 0;
}
/**
* @brief Add a poll object to a poll context.
*
* @param ctx Pointer to an already allocated poll context.
* @param p Pointer to an already allocated poll object.
*
* @return 0 on success, < 0 on error
*/
int ssh_poll_ctx_add(ssh_poll_ctx ctx, ssh_poll_handle p) {
int fd;
if (p->ctx != NULL) {
/* already attached to a context */
return -1;
}
if (ctx->polls_used == ctx->polls_allocated &&
ssh_poll_ctx_resize(ctx, ctx->polls_allocated + ctx->chunk_size) < 0) {
return -1;
}
fd = p->x.fd;
p->x.idx = ctx->polls_used++;
ctx->pollptrs[p->x.idx] = p;
ctx->pollfds[p->x.idx].fd = fd;
ctx->pollfds[p->x.idx].events = p->events;
ctx->pollfds[p->x.idx].revents = 0;
p->ctx = ctx;
return 0;
}
/**
* @brief Remove a poll object from a poll context.
*
* @param ctx Pointer to an already allocated poll context.
* @param p Pointer to an already allocated poll object.
*/
void ssh_poll_ctx_remove(ssh_poll_ctx ctx, ssh_poll_handle p) {
size_t i;
i = p->x.idx;
p->x.fd = ctx->pollfds[i].fd;
p->ctx = NULL;
ctx->polls_used--;
/* fill the empty poll slot with the last one */
if (ctx->polls_used > 0 && ctx->polls_used != i) {
ctx->pollfds[i] = ctx->pollfds[ctx->polls_used];
ctx->pollptrs[i] = ctx->pollptrs[ctx->polls_used];
}
/* this will always leave at least chunk_size polls allocated */
if (ctx->polls_allocated - ctx->polls_used > ctx->chunk_size) {
ssh_poll_ctx_resize(ctx, ctx->polls_allocated - ctx->chunk_size);
}
}
/**
* @brief Poll all the sockets associated through a poll object with a
* poll context. If any of the events are set after the poll, the
* call back function of the socket will be called.
* This function should be called once within the programs main loop.
*
* @param ctx Pointer to an already allocated poll context.
* @param timeout An upper limit on the time for which ssh_poll_ctx() will
* block, in milliseconds. Specifying a negative value
* means an infinite timeout. This parameter is passed to
* the poll() function.
*/
int ssh_poll_ctx_dopoll(ssh_poll_ctx ctx, int timeout) {
int rc;
if (!ctx->polls_used)
return 0;
rc = ssh_poll(ctx->pollfds, ctx->polls_used, timeout);
if (rc > 0) {
register size_t i, used;
used = ctx->polls_used;
for (i = 0; i < used && rc > 0; ) {
if (!ctx->pollfds[i].revents) {
i++;
} else {
ssh_poll_handle p = ctx->pollptrs[i];
int fd = ctx->pollfds[i].fd;
int revents = ctx->pollfds[i].revents;
if (p->cb(p, fd, revents, p->cb_data) < 0) {
/* the poll was removed, reload the used counter and stall the loop */
used = ctx->polls_used;
} else {
ctx->pollfds[i].revents = 0;
i++;
}
rc--;
}
}
}
return rc;
}
|
zzlydm-fbbs
|
libssh/poll.c
|
C
|
gpl3
| 13,922
|
/*
* callbacks.c - callback functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include "libssh/callbacks.h"
#include "libssh/session.h"
int ssh_set_callbacks(ssh_session session, ssh_callbacks cb) {
if (session == NULL || cb == NULL) {
return -1;
}
session->callbacks = cb;
return 0;
}
|
zzlydm-fbbs
|
libssh/callbacks.c
|
C
|
gpl3
| 1,177
|
/*
* base64.c - support for base64 alphabet system, described in RFC1521
*
* This file is part of the SSH Library
*
* Copyright (c) 2005-2005 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/* just the dirtiest part of code i ever made */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "libssh/priv.h"
#include "libssh/buffer.h"
static char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
/* Transformations */
#define SET_A(n, i) do { (n) |= ((i) & 63) <<18; } while (0)
#define SET_B(n, i) do { (n) |= ((i) & 63) <<12; } while (0)
#define SET_C(n, i) do { (n) |= ((i) & 63) << 6; } while (0)
#define SET_D(n, i) do { (n) |= ((i) & 63); } while (0)
#define GET_A(n) (((n) & 0xff0000) >> 16)
#define GET_B(n) (((n) & 0xff00) >> 8)
#define GET_C(n) ((n) & 0xff)
static int _base64_to_bin(unsigned char dest[3], const char *source, int num);
static int get_equals(char *string);
/* First part: base64 to binary */
/**
* @internal
*
* @brief Translates a base64 string into a binary one.
*
* @returns A buffer containing the decoded string, NULL if something went
* wrong (e.g. incorrect char).
*/
ssh_buffer base64_to_bin(const char *source) {
ssh_buffer buffer = NULL;
unsigned char block[3];
char *base64;
char *ptr;
size_t len;
int equals;
base64 = strdup(source);
if (base64 == NULL) {
return NULL;
}
ptr = base64;
/* Get the number of equals signs, which mirrors the padding */
equals = get_equals(ptr);
if (equals > 2) {
SAFE_FREE(base64);
return NULL;
}
buffer = buffer_new();
if (buffer == NULL) {
SAFE_FREE(base64);
return NULL;
}
len = strlen(ptr);
while (len > 4) {
if (_base64_to_bin(block, ptr, 3) < 0) {
goto error;
}
if (buffer_add_data(buffer, block, 3) < 0) {
goto error;
}
len -= 4;
ptr += 4;
}
/*
* Depending on the number of bytes resting, there are 3 possibilities
* from the RFC.
*/
switch (len) {
/*
* (1) The final quantum of encoding input is an integral multiple of
* 24 bits. Here, the final unit of encoded output will be an integral
* multiple of 4 characters with no "=" padding
*/
case 4:
if (equals != 0) {
goto error;
}
if (_base64_to_bin(block, ptr, 3) < 0) {
goto error;
}
if (buffer_add_data(buffer, block, 3) < 0) {
goto error;
}
SAFE_FREE(base64);
return buffer;
/*
* (2) The final quantum of encoding input is exactly 8 bits; here, the
* final unit of encoded output will be two characters followed by
* two "=" padding characters.
*/
case 2:
if (equals != 2){
goto error;
}
if (_base64_to_bin(block, ptr, 1) < 0) {
goto error;
}
if (buffer_add_data(buffer, block, 1) < 0) {
goto error;
}
SAFE_FREE(base64);
return buffer;
/*
* The final quantum of encoding input is exactly 16 bits. Here, the final
* unit of encoded output will be three characters followed by one "="
* padding character.
*/
case 3:
if (equals != 1) {
goto error;
}
if (_base64_to_bin(block, ptr, 2) < 0) {
goto error;
}
if (buffer_add_data(buffer,block,2) < 0) {
goto error;
}
SAFE_FREE(base64);
return buffer;
default:
/* 4,3,2 are the only padding size allowed */
goto error;
}
error:
SAFE_FREE(base64);
buffer_free(buffer);
return NULL;
}
#define BLOCK(letter, n) do {ptr = strchr(alphabet, source[n]); \
if(!ptr) return -1; \
i = ptr - alphabet; \
SET_##letter(*block, i); \
} while(0)
/* Returns 0 if ok, -1 if not (ie invalid char into the stuff) */
static int to_block4(unsigned long *block, const char *source, int num) {
char *ptr;
unsigned int i;
*block = 0;
if (num < 1) {
return 0;
}
BLOCK(A, 0); /* 6 bit */
BLOCK(B,1); /* 12 bit */
if (num < 2) {
return 0;
}
BLOCK(C, 2); /* 18 bit */
if (num < 3) {
return 0;
}
BLOCK(D, 3); /* 24 bit */
return 0;
}
/* num = numbers of final bytes to be decoded */
static int _base64_to_bin(unsigned char dest[3], const char *source, int num) {
unsigned long block;
if (to_block4(&block, source, num) < 0) {
return -1;
}
dest[0] = GET_A(block);
dest[1] = GET_B(block);
dest[2] = GET_C(block);
return 0;
}
/* Count the number of "=" signs and replace them by zeroes */
static int get_equals(char *string) {
char *ptr = string;
int num = 0;
while ((ptr=strchr(ptr,'=')) != NULL) {
num++;
*ptr = '\0';
ptr++;
}
return num;
}
/* thanks sysk for debugging my mess :) */
#define BITS(n) ((1 << (n)) - 1)
static void _bin_to_base64(unsigned char *dest, const unsigned char source[3],
int len) {
switch (len) {
case 1:
dest[0] = alphabet[(source[0] >> 2)];
dest[1] = alphabet[((source[0] & BITS(2)) << 4)];
dest[2] = '=';
dest[3] = '=';
break;
case 2:
dest[0] = alphabet[source[0] >> 2];
dest[1] = alphabet[(source[1] >> 4) | ((source[0] & BITS(2)) << 4)];
dest[2] = alphabet[(source[1] & BITS(4)) << 2];
dest[3] = '=';
break;
case 3:
dest[0] = alphabet[(source[0] >> 2)];
dest[1] = alphabet[(source[1] >> 4) | ((source[0] & BITS(2)) << 4)];
dest[2] = alphabet[ (source[2] >> 6) | (source[1] & BITS(4)) << 2];
dest[3] = alphabet[source[2] & BITS(6)];
break;
}
}
/**
* @internal
*
* @brief Converts binary data to a base64 string.
*
* @returns the converted string
*/
unsigned char *bin_to_base64(const unsigned char *source, int len) {
unsigned char *base64;
unsigned char *ptr;
int flen = len + (3 - (len % 3)); /* round to upper 3 multiple */
flen = (4 * flen) / 3 + 1;
base64 = malloc(flen);
if (base64 == NULL) {
return NULL;
}
ptr = base64;
while(len > 0){
_bin_to_base64(ptr, source, len > 3 ? 3 : len);
ptr += 4;
source += 3;
len -= 3;
}
ptr[0] = '\0';
return base64;
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/base64.c
|
C
|
gpl3
| 7,084
|
/*
* server.c - functions for creating a SSH server
*
* This file is part of the SSH Library
*
* Copyright (c) 2004-2005 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/**
* \defgroup ssh_server SSH Server
* \addtogroup ssh_server
* @{
*/
#include "config.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "libssh/priv.h"
#include "libssh/libssh.h"
#include "libssh/server.h"
#include "libssh/ssh2.h"
#include "libssh/keyfiles.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/socket.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#include "libssh/misc.h"
#include "libssh/keys.h"
#include "libssh/dh.h"
#include "libssh/messages.h"
#ifdef _WIN32
#include <winsock2.h>
#define SOCKOPT_TYPE_ARG4 char
/* We need to provide hstrerror. Not we can't call the parameter h_errno because it's #defined */
static char *hstrerror(int h_errno_val) {
static char text[50] = {0};
snprintf(text, sizeof(text), "gethostbyname error %d\n", h_errno_val);
return text;
}
#else /* _WIN32 */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define SOCKOPT_TYPE_ARG4 int
#endif /* _WIN32 */
/* TODO FIXME: must use getaddrinfo */
static socket_t bind_socket(ssh_bind sshbind, const char *hostname,
int port) {
struct sockaddr_in myaddr;
struct hostent *hp=NULL;
socket_t s;
int opt = 1;
s = socket(PF_INET, SOCK_STREAM, 0);
if (s < 0) {
ssh_set_error(sshbind, SSH_FATAL, "%s", strerror(errno));
return -1;
}
#ifdef HAVE_GETHOSTBYNAME
hp = gethostbyname(hostname);
#endif
if (hp == NULL) {
ssh_set_error(sshbind, SSH_FATAL,
"Resolving %s: %s", hostname, hstrerror(h_errno));
close(s);
return -1;
}
memset(&myaddr, 0, sizeof(myaddr));
memcpy(&myaddr.sin_addr, hp->h_addr, hp->h_length);
myaddr.sin_family = hp->h_addrtype;
myaddr.sin_port = htons(port);
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0) {
ssh_set_error(sshbind, SSH_FATAL,
"Setting socket options failed: %s", hstrerror(h_errno));
close(s);
return -1;
}
if (bind(s, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) {
ssh_set_error(sshbind, SSH_FATAL, "Binding to %s:%d: %s",
hostname,
port,
strerror(errno));
close(s);
return -1;
}
return s;
}
ssh_bind ssh_bind_new(void) {
ssh_bind ptr;
ptr = malloc(sizeof(struct ssh_bind_struct));
if (ptr == NULL) {
return NULL;
}
ZERO_STRUCTP(ptr);
ptr->bindfd = -1;
ptr->bindport= 22;
ptr->log_verbosity = 0;
return ptr;
}
int ssh_bind_listen(ssh_bind sshbind) {
const char *host;
int fd;
if (ssh_init() < 0) {
return -1;
}
host = sshbind->bindaddr;
if (host == NULL) {
host = "0.0.0.0";
}
fd = bind_socket(sshbind, host, sshbind->bindport);
if (fd < 0) {
return -1;
}
sshbind->bindfd = fd;
if (listen(fd, 10) < 0) {
ssh_set_error(sshbind, SSH_FATAL,
"Listening to socket %d: %s",
fd, strerror(errno));
close(fd);
return -1;
}
return 0;
}
void ssh_bind_set_blocking(ssh_bind sshbind, int blocking) {
sshbind->blocking = blocking ? 1 : 0;
}
socket_t ssh_bind_get_fd(ssh_bind sshbind) {
return sshbind->bindfd;
}
void ssh_bind_set_fd(ssh_bind sshbind, socket_t fd) {
sshbind->bindfd = fd;
}
void ssh_bind_fd_toaccept(ssh_bind sshbind) {
sshbind->toaccept = 1;
}
int ssh_bind_accept(ssh_bind sshbind, ssh_session session) {
ssh_private_key dsa = NULL;
ssh_private_key rsa = NULL;
int fd = -1;
int i;
if (sshbind->bindfd < 0) {
ssh_set_error(sshbind, SSH_FATAL,
"Can't accept new clients on a not bound socket.");
return SSH_ERROR;
}
if(session == NULL){
ssh_set_error(sshbind, SSH_FATAL,"session is null");
return SSH_ERROR;
}
if (sshbind->dsakey == NULL && sshbind->rsakey == NULL) {
ssh_set_error(sshbind, SSH_FATAL,
"DSA or RSA host key file must be set before accept()");
return SSH_ERROR;
}
if (sshbind->dsakey) {
dsa = _privatekey_from_file(sshbind, sshbind->dsakey, TYPE_DSS);
if (dsa == NULL) {
return SSH_ERROR;
}
}
if (sshbind->rsakey) {
rsa = _privatekey_from_file(sshbind, sshbind->rsakey, TYPE_RSA);
if (rsa == NULL) {
privatekey_free(dsa);
return SSH_ERROR;
}
}
fd = accept(sshbind->bindfd, NULL, NULL);
if (fd < 0) {
ssh_set_error(sshbind, SSH_FATAL,
"Accepting a new connection: %s",
strerror(errno));
privatekey_free(dsa);
privatekey_free(rsa);
return SSH_ERROR;
}
session->server = 1;
session->version = 2;
/* copy options */
for (i = 0; i < 10; ++i) {
if (sshbind->wanted_methods[i]) {
session->wanted_methods[i] = strdup(sshbind->wanted_methods[i]);
if (session->wanted_methods[i] == NULL) {
privatekey_free(dsa);
privatekey_free(rsa);
return SSH_ERROR;
}
}
}
if (sshbind->bindaddr == NULL)
session->bindaddr = NULL;
else {
session->bindaddr = strdup(sshbind->bindaddr);
if (session->bindaddr == NULL) {
privatekey_free(dsa);
privatekey_free(rsa);
return SSH_ERROR;
}
}
session->log_verbosity = sshbind->log_verbosity;
ssh_socket_free(session->socket);
session->socket = ssh_socket_new(session);
if (session->socket == NULL) {
privatekey_free(dsa);
privatekey_free(rsa);
return SSH_ERROR;
}
ssh_socket_set_fd(session->socket, fd);
session->dsa_key = dsa;
session->rsa_key = rsa;
return SSH_OK;
}
void ssh_bind_free(ssh_bind sshbind){
int i;
if (sshbind == NULL) {
return;
}
if (sshbind->bindfd >= 0) {
#ifdef _WIN32
closesocket(sshbind->bindfd);
#else
close(sshbind->bindfd);
#endif
}
sshbind->bindfd = -1;
/* options */
SAFE_FREE(sshbind->banner);
SAFE_FREE(sshbind->dsakey);
SAFE_FREE(sshbind->rsakey);
SAFE_FREE(sshbind->bindaddr);
for (i = 0; i < 10; i++) {
if (sshbind->wanted_methods[i]) {
SAFE_FREE(sshbind->wanted_methods[i]);
}
}
SAFE_FREE(sshbind);
}
extern char *supported_methods[];
/** @internal
* This functions sets the Key Exchange protocols to be accepted
* by the server. They depend on
* -What the user asked (via options)
* -What is available (keys)
* It should then accept the intersection of what the user asked
* and what is available, and return an error if nothing matches
*/
static int server_set_kex(ssh_session session) {
KEX *server = &session->server_kex;
int i, j;
char *wanted;
ZERO_STRUCTP(server);
ssh_get_random(server->cookie, 16, 0);
if (session->dsa_key != NULL && session->rsa_key != NULL) {
if (ssh_options_set_algo(session, SSH_HOSTKEYS,
"ssh-dss,ssh-rsa") < 0) {
return -1;
}
} else if (session->dsa_key != NULL) {
if (ssh_options_set_algo(session, SSH_HOSTKEYS, "ssh-dss") < 0) {
return -1;
}
} else {
if (ssh_options_set_algo(session, SSH_HOSTKEYS, "ssh-rsa") < 0) {
return -1;
}
}
server->methods = malloc(10 * sizeof(char **));
if (server->methods == NULL) {
return -1;
}
for (i = 0; i < 10; i++) {
if ((wanted = session->wanted_methods[i]) == NULL) {
wanted = supported_methods[i];
}
server->methods[i] = strdup(wanted);
if (server->methods[i] == NULL) {
for (j = i - 1; j <= 0; j--) {
SAFE_FREE(server->methods[j]);
}
SAFE_FREE(server->methods);
return -1;
}
}
return 0;
}
static int dh_handshake_server(ssh_session session) {
ssh_string e;
ssh_string f;
ssh_string pubkey;
ssh_string sign;
ssh_public_key pub;
ssh_private_key prv;
if (packet_wait(session, SSH2_MSG_KEXDH_INIT, 1) != SSH_OK) {
return -1;
}
e = buffer_get_ssh_string(session->in_buffer);
if (e == NULL) {
ssh_set_error(session, SSH_FATAL, "No e number in client request");
return -1;
}
if (dh_import_e(session, e) < 0) {
ssh_set_error(session, SSH_FATAL, "Cannot import e number");
string_free(e);
return -1;
}
string_free(e);
if (dh_generate_y(session) < 0) {
ssh_set_error(session, SSH_FATAL, "Could not create y number");
return -1;
}
if (dh_generate_f(session) < 0) {
ssh_set_error(session, SSH_FATAL, "Could not create f number");
return -1;
}
f = dh_get_f(session);
if (f == NULL) {
ssh_set_error(session, SSH_FATAL, "Could not get the f number");
return -1;
}
switch(session->hostkeys){
case TYPE_DSS:
prv = session->dsa_key;
break;
case TYPE_RSA:
prv = session->rsa_key;
break;
default:
prv = NULL;
}
pub = publickey_from_privatekey(prv);
if (pub == NULL) {
ssh_set_error(session, SSH_FATAL,
"Could not get the public key from the private key");
string_free(f);
return -1;
}
pubkey = publickey_to_string(pub);
publickey_free(pub);
if (pubkey == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
string_free(f);
return -1;
}
dh_import_pubkey(session, pubkey);
if (dh_build_k(session) < 0) {
ssh_set_error(session, SSH_FATAL, "Could not import the public key");
string_free(f);
return -1;
}
if (make_sessionid(session) != SSH_OK) {
ssh_set_error(session, SSH_FATAL, "Could not create a session id");
string_free(f);
return -1;
}
sign = ssh_sign_session_id(session, prv);
if (sign == NULL) {
ssh_set_error(session, SSH_FATAL, "Could not sign the session id");
string_free(f);
return -1;
}
/* Free private keys as they should not be readable after this point */
if (session->rsa_key) {
privatekey_free(session->rsa_key);
session->rsa_key = NULL;
}
if (session->dsa_key) {
privatekey_free(session->dsa_key);
session->dsa_key = NULL;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_KEXDH_REPLY) < 0 ||
buffer_add_ssh_string(session->out_buffer, pubkey) < 0 ||
buffer_add_ssh_string(session->out_buffer, f) < 0 ||
buffer_add_ssh_string(session->out_buffer, sign) < 0) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
buffer_reinit(session->out_buffer);
string_free(f);
string_free(sign);
return -1;
}
string_free(f);
string_free(sign);
if (packet_send(session) != SSH_OK) {
return -1;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_NEWKEYS) < 0) {
buffer_reinit(session->out_buffer);
return -1;
}
if (packet_send(session) != SSH_OK) {
return -1;
}
ssh_log(session, SSH_LOG_PACKET, "SSH_MSG_NEWKEYS sent");
if (packet_wait(session, SSH2_MSG_NEWKEYS, 1) != SSH_OK) {
return -1;
}
ssh_log(session, SSH_LOG_PACKET, "Got SSH_MSG_NEWKEYS");
if (generate_session_keys(session) < 0) {
return -1;
}
/*
* Once we got SSH2_MSG_NEWKEYS we can switch next_crypto and
* current_crypto
*/
if (session->current_crypto) {
crypto_free(session->current_crypto);
}
/* FIXME TODO later, include a function to change keys */
session->current_crypto = session->next_crypto;
session->next_crypto = crypto_new();
if (session->next_crypto == NULL) {
return -1;
}
return 0;
}
/* Do the banner and key exchange */
int ssh_accept(ssh_session session) {
if (ssh_send_banner(session, 1) < 0) {
return -1;
}
session->alive = 1;
session->clientbanner = ssh_get_banner(session);
if (session->clientbanner == NULL) {
return -1;
}
if (server_set_kex(session) < 0) {
return -1;
}
if (ssh_send_kex(session, 1) < 0) {
return -1;
}
if (ssh_get_kex(session,1) < 0) {
return -1;
}
ssh_list_kex(session, &session->client_kex);
crypt_set_algorithms_server(session);
if (dh_handshake_server(session) < 0) {
return -1;
}
session->connected = 1;
return 0;
}
/**
* @brief Blocking write on channel for stderr.
*
* @param channel The channel to write to.
*
* @param data A pointer to the data to write.
*
* @param len The length of the buffer to write to.
*
* @return The number of bytes written, SSH_ERROR on error.
*
* @see channel_read()
*/
int channel_write_stderr(ssh_channel channel, const void *data, uint32_t len) {
return channel_write_common(channel, data, len, 1);
}
/* messages */
static int ssh_message_auth_reply_default(ssh_message msg,int partial) {
ssh_session session = msg->session;
char methods_c[128] = {0};
ssh_string methods = NULL;
int rc = SSH_ERROR;
enter_function();
if (buffer_add_u8(session->out_buffer, SSH2_MSG_USERAUTH_FAILURE) < 0) {
return rc;
}
if (session->auth_methods == 0) {
session->auth_methods = SSH_AUTH_METHOD_PUBLICKEY | SSH_AUTH_METHOD_PASSWORD;
}
if (session->auth_methods & SSH_AUTH_METHOD_PUBLICKEY) {
strcat(methods_c, "publickey,");
}
if (session->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) {
strcat(methods_c, "keyboard-interactive,");
}
if (session->auth_methods & SSH_AUTH_METHOD_PASSWORD) {
strcat(methods_c, "password,");
}
if (session->auth_methods & SSH_AUTH_METHOD_HOSTBASED) {
strcat(methods_c, "hostbased,");
}
/* Strip the comma. */
methods_c[strlen(methods_c) - 1] = '\0'; // strip the comma. We are sure there is at
ssh_log(session, SSH_LOG_PACKET,
"Sending a auth failure. methods that can continue: %s", methods_c);
methods = string_from_char(methods_c);
if (methods == NULL) {
goto error;
}
if (buffer_add_ssh_string(msg->session->out_buffer, methods) < 0) {
goto error;
}
if (partial) {
if (buffer_add_u8(session->out_buffer, 1) < 0) {
goto error;
}
} else {
if (buffer_add_u8(session->out_buffer, 0) < 0) {
goto error;
}
}
rc = packet_send(msg->session);
error:
string_free(methods);
leave_function();
return rc;
}
static int ssh_message_channel_request_open_reply_default(ssh_message msg) {
ssh_log(msg->session, SSH_LOG_FUNCTIONS, "Refusing a channel");
if (buffer_add_u8(msg->session->out_buffer
, SSH2_MSG_CHANNEL_OPEN_FAILURE) < 0) {
goto error;
}
if (buffer_add_u32(msg->session->out_buffer,
htonl(msg->channel_request_open.sender)) < 0) {
goto error;
}
if (buffer_add_u32(msg->session->out_buffer,
htonl(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) < 0) {
goto error;
}
/* reason is an empty string */
if (buffer_add_u32(msg->session->out_buffer, 0) < 0) {
goto error;
}
/* language too */
if (buffer_add_u32(msg->session->out_buffer, 0) < 0) {
goto error;
}
return packet_send(msg->session);
error:
return SSH_ERROR;
}
static int ssh_message_channel_request_reply_default(ssh_message msg) {
uint32_t channel;
if (msg->channel_request.want_reply) {
channel = msg->channel_request.channel->remote_channel;
ssh_log(msg->session, SSH_LOG_PACKET,
"Sending a default channel_request denied to channel %d", channel);
if (buffer_add_u8(msg->session->out_buffer, SSH2_MSG_CHANNEL_FAILURE) < 0) {
return SSH_ERROR;
}
if (buffer_add_u32(msg->session->out_buffer, htonl(channel)) < 0) {
return SSH_ERROR;
}
return packet_send(msg->session);
}
ssh_log(msg->session, SSH_LOG_PACKET,
"The client doesn't want to know the request failed!");
return SSH_OK;
}
static int ssh_message_service_request_reply_default(ssh_message msg) {
/* The only return code accepted by specifications are success or disconnect */
return ssh_message_service_reply_success(msg);
}
int ssh_message_service_reply_success(ssh_message msg) {
struct ssh_string_struct *service;
ssh_session session=msg->session;
if (msg == NULL) {
return SSH_ERROR;
}
ssh_log(session, SSH_LOG_PACKET,
"Sending a SERVICE_ACCEPT for service %s", msg->service_request.service);
if (buffer_add_u8(session->out_buffer, SSH2_MSG_SERVICE_ACCEPT) < 0) {
return -1;
}
service=string_from_char(msg->service_request.service);
if (buffer_add_ssh_string(session->out_buffer, service) < 0) {
string_free(service);
return -1;
}
string_free(service);
return packet_send(msg->session);
}
int ssh_message_reply_default(ssh_message msg) {
if (msg == NULL) {
return -1;
}
switch(msg->type) {
case SSH_REQUEST_AUTH:
return ssh_message_auth_reply_default(msg, 0);
case SSH_REQUEST_CHANNEL_OPEN:
return ssh_message_channel_request_open_reply_default(msg);
case SSH_REQUEST_CHANNEL:
return ssh_message_channel_request_reply_default(msg);
case SSH_REQUEST_SERVICE:
return ssh_message_service_request_reply_default(msg);
default:
ssh_log(msg->session, SSH_LOG_PACKET,
"Don't know what to default reply to %d type",
msg->type);
break;
}
return -1;
}
char *ssh_message_service_service(ssh_message msg){
if (msg == NULL) {
return NULL;
}
return msg->service_request.service;
}
char *ssh_message_auth_user(ssh_message msg) {
if (msg == NULL) {
return NULL;
}
return msg->auth_request.username;
}
char *ssh_message_auth_password(ssh_message msg){
if (msg == NULL) {
return NULL;
}
return msg->auth_request.password;
}
/* Get the publickey of an auth request */
ssh_public_key ssh_message_auth_publickey(ssh_message msg){
if (msg == NULL) {
return NULL;
}
return msg->auth_request.public_key;
}
int ssh_message_auth_set_methods(ssh_message msg, int methods) {
if (msg == NULL || msg->session == NULL) {
return -1;
}
msg->session->auth_methods = methods;
return 0;
}
int ssh_message_auth_reply_success(ssh_message msg, int partial) {
if (msg == NULL) {
return SSH_ERROR;
}
if (partial) {
return ssh_message_auth_reply_default(msg, partial);
}
if (buffer_add_u8(msg->session->out_buffer,SSH2_MSG_USERAUTH_SUCCESS) < 0) {
return SSH_ERROR;
}
return packet_send(msg->session);
}
/* Answer OK to a pubkey auth request */
int ssh_message_auth_reply_pk_ok(ssh_message msg, ssh_string algo, ssh_string pubkey) {
if (msg == NULL) {
return SSH_ERROR;
}
if (buffer_add_u8(msg->session->out_buffer, SSH2_MSG_USERAUTH_PK_OK) < 0 ||
buffer_add_ssh_string(msg->session->out_buffer, algo) < 0 ||
buffer_add_ssh_string(msg->session->out_buffer, pubkey) < 0) {
return SSH_ERROR;
}
return packet_send(msg->session);
}
char *ssh_message_channel_request_open_originator(ssh_message msg){
return msg->channel_request_open.originator;
}
int ssh_message_channel_request_open_originator_port(ssh_message msg){
return msg->channel_request_open.originator_port;
}
char *ssh_message_channel_request_open_destination(ssh_message msg){
return msg->channel_request_open.destination;
}
int ssh_message_channel_request_open_destination_port(ssh_message msg){
return msg->channel_request_open.destination_port;
}
ssh_channel ssh_message_channel_request_channel(ssh_message msg){
return msg->channel_request.channel;
}
char *ssh_message_channel_request_pty_term(ssh_message msg){
return msg->channel_request.TERM;
}
int ssh_message_channel_request_pty_width(ssh_message msg){
return msg->channel_request.width;
}
int ssh_message_channel_request_pty_height(ssh_message msg){
return msg->channel_request.height;
}
int ssh_message_channel_request_pty_pxwidth(ssh_message msg){
return msg->channel_request.pxwidth;
}
int ssh_message_channel_request_pty_pxheight(ssh_message msg){
return msg->channel_request.pxheight;
}
char *ssh_message_channel_request_env_name(ssh_message msg){
return msg->channel_request.var_name;
}
char *ssh_message_channel_request_env_value(ssh_message msg){
return msg->channel_request.var_value;
}
char *ssh_message_channel_request_command(ssh_message msg){
return msg->channel_request.command;
}
char *ssh_message_channel_request_subsystem(ssh_message msg){
return msg->channel_request.subsystem;
}
/** @brief defines the SSH_MESSAGE callback
* @param session the current ssh session
* @param ssh_message_callback a function pointer to a callback taking the
* current ssh session and received message as parameters. the function returns
* 0 if the message has been parsed and treated sucessfuly, 1 otherwise (libssh
* must take care of the response).
*/
void ssh_set_message_callback(ssh_session session,
int(*ssh_message_callback)(ssh_session session, ssh_message msg)){
session->ssh_message_callback=ssh_message_callback;
}
int ssh_execute_message_callbacks(ssh_session session){
ssh_message msg=NULL;
int ret;
if(!session->ssh_message_list)
return SSH_OK;
if(session->ssh_message_callback){
while((msg=ssh_list_pop_head(ssh_message , session->ssh_message_list)) != NULL){
ret=session->ssh_message_callback(session,msg);
if(ret==1){
ret = ssh_message_reply_default(msg);
if(ret != SSH_OK)
return ret;
}
}
} else {
while((msg=ssh_list_pop_head(ssh_message , session->ssh_message_list)) != NULL){
ret = ssh_message_reply_default(msg);
if(ret != SSH_OK)
return ret;
}
}
return SSH_OK;
}
/** @}
*/
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/server.c
|
C
|
gpl3
| 21,927
|
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/* pcap.c */
/** \defgroup ssh_pcap SSH-pcap
* \brief libssh pcap file generation
*
* \addtogroup ssh_pcap
* @{ */
#include "config.h"
#ifdef WITH_PCAP
#include <stdio.h>
#ifdef _WIN32
#include <ws2tcpip.h>
#else
#include <sys/time.h>
#include <sys/socket.h>
#endif
#include <errno.h>
#include "libssh/libssh.h"
#include "libssh/pcap.h"
#include "libssh/session.h"
#include "libssh/buffer.h"
#include "libssh/socket.h"
/* The header of a pcap file is the following. We are not going to make it
* very complicated.
* Just for information.
*/
struct pcap_hdr_s {
uint32_t magic_number; /* magic number */
uint16_t version_major; /* major version number */
uint16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length of captured packets, in octets */
uint32_t network; /* data link type */
};
#define PCAP_MAGIC 0xa1b2c3d4
#define PCAP_VERSION_MAJOR 2
#define PCAP_VERSION_MINOR 4
#define DLT_RAW 12 /* raw IP */
/* TCP flags */
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
/* The header of a pcap packet.
* Just for information.
*/
struct pcaprec_hdr_s {
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
};
/** @private
* @brief a pcap context expresses the state of a pcap dump
* in a SSH session only. Multiple pcap contexts may be used into
* a single pcap file.
*/
struct ssh_pcap_context_struct {
ssh_session session;
ssh_pcap_file file;
int connected;
/* All of these information are useful to generate
* the dummy IP and TCP packets
*/
uint32_t ipsource;
uint32_t ipdest;
uint16_t portsource;
uint16_t portdest;
uint32_t outsequence;
uint32_t insequence;
};
/** @private
* @brief a pcap file expresses the state of a pcap file which may
* contain several streams.
*/
struct ssh_pcap_file_struct {
FILE *output;
uint16_t ipsequence;
};
/**
* @brief create a new ssh_pcap_file object
*/
ssh_pcap_file ssh_pcap_file_new(){
return malloc(sizeof(struct ssh_pcap_file_struct));
}
/** @internal
* @brief writes a packet on file
*/
static int ssh_pcap_file_write(ssh_pcap_file pcap, ssh_buffer packet){
int err;
uint32_t len;
if(pcap == NULL || pcap->output==NULL)
return SSH_ERROR;
len=buffer_get_len(packet);
err=fwrite(buffer_get(packet),len,1,pcap->output);
if(err<0)
return SSH_ERROR;
else
return SSH_OK;
}
/** @internal
* @brief prepends a packet with the pcap header and writes packet
* on file
*/
int ssh_pcap_file_write_packet(ssh_pcap_file pcap, ssh_buffer packet, uint32_t original_len){
ssh_buffer header=buffer_new();
struct timeval now;
int err;
if(header == NULL)
return SSH_ERROR;
gettimeofday(&now,NULL);
buffer_add_u32(header,htonl(now.tv_sec));
buffer_add_u32(header,htonl(now.tv_usec));
buffer_add_u32(header,htonl(buffer_get_len(packet)));
buffer_add_u32(header,htonl(original_len));
buffer_add_buffer(header,packet);
err=ssh_pcap_file_write(pcap,header);
buffer_free(header);
return err;
}
/**
* @brief opens a new pcap file and create header
*/
int ssh_pcap_file_open(ssh_pcap_file pcap, const char *filename){
ssh_buffer header;
int err;
if(pcap == NULL)
return SSH_ERROR;
if(pcap->output){
fclose(pcap->output);
pcap->output=NULL;
}
pcap->output=fopen(filename,"wb");
if(pcap->output==NULL)
return SSH_ERROR;
header=buffer_new();
if(header==NULL)
return SSH_ERROR;
buffer_add_u32(header,htonl(PCAP_MAGIC));
buffer_add_u16(header,htons(PCAP_VERSION_MAJOR));
buffer_add_u16(header,htons(PCAP_VERSION_MINOR));
/* currently hardcode GMT to 0 */
buffer_add_u32(header,htonl(0));
/* accuracy */
buffer_add_u32(header,htonl(0));
/* size of the biggest packet */
buffer_add_u32(header,htonl(MAX_PACKET_LEN));
/* we will write sort-of IP */
buffer_add_u32(header,htonl(DLT_RAW));
err=ssh_pcap_file_write(pcap,header);
buffer_free(header);
return err;
}
int ssh_pcap_file_close(ssh_pcap_file pcap){
int err;
if(pcap ==NULL || pcap->output==NULL)
return SSH_ERROR;
err=fclose(pcap->output);
pcap->output=NULL;
if(err != 0)
return SSH_ERROR;
else
return SSH_OK;
}
void ssh_pcap_file_free(ssh_pcap_file pcap){
ssh_pcap_file_close(pcap);
SAFE_FREE(pcap);
}
/** @internal
* @brief allocates a new ssh_pcap_context object
*/
ssh_pcap_context ssh_pcap_context_new(ssh_session session){
ssh_pcap_context ctx=malloc(sizeof(struct ssh_pcap_context_struct));
if(ctx==NULL){
ssh_set_error_oom(session);
return NULL;
}
ZERO_STRUCTP(ctx);
ctx->session=session;
return ctx;
}
void ssh_pcap_context_free(ssh_pcap_context ctx){
SAFE_FREE(ctx);
}
void ssh_pcap_context_set_file(ssh_pcap_context ctx, ssh_pcap_file pcap){
ctx->file=pcap;
}
/** @internal
* @brief sets the IP and port parameters in the connection
*/
static int ssh_pcap_context_connect(ssh_pcap_context ctx){
ssh_session session=ctx->session;
struct sockaddr_in local, remote;
socket_t fd;
socklen_t len;
if(session==NULL)
return SSH_ERROR;
if(session->socket==NULL)
return SSH_ERROR;
fd=ssh_socket_get_fd(session->socket);
/* TODO: adapt for windows */
if(fd<0)
return SSH_ERROR;
len=sizeof(local);
if(getsockname(fd,(struct sockaddr *)&local,&len)<0){
ssh_set_error(session,SSH_REQUEST_DENIED,"Getting local IP address: %s",strerror(errno));
return SSH_ERROR;
}
len=sizeof(remote);
if(getpeername(fd,(struct sockaddr *)&remote,&len)<0){
ssh_set_error(session,SSH_REQUEST_DENIED,"Getting remote IP address: %s",strerror(errno));
return SSH_ERROR;
}
if(local.sin_family != AF_INET){
ssh_set_error(session,SSH_REQUEST_DENIED,"Only IPv4 supported for pcap logging");
return SSH_ERROR;
}
memcpy(&ctx->ipsource,&local.sin_addr,sizeof(ctx->ipsource));
memcpy(&ctx->ipdest,&remote.sin_addr,sizeof(ctx->ipdest));
memcpy(&ctx->portsource,&local.sin_port,sizeof(ctx->portsource));
memcpy(&ctx->portdest,&remote.sin_port,sizeof(ctx->portdest));
ctx->connected=1;
return SSH_OK;
}
#define IPHDR_LEN 20
#define TCPHDR_LEN 20
#define TCPIPHDR_LEN (IPHDR_LEN + TCPHDR_LEN)
/** @internal
* @brief write a SSH packet as a TCP over IP in a pcap file
* @param ctx open pcap context
* @param direction SSH_PCAP_DIRECTION_IN if the packet has been received
* @param direction SSH_PCAP_DIRECTION_OUT if the packet has been emitted
* @param data pointer to the data to write
* @param len data to write in the pcap file. May be smaller than origlen.
* @param origlen number of bytes of complete data.
* @returns SSH_OK write is successful
* @returns SSH_ERROR an error happened.
*/
int ssh_pcap_context_write(ssh_pcap_context ctx,enum ssh_pcap_direction direction
, void *data, uint32_t len, uint32_t origlen){
ssh_buffer ip;
int err;
if(ctx==NULL || ctx->file ==NULL)
return SSH_ERROR;
if(ctx->connected==0)
if(ssh_pcap_context_connect(ctx)==SSH_ERROR)
return SSH_ERROR;
ip=buffer_new();
if(ip==NULL){
ssh_set_error_oom(ctx->session);
return SSH_ERROR;
}
/* build an IP packet */
/* V4, 20 bytes */
buffer_add_u8(ip,4 << 4 | 5);
/* tos */
buffer_add_u8(ip,0);
/* total len */
buffer_add_u16(ip,htons(origlen + TCPIPHDR_LEN));
/* IP id number */
buffer_add_u16(ip,htons(ctx->file->ipsequence));
ctx->file->ipsequence++;
/* fragment offset */
buffer_add_u16(ip,htons(0));
/* TTL */
buffer_add_u8(ip,64);
/* protocol TCP=6 */
buffer_add_u8(ip,6);
/* checksum */
buffer_add_u16(ip,0);
if(direction==SSH_PCAP_DIR_OUT){
buffer_add_u32(ip,ctx->ipsource);
buffer_add_u32(ip,ctx->ipdest);
} else {
buffer_add_u32(ip,ctx->ipdest);
buffer_add_u32(ip,ctx->ipsource);
}
/* TCP */
if(direction==SSH_PCAP_DIR_OUT){
buffer_add_u16(ip,ctx->portsource);
buffer_add_u16(ip,ctx->portdest);
} else {
buffer_add_u16(ip,ctx->portdest);
buffer_add_u16(ip,ctx->portsource);
}
/* sequence number */
if(direction==SSH_PCAP_DIR_OUT){
buffer_add_u32(ip,ntohl(ctx->outsequence));
ctx->outsequence+=origlen;
} else {
buffer_add_u32(ip,ntohl(ctx->insequence));
ctx->insequence+=origlen;
}
/* ack number */
if(direction==SSH_PCAP_DIR_OUT){
buffer_add_u32(ip,ntohl(ctx->insequence));
} else {
buffer_add_u32(ip,ntohl(ctx->outsequence));
}
/* header len = 20 = 5 * 32 bits, at offset 4*/
buffer_add_u8(ip,5 << 4);
/* flags */
buffer_add_u8(ip,TH_PUSH | TH_ACK);
/* window */
buffer_add_u16(ip,htons(65535));
/* checksum */
buffer_add_u16(ip,htons(0));
/* urgent data ptr */
buffer_add_u16(ip,0);
/* actual data */
buffer_add_data(ip,data,len);
err=ssh_pcap_file_write_packet(ctx->file,ip,origlen + TCPIPHDR_LEN);
buffer_free(ip);
return err;
}
/** @brief sets the pcap file used to trace the session
* @param current session
* @param pcap an handler to a pcap file. A pcap file may be used in several
* sessions.
* @returns SSH_ERROR in case of error, SSH_OK otherwise.
*/
int ssh_set_pcap_file(ssh_session session, ssh_pcap_file pcap){
ssh_pcap_context ctx=ssh_pcap_context_new(session);
if(ctx==NULL){
ssh_set_error_oom(session);
return SSH_ERROR;
}
ctx->file=pcap;
if(session->pcap_ctx)
ssh_pcap_context_free(session->pcap_ctx);
session->pcap_ctx=ctx;
return SSH_OK;
}
#endif /* WITH_PCAP */
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/pcap.c
|
C
|
gpl3
| 10,413
|
/*
* channels.c - SSH channel functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2008 by Aris Adamantiadis
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/socket.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#include "libssh/misc.h"
#include "libssh/messages.h"
#define WINDOWBASE 128000
#define WINDOWLIMIT (WINDOWBASE/2)
/**
* @defgroup ssh_channel SSH Channels
* @brief Functions that manage a channel.
*/
/**
* @addtogroup ssh_channel
* @{
*/
/**
* @brief Allocate a new channel.
*
* @param session The ssh session to use.
*
* @return A pointer to a newly allocated channel, NULL on error.
*/
ssh_channel channel_new(ssh_session session) {
ssh_channel channel = NULL;
channel = malloc(sizeof(struct ssh_channel_struct));
if (channel == NULL) {
return NULL;
}
memset(channel,0,sizeof(struct ssh_channel_struct));
channel->stdout_buffer = buffer_new();
if (channel->stdout_buffer == NULL) {
SAFE_FREE(channel);
return NULL;
}
channel->stderr_buffer = buffer_new();
if (channel->stderr_buffer == NULL) {
buffer_free(channel->stdout_buffer);
SAFE_FREE(channel);
return NULL;
}
channel->session = session;
channel->version = session->version;
channel->exit_status = -1;
if(session->channels == NULL) {
session->channels = channel;
channel->next = channel->prev = channel;
return channel;
}
channel->next = session->channels;
channel->prev = session->channels->prev;
channel->next->prev = channel;
channel->prev->next = channel;
return channel;
}
/**
* @internal
*
* @brief Create a new channel identifier.
*
* @param session The SSH session to use.
*
* @return The new channel identifier.
*/
uint32_t ssh_channel_new_id(ssh_session session) {
return ++(session->maxchannel);
}
static int channel_open(ssh_channel channel, const char *type_c, int window,
int maxpacket, ssh_buffer payload) {
ssh_session session = channel->session;
ssh_string type = NULL;
uint32_t tmp = 0;
enter_function();
channel->local_channel = ssh_channel_new_id(session);
channel->local_maxpacket = maxpacket;
channel->local_window = window;
ssh_log(session, SSH_LOG_RARE,
"Creating a channel %d with %d window and %d max packet",
channel->local_channel, window, maxpacket);
type = string_from_char(type_c);
if (type == NULL) {
leave_function();
return -1;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_CHANNEL_OPEN) < 0 ||
buffer_add_ssh_string(session->out_buffer,type) < 0 ||
buffer_add_u32(session->out_buffer, htonl(channel->local_channel)) < 0 ||
buffer_add_u32(session->out_buffer, htonl(channel->local_window)) < 0 ||
buffer_add_u32(session->out_buffer, htonl(channel->local_maxpacket)) < 0) {
string_free(type);
leave_function();
return -1;
}
string_free(type);
if (payload != NULL) {
if (buffer_add_buffer(session->out_buffer, payload) < 0) {
leave_function();
return -1;
}
}
if (packet_send(session) != SSH_OK) {
leave_function();
return -1;
}
ssh_log(session, SSH_LOG_RARE,
"Sent a SSH_MSG_CHANNEL_OPEN type %s for channel %d",
type_c, channel->local_channel);
if (packet_wait(session, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, 1) != SSH_OK) {
leave_function();
return -1;
}
switch(session->in_packet.type) {
case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
buffer_get_u32(session->in_buffer, &tmp);
if (channel->local_channel != ntohl(tmp)) {
ssh_set_error(session, SSH_FATAL,
"Server answered with sender channel number %lu instead of given %u",
(long unsigned int) ntohl(tmp),
channel->local_channel);
leave_function();
return -1;
}
buffer_get_u32(session->in_buffer, &tmp);
channel->remote_channel = ntohl(tmp);
buffer_get_u32(session->in_buffer, &tmp);
channel->remote_window = ntohl(tmp);
buffer_get_u32(session->in_buffer,&tmp);
channel->remote_maxpacket=ntohl(tmp);
ssh_log(session, SSH_LOG_PROTOCOL,
"Received a CHANNEL_OPEN_CONFIRMATION for channel %d:%d",
channel->local_channel,
channel->remote_channel);
ssh_log(session, SSH_LOG_PROTOCOL,
"Remote window : %lu, maxpacket : %lu",
(long unsigned int) channel->remote_window,
(long unsigned int) channel->remote_maxpacket);
channel->open = 1;
leave_function();
return 0;
case SSH2_MSG_CHANNEL_OPEN_FAILURE:
{
ssh_string error_s;
char *error;
uint32_t code;
buffer_get_u32(session->in_buffer, &tmp);
buffer_get_u32(session->in_buffer, &code);
error_s = buffer_get_ssh_string(session->in_buffer);
error = string_to_char(error_s);
string_free(error_s);
if (error == NULL) {
leave_function();
return -1;
}
ssh_set_error(session, SSH_REQUEST_DENIED,
"Channel opening failure: channel %u error (%lu) %s",
channel->local_channel,
(long unsigned int) ntohl(code),
error);
SAFE_FREE(error);
leave_function();
return -1;
}
default:
ssh_set_error(session, SSH_FATAL,
"Received unknown packet %d\n", session->in_packet.type);
leave_function();
return -1;
}
leave_function();
return -1;
}
/* get ssh channel from local session? */
ssh_channel ssh_channel_from_local(ssh_session session, uint32_t id) {
ssh_channel initchan = session->channels;
ssh_channel channel;
/* We assume we are always the local */
if (initchan == NULL) {
return NULL;
}
for (channel = initchan; channel->local_channel != id;
channel=channel->next) {
if (channel->next == initchan) {
return NULL;
}
}
return channel;
}
static int grow_window(ssh_session session, ssh_channel channel, int minimumsize) {
uint32_t new_window = minimumsize > WINDOWBASE ? minimumsize : WINDOWBASE;
enter_function();
if (buffer_add_u8(session->out_buffer, SSH2_MSG_CHANNEL_WINDOW_ADJUST) < 0 ||
buffer_add_u32(session->out_buffer, htonl(channel->remote_channel)) < 0 ||
buffer_add_u32(session->out_buffer, htonl(new_window)) < 0) {
goto error;
}
if (packet_send(session) != SSH_OK) {
/* FIXME should we fail here or not? */
leave_function();
return 1;
}
ssh_log(session, SSH_LOG_PROTOCOL,
"growing window (channel %d:%d) to %d bytes",
channel->local_channel,
channel->remote_channel,
channel->local_window + new_window);
channel->local_window += new_window;
leave_function();
return 0;
error:
buffer_reinit(session->out_buffer);
leave_function();
return -1;
}
static ssh_channel channel_from_msg(ssh_session session) {
ssh_channel channel;
uint32_t chan;
if (buffer_get_u32(session->in_buffer, &chan) != sizeof(uint32_t)) {
ssh_set_error(session, SSH_FATAL,
"Getting channel from message: short read");
return NULL;
}
channel = ssh_channel_from_local(session, ntohl(chan));
if (channel == NULL) {
ssh_set_error(session, SSH_FATAL,
"Server specified invalid channel %lu",
(long unsigned int) ntohl(chan));
}
return channel;
}
static void channel_rcv_change_window(ssh_session session) {
ssh_channel channel;
uint32_t bytes;
int rc;
enter_function();
channel = channel_from_msg(session);
if (channel == NULL) {
ssh_log(session, SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));
}
rc = buffer_get_u32(session->in_buffer, &bytes);
if (channel == NULL || rc != sizeof(uint32_t)) {
ssh_log(session, SSH_LOG_PACKET,
"Error getting a window adjust message: invalid packet");
leave_function();
return;
}
bytes = ntohl(bytes);
ssh_log(session, SSH_LOG_PROTOCOL,
"Adding %d bytes to channel (%d:%d) (from %d bytes)",
bytes,
channel->local_channel,
channel->remote_channel,
channel->remote_window);
channel->remote_window += bytes;
leave_function();
}
/* is_stderr is set to 1 if the data are extended, ie stderr */
static void channel_rcv_data(ssh_session session,int is_stderr) {
ssh_channel channel;
ssh_string str;
size_t len;
enter_function();
channel = channel_from_msg(session);
if (channel == NULL) {
ssh_log(session, SSH_LOG_FUNCTIONS,
"%s", ssh_get_error(session));
leave_function();
return;
}
if (is_stderr) {
uint32_t ignore;
/* uint32 data type code. we can ignore it */
buffer_get_u32(session->in_buffer, &ignore);
}
str = buffer_get_ssh_string(session->in_buffer);
if (str == NULL) {
ssh_log(session, SSH_LOG_PACKET, "Invalid data packet!");
leave_function();
return;
}
len = string_len(str);
ssh_log(session, SSH_LOG_PROTOCOL,
"Channel receiving %zu bytes data in %d (local win=%d remote win=%d)",
len,
is_stderr,
channel->local_window,
channel->remote_window);
/* What shall we do in this case? Let's accept it anyway */
if (len > channel->local_window) {
ssh_log(session, SSH_LOG_RARE,
"Data packet too big for our window(%zu vs %d)",
len,
channel->local_window);
}
if (channel_default_bufferize(channel, string_data(str), len,
is_stderr) < 0) {
string_free(str);
leave_function();
return;
}
if (len <= channel->local_window) {
channel->local_window -= len;
} else {
channel->local_window = 0; /* buggy remote */
}
ssh_log(session, SSH_LOG_PROTOCOL,
"Channel windows are now (local win=%d remote win=%d)",
channel->local_window,
channel->remote_window);
string_free(str);
leave_function();
}
static void channel_rcv_eof(ssh_session session) {
ssh_channel channel;
enter_function();
channel = channel_from_msg(session);
if (channel == NULL) {
ssh_log(session, SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));
leave_function();
return;
}
ssh_log(session, SSH_LOG_PACKET,
"Received eof on channel (%d:%d)",
channel->local_channel,
channel->remote_channel);
/* channel->remote_window = 0; */
channel->remote_eof = 1;
leave_function();
}
static void channel_rcv_close(ssh_session session) {
ssh_channel channel;
enter_function();
channel = channel_from_msg(session);
if (channel == NULL) {
ssh_log(session, SSH_LOG_FUNCTIONS, "%s", ssh_get_error(session));
leave_function();
return;
}
ssh_log(session, SSH_LOG_PACKET,
"Received close on channel (%d:%d)",
channel->local_channel,
channel->remote_channel);
if ((channel->stdout_buffer &&
buffer_get_rest_len(channel->stdout_buffer) > 0) ||
(channel->stderr_buffer &&
buffer_get_rest_len(channel->stderr_buffer) > 0)) {
channel->delayed_close = 1;
} else {
channel->open = 0;
}
if (channel->remote_eof == 0) {
ssh_log(session, SSH_LOG_PACKET,
"Remote host not polite enough to send an eof before close");
}
channel->remote_eof = 1;
/*
* The remote eof doesn't break things if there was still data into read
* buffer because the eof is ignored until the buffer is empty.
*/
leave_function();
}
static void channel_rcv_request(ssh_session session) {
ssh_channel channel;
ssh_string request_s;
char *request;
uint32_t status;
uint32_t startpos = session->in_buffer->pos;
enter_function();
channel = channel_from_msg(session);
if (channel == NULL) {
ssh_log(session, SSH_LOG_FUNCTIONS,"%s", ssh_get_error(session));
leave_function();
return;
}
request_s = buffer_get_ssh_string(session->in_buffer);
if (request_s == NULL) {
ssh_log(session, SSH_LOG_PACKET, "Invalid MSG_CHANNEL_REQUEST");
leave_function();
return;
}
request = string_to_char(request_s);
string_free(request_s);
if (request == NULL) {
leave_function();
return;
}
buffer_get_u8(session->in_buffer, (uint8_t *) &status);
if (strcmp(request,"exit-status") == 0) {
SAFE_FREE(request);
ssh_log(session, SSH_LOG_PACKET, "received exit-status");
buffer_get_u32(session->in_buffer, &status);
channel->exit_status = ntohl(status);
leave_function();
return ;
}
if (strcmp(request, "exit-signal") == 0) {
const char *core = "(core dumped)";
ssh_string signal_s;
char *signal;
uint8_t i;
SAFE_FREE(request);
signal_s = buffer_get_ssh_string(session->in_buffer);
if (signal_s == NULL) {
ssh_log(session, SSH_LOG_PACKET, "Invalid MSG_CHANNEL_REQUEST");
leave_function();
return;
}
signal = string_to_char(signal_s);
string_free(signal_s);
if (signal == NULL) {
leave_function();
return;
}
buffer_get_u8(session->in_buffer, &i);
if (i == 0) {
core = "";
}
ssh_log(session, SSH_LOG_PACKET,
"Remote connection closed by signal SIG %s %s", signal, core);
SAFE_FREE(signal);
leave_function();
return;
}
if(strcmp(request,"keepalive@openssh.com")==0){
SAFE_FREE(request);
ssh_log(session, SSH_LOG_PROTOCOL,"Responding to Openssh's keepalive");
buffer_add_u8(session->out_buffer, SSH2_MSG_CHANNEL_SUCCESS);
buffer_add_u32(session->out_buffer, htonl(channel->remote_channel));
packet_send(session);
leave_function();
return;
}
/* TODO call message_handle since it handles channel requests as messages */
/* *but* reset buffer before !! */
session->in_buffer->pos = startpos;
message_handle(session, SSH2_MSG_CHANNEL_REQUEST);
ssh_log(session, SSH_LOG_PACKET, "Unknown request %s", request);
SAFE_FREE(request);
leave_function();
}
/*
* channel_handle() is called by packet_wait(), for example when there is
* channel information to handle.
*/
void channel_handle(ssh_session session, int type){
enter_function();
ssh_log(session, SSH_LOG_PROTOCOL, "Channel_handle(%d)", type);
switch(type) {
case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
channel_rcv_change_window(session);
break;
case SSH2_MSG_CHANNEL_DATA:
channel_rcv_data(session,0);
break;
case SSH2_MSG_CHANNEL_EXTENDED_DATA:
channel_rcv_data(session,1);
break;
case SSH2_MSG_CHANNEL_EOF:
channel_rcv_eof(session);
break;
case SSH2_MSG_CHANNEL_CLOSE:
channel_rcv_close(session);
break;
case SSH2_MSG_CHANNEL_REQUEST:
channel_rcv_request(session);
break;
default:
ssh_log(session, SSH_LOG_FUNCTIONS,
"Unexpected message %d", type);
}
leave_function();
}
/*
* When data has been received from the ssh server, it can be applied to the
* known user function, with help of the callback, or inserted here
*
* FIXME is the window changed?
*/
int channel_default_bufferize(ssh_channel channel, void *data, int len,
int is_stderr) {
ssh_session session = channel->session;
ssh_log(session, SSH_LOG_RARE,
"placing %d bytes into channel buffer (stderr=%d)", len, is_stderr);
if (is_stderr == 0) {
/* stdout */
if (channel->stdout_buffer == NULL) {
channel->stdout_buffer = buffer_new();
if (channel->stdout_buffer == NULL) {
ssh_set_error_oom(session);
return -1;
}
}
if (buffer_add_data(channel->stdout_buffer, data, len) < 0) {
buffer_free(channel->stdout_buffer);
channel->stdout_buffer = NULL;
return -1;
}
} else {
/* stderr */
if (channel->stderr_buffer == NULL) {
channel->stderr_buffer = buffer_new();
if (channel->stderr_buffer == NULL) {
ssh_set_error_oom(session);
return -1;
}
}
if (buffer_add_data(channel->stderr_buffer, data, len) < 0) {
buffer_free(channel->stderr_buffer);
channel->stderr_buffer = NULL;
return -1;
}
}
return 0;
}
/**
* @brief Open a session channel (suited for a shell, not TCP forwarding).
*
* @param channel An allocated channel.
*
* @return SSH_OK on success\n
* SSH_ERROR on error.
*
* @see channel_open_forward()
* @see channel_request_env()
* @see channel_request_shell()
* @see channel_request_exec()
*/
int channel_open_session(ssh_channel channel) {
#ifdef WITH_SSH1
if (channel->session->version == 1) {
return channel_open_session1(channel);
}
#endif
return channel_open(channel,"session",64000,32000,NULL);
}
/**
* @brief Open a TCP/IP forwarding channel.
*
* @param channel An allocated channel.
*
* @param remotehost The remote host to connected (host name or IP).
*
* @param remoteport The remote port.
*
* @param sourcehost The source host (your local computer). It's facultative
* and for logging purpose.
*
* @param localport The source port (your local computer). It's facultative
* and for logging purpose.
* @warning This function does not bind the local port and does not automatically
* forward the content of a socket to the channel. You still have to
* use channel_read and channel_write for this.
*
* @return SSH_OK on success\n
* SSH_ERROR on error
*/
int channel_open_forward(ssh_channel channel, const char *remotehost,
int remoteport, const char *sourcehost, int localport) {
ssh_session session = channel->session;
ssh_buffer payload = NULL;
ssh_string str = NULL;
int rc = SSH_ERROR;
enter_function();
payload = buffer_new();
if (payload == NULL) {
goto error;
}
str = string_from_char(remotehost);
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(payload, str) < 0 ||
buffer_add_u32(payload,htonl(remoteport)) < 0) {
goto error;
}
string_free(str);
str = string_from_char(sourcehost);
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(payload, str) < 0 ||
buffer_add_u32(payload,htonl(localport)) < 0) {
goto error;
}
rc = channel_open(channel, "direct-tcpip", 64000, 32000, payload);
error:
buffer_free(payload);
string_free(str);
leave_function();
return rc;
}
/**
* @brief Close and free a channel.
*
* @param channel The channel to free.
*
* @warning Any data unread on this channel will be lost.
*/
void channel_free(ssh_channel channel) {
ssh_session session = channel->session;
enter_function();
if (channel == NULL) {
leave_function();
return;
}
if (session->alive && channel->open) {
channel_close(channel);
}
/* handle the "my channel is first on session list" case */
if (session->channels == channel) {
session->channels = channel->next;
}
/* handle the "my channel is the only on session list" case */
if (channel->next == channel) {
session->channels = NULL;
} else {
channel->prev->next = channel->next;
channel->next->prev = channel->prev;
}
buffer_free(channel->stdout_buffer);
buffer_free(channel->stderr_buffer);
/* debug trick to catch use after frees */
memset(channel, 'X', sizeof(struct ssh_channel_struct));
SAFE_FREE(channel);
leave_function();
}
/**
* @brief Send an end of file on the channel.
*
* This doesn't close the channel. You may still read from it but not write.
*
* @param channel The channel to send the eof to.
*
* @return SSH_SUCCESS on success\n
* SSH_ERROR on error\n
*
* @see channel_close()
* @see channel_free()
*/
int channel_send_eof(ssh_channel channel){
ssh_session session = channel->session;
int rc = SSH_ERROR;
enter_function();
if (buffer_add_u8(session->out_buffer, SSH2_MSG_CHANNEL_EOF) < 0) {
goto error;
}
if (buffer_add_u32(session->out_buffer,htonl(channel->remote_channel)) < 0) {
goto error;
}
rc = packet_send(session);
ssh_log(session, SSH_LOG_PACKET,
"Sent a EOF on client channel (%d:%d)",
channel->local_channel,
channel->remote_channel);
channel->local_eof = 1;
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
leave_function();
return rc;
}
/**
* @brief Close a channel.
*
* This sends an end of file and then closes the channel. You won't be able
* to recover any data the server was going to send or was in buffers.
*
* @param channel The channel to close.
*
* @return SSH_SUCCESS on success\n
* SSH_ERROR on error
*
* @see channel_free()
* @see channel_eof()
*/
int channel_close(ssh_channel channel){
ssh_session session = channel->session;
int rc = 0;
enter_function();
if (channel->local_eof == 0) {
rc = channel_send_eof(channel);
}
if (rc != SSH_OK) {
leave_function();
return rc;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_CHANNEL_CLOSE) < 0 ||
buffer_add_u32(session->out_buffer, htonl(channel->remote_channel)) < 0) {
goto error;
}
rc = packet_send(session);
ssh_log(session, SSH_LOG_PACKET,
"Sent a close on client channel (%d:%d)",
channel->local_channel,
channel->remote_channel);
if(rc == SSH_OK) {
channel->open = 0;
}
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
leave_function();
return rc;
}
int channel_write_common(ssh_channel channel, const void *data,
uint32_t len, int is_stderr) {
ssh_session session = channel->session;
int origlen = len;
int effectivelen;
enter_function();
if (channel->local_eof) {
ssh_set_error(session, SSH_REQUEST_DENIED,
"Can't write to channel %d:%d after EOF was sent",
channel->local_channel,
channel->remote_channel);
leave_function();
return -1;
}
if (channel->open == 0 || channel->delayed_close != 0) {
ssh_set_error(session, SSH_REQUEST_DENIED, "Remote channel is closed");
leave_function();
return -1;
}
#ifdef WITH_SSH1
if (channel->version == 1) {
int rc = channel_write1(channel, data, len);
leave_function();
return rc;
}
#endif
while (len > 0) {
if (channel->remote_window < len) {
ssh_log(session, SSH_LOG_PROTOCOL,
"Remote window is %d bytes. going to write %d bytes",
channel->remote_window,
len);
ssh_log(session, SSH_LOG_PROTOCOL,
"Waiting for a growing window message...");
/* What happens when the channel window is zero? */
while(channel->remote_window == 0) {
/* parse every incoming packet */
if (packet_wait(channel->session, 0, 0) == SSH_ERROR) {
leave_function();
return SSH_ERROR;
}
}
effectivelen = len > channel->remote_window ? channel->remote_window : len;
} else {
effectivelen = len;
}
if (buffer_add_u8(session->out_buffer, is_stderr ?
SSH2_MSG_CHANNEL_EXTENDED_DATA : SSH2_MSG_CHANNEL_DATA) < 0 ||
buffer_add_u32(session->out_buffer,
htonl(channel->remote_channel)) < 0 ||
buffer_add_u32(session->out_buffer, htonl(effectivelen)) < 0 ||
buffer_add_data(session->out_buffer, data, effectivelen) < 0) {
goto error;
}
if (packet_send(session) != SSH_OK) {
leave_function();
return SSH_ERROR;
}
ssh_log(session, SSH_LOG_RARE,
"channel_write wrote %d bytes", effectivelen);
channel->remote_window -= effectivelen;
len -= effectivelen;
data = ((uint8_t*)data + effectivelen);
}
leave_function();
return origlen;
error:
buffer_reinit(session->out_buffer);
leave_function();
return SSH_ERROR;
}
/**
* @brief Blocking write on channel.
*
* @param channel The channel to write to.
*
* @param data A pointer to the data to write.
*
* @param len The length of the buffer to write to.
*
* @return The number of bytes written, SSH_ERROR on error.
*
* @see channel_read()
*/
int channel_write(ssh_channel channel, const void *data, uint32_t len) {
return channel_write_common(channel, data, len, 0);
}
/**
* @brief Check if the channel is open or not.
*
* @param channel The channel to check.
*
* @return 0 if channel is closed, nonzero otherwise.
*
* @see channel_is_closed()
*/
int channel_is_open(ssh_channel channel) {
return (channel->open != 0 && channel->session->alive != 0);
}
/**
* @brief Check if the channel is closed or not.
*
* @param channel The channel to check.
*
* @return 0 if channel is opened, nonzero otherwise.
*
* @see channel_is_open()
*/
int channel_is_closed(ssh_channel channel) {
return (channel->open == 0 || channel->session->alive == 0);
}
/**
* @brief Check if remote has sent an EOF.
*
* @param channel The channel to check.
*
* @return 0 if there is no EOF, nonzero otherwise.
*/
int channel_is_eof(ssh_channel channel) {
if ((channel->stdout_buffer &&
buffer_get_rest_len(channel->stdout_buffer) > 0) ||
(channel->stderr_buffer &&
buffer_get_rest_len(channel->stderr_buffer) > 0)) {
return 0;
}
return (channel->remote_eof != 0);
}
/**
* @brief Put the channel into blocking or nonblocking mode.
*
* @param channel The channel to use.
*
* @param blocking A boolean for blocking or nonblocking.
*
* @bug This functionnality is still under development and
* doesn't work correctly.
*/
void channel_set_blocking(ssh_channel channel, int blocking) {
channel->blocking = (blocking == 0 ? 0 : 1);
}
static int channel_request(ssh_channel channel, const char *request,
ssh_buffer buffer, int reply) {
ssh_session session = channel->session;
ssh_string req = NULL;
int rc = SSH_ERROR;
enter_function();
req = string_from_char(request);
if (req == NULL) {
goto error;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_CHANNEL_REQUEST) < 0 ||
buffer_add_u32(session->out_buffer, htonl(channel->remote_channel)) < 0 ||
buffer_add_ssh_string(session->out_buffer, req) < 0 ||
buffer_add_u8(session->out_buffer, reply == 0 ? 0 : 1) < 0) {
goto error;
}
string_free(req);
if (buffer != NULL) {
if (buffer_add_data(session->out_buffer, buffer_get(buffer),
buffer_get_len(buffer)) < 0) {
goto error;
}
}
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
ssh_log(session, SSH_LOG_RARE,
"Sent a SSH_MSG_CHANNEL_REQUEST %s", request);
if (reply == 0) {
leave_function();
return SSH_OK;
}
rc = packet_wait(session, SSH2_MSG_CHANNEL_SUCCESS, 1);
if (rc == SSH_ERROR) {
if (session->in_packet.type == SSH2_MSG_CHANNEL_FAILURE) {
ssh_log(session, SSH_LOG_PACKET,
"%s channel request failed", request);
ssh_set_error(session, SSH_REQUEST_DENIED,
"Channel request %s failed", request);
} else {
ssh_log(session, SSH_LOG_RARE,
"Received an unexpected %d message", session->in_packet.type);
}
} else {
ssh_log(session, SSH_LOG_RARE, "Received a SUCCESS");
}
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(req);
leave_function();
return rc;
}
/**
* @brief Request a pty with a specific type and size.
*
* @param channel The channel to sent the request.
*
* @param terminal The terminal type ("vt100, xterm,...").
*
* @param col The number of columns.
*
* @param row The number of rows.
*
* @return SSH_SUCCESS on success, SSH_ERROR on error.
*/
int channel_request_pty_size(ssh_channel channel, const char *terminal,
int col, int row) {
ssh_session session = channel->session;
ssh_string term = NULL;
ssh_buffer buffer = NULL;
int rc = SSH_ERROR;
enter_function();
#ifdef WITH_SSH1
if (channel->version==1) {
channel_request_pty_size1(channel,terminal, col, row);
leave_function();
return rc;
}
#endif
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
term = string_from_char(terminal);
if (term == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, term) < 0 ||
buffer_add_u32(buffer, htonl(col)) < 0 ||
buffer_add_u32(buffer, htonl(row)) < 0 ||
buffer_add_u32(buffer, 0) < 0 ||
buffer_add_u32(buffer, 0) < 0 ||
buffer_add_u32(buffer, htonl(1)) < 0 || /* Add a 0byte string */
buffer_add_u8(buffer, 0) < 0) {
goto error;
}
rc = channel_request(channel, "pty-req", buffer, 1);
error:
buffer_free(buffer);
string_free(term);
leave_function();
return rc;
}
/**
* @brief Request a PTY.
*
* @param channel The channel to send the request.
*
* @return SSH_SUCCESS on success, SSH_ERROR on error.
*
* @see channel_request_pty_size()
*/
int channel_request_pty(ssh_channel channel) {
return channel_request_pty_size(channel, "xterm", 80, 24);
}
/**
* @brief Change the size of the terminal associated to a channel.
*
* @param channel The channel to change the size.
*
* @param cols The new number of columns.
*
* @param rows The new number of rows.
*
* @warning Do not call it from a signal handler if you are not
* sure any other libssh function using the same channel/session
* is running at same time (not 100% threadsafe).
*/
int channel_change_pty_size(ssh_channel channel, int cols, int rows) {
ssh_session session = channel->session;
ssh_buffer buffer = NULL;
int rc = SSH_ERROR;
enter_function();
#ifdef WITH_SSH1
if (channel->version == 1) {
rc = channel_change_pty_size1(channel,cols,rows);
leave_function();
return rc;
}
#endif
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
if (buffer_add_u32(buffer, htonl(cols)) < 0 ||
buffer_add_u32(buffer, htonl(rows)) < 0 ||
buffer_add_u32(buffer, 0) < 0 ||
buffer_add_u32(buffer, 0) < 0) {
goto error;
}
rc = channel_request(channel, "window-change", buffer, 0);
error:
buffer_free(buffer);
leave_function();
return rc;
}
/**
* @brief Request a shell.
*
* @param channel The channel to send the request.
*
* @returns SSH_SUCCESS on success, SSH_ERROR on error.
*/
int channel_request_shell(ssh_channel channel) {
#ifdef WITH_SSH1
if (channel->version == 1) {
return channel_request_shell1(channel);
}
#endif
return channel_request(channel, "shell", NULL, 1);
}
/**
* @brief Request a subsystem (for example "sftp").
*
* @param channel The channel to send the request.
*
* @param subsys The subsystem to request (for example "sftp").
*
* @return SSH_SUCCESS on success, SSH_ERROR on error.
*
* @warning You normally don't have to call it for sftp, see sftp_new().
*/
int channel_request_subsystem(ssh_channel channel, const char *subsys) {
ssh_buffer buffer = NULL;
ssh_string subsystem = NULL;
int rc = SSH_ERROR;
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
subsystem = string_from_char(subsys);
if (subsystem == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, subsystem) < 0) {
goto error;
}
rc = channel_request(channel, "subsystem", buffer, 1);
error:
buffer_free(buffer);
string_free(subsystem);
return rc;
}
int channel_request_sftp( ssh_channel channel){
return channel_request_subsystem(channel, "sftp");
}
static ssh_string generate_cookie(void) {
static const char *hex = "0123456789abcdef";
char s[36];
int i;
srand ((unsigned int)time(NULL));
for (i = 0; i < 32; i++) {
s[i] = hex[rand() % 16];
}
s[32] = '\0';
return string_from_char(s);
}
/**
* @brief Sends the "x11-req" channel request over an existing session channel.
*
* This will enable redirecting the display of the remote X11 applications to
* local X server over an secure tunnel.
*
* @param channel An existing session channel where the remote X11
* applications are going to be executed.
*
* @param single_connection A boolean to mark only one X11 app will be
* redirected.
*
* @param protocol x11 authentication protocol. Pass NULL to use the
* default value MIT-MAGIC-COOKIE-1
*
* @param cookie x11 authentication cookie. Pass NULL to generate
* a random cookie.
*
* @param screen_number Screen number.
*
* @return SSH_OK on success\n
* SSH_ERROR on error
*/
int channel_request_x11(ssh_channel channel, int single_connection, const char *protocol,
const char *cookie, int screen_number) {
ssh_buffer buffer = NULL;
ssh_string p = NULL;
ssh_string c = NULL;
int rc = SSH_ERROR;
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
p = string_from_char(protocol ? protocol : "MIT-MAGIC-COOKIE-1");
if (p == NULL) {
goto error;
}
if (cookie) {
c = string_from_char(cookie);
} else {
c = generate_cookie();
}
if (c == NULL) {
goto error;
}
if (buffer_add_u8(buffer, single_connection == 0 ? 0 : 1) < 0 ||
buffer_add_ssh_string(buffer, p) < 0 ||
buffer_add_ssh_string(buffer, c) < 0 ||
buffer_add_u32(buffer, htonl(screen_number)) < 0) {
goto error;
}
rc = channel_request(channel, "x11-req", buffer, 1);
error:
buffer_free(buffer);
string_free(p);
string_free(c);
return rc;
}
static ssh_channel channel_accept(ssh_session session, int channeltype,
int timeout_ms) {
#ifndef _WIN32
static const struct timespec ts = {
.tv_sec = 0,
.tv_nsec = 50000000 /* 50ms */
};
#endif
ssh_message msg = NULL;
ssh_channel channel = NULL;
struct ssh_iterator *iterator;
int t;
for (t = timeout_ms; t >= 0; t -= 50)
{
ssh_handle_packets(session);
if (session->ssh_message_list) {
iterator = ssh_list_get_iterator(session->ssh_message_list);
while (iterator) {
msg = (ssh_message)iterator->data;
if (ssh_message_type(msg) == SSH_REQUEST_CHANNEL_OPEN &&
ssh_message_subtype(msg) == channeltype) {
ssh_list_remove(session->ssh_message_list, iterator);
channel = ssh_message_channel_request_open_reply_accept(msg);
ssh_message_free(msg);
return channel;
}
iterator = iterator->next;
}
}
#ifdef _WIN32
Sleep(50); /* 50ms */
#else
nanosleep(&ts, NULL);
#endif
}
return NULL;
}
/**
* @brief Accept an X11 forwarding channel.
*
* @param channel An x11-enabled session channel.
*
* @param timeout_ms Timeout in milli-seconds.
*
* @return Newly created channel, or NULL if no X11 request from the server
*/
ssh_channel channel_accept_x11(ssh_channel channel, int timeout_ms) {
return channel_accept(channel->session, SSH_CHANNEL_X11, timeout_ms);
}
static int global_request(ssh_session session, const char *request,
ssh_buffer buffer, int reply) {
ssh_string req = NULL;
int rc = SSH_ERROR;
enter_function();
req = string_from_char(request);
if (req == NULL) {
goto error;
}
if (buffer_add_u8(session->out_buffer, SSH2_MSG_GLOBAL_REQUEST) < 0 ||
buffer_add_ssh_string(session->out_buffer, req) < 0 ||
buffer_add_u8(session->out_buffer, reply == 0 ? 0 : 1) < 0) {
goto error;
}
string_free(req);
if (buffer != NULL) {
if (buffer_add_data(session->out_buffer, buffer_get(buffer),
buffer_get_len(buffer)) < 0) {
goto error;
}
}
if (packet_send(session) != SSH_OK) {
leave_function();
return rc;
}
ssh_log(session, SSH_LOG_RARE,
"Sent a SSH_MSG_GLOBAL_REQUEST %s", request);
if (reply == 0) {
leave_function();
return SSH_OK;
}
rc = packet_wait(session, SSH2_MSG_REQUEST_SUCCESS, 1);
if (rc == SSH_ERROR) {
if (session->in_packet.type == SSH2_MSG_REQUEST_FAILURE) {
ssh_log(session, SSH_LOG_PACKET,
"%s channel request failed", request);
ssh_set_error(session, SSH_REQUEST_DENIED,
"Channel request %s failed", request);
} else {
ssh_log(session, SSH_LOG_RARE,
"Received an unexpected %d message", session->in_packet.type);
}
} else {
ssh_log(session, SSH_LOG_RARE, "Received a SUCCESS");
}
leave_function();
return rc;
error:
buffer_reinit(session->out_buffer);
string_free(req);
leave_function();
return rc;
}
/**
* @brief Sends the "tcpip-forward" global request to ask the server to begin
* listening for inbound connections.
*
* @param session The ssh session to send the request.
*
* @param address The address to bind to on the server. Pass NULL to bind
* to all available addresses on all protocol families
* supported by the server.
*
* @param port The port to bind to on the server. Pass 0 to ask the
* server to allocate the next available unprivileged port
* number
*
* @param bound_port The pointer to get actual bound port. Pass NULL to
* ignore.
*
* @return SSH_OK on success\n
* SSH_ERROR on error
*/
int channel_forward_listen(ssh_session session, const char *address, int port, int *bound_port) {
ssh_buffer buffer = NULL;
ssh_string addr = NULL;
int rc = SSH_ERROR;
uint32_t tmp;
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
addr = string_from_char(address ? address : "");
if (addr == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, addr) < 0 ||
buffer_add_u32(buffer, htonl(port)) < 0) {
goto error;
}
rc = global_request(session, "tcpip-forward", buffer, 1);
if (rc == SSH_OK && port == 0 && bound_port) {
buffer_get_u32(session->in_buffer, &tmp);
*bound_port = ntohl(tmp);
}
error:
buffer_free(buffer);
string_free(addr);
return rc;
}
/**
* @brief Accept an incoming TCP/IP forwarding channel.
*
* @param session The ssh session to use.
*
* @param timeout_ms Timeout in milli-seconds.
*
* @return Newly created channel, or NULL if no incoming channel request from
* the server
*/
ssh_channel channel_forward_accept(ssh_session session, int timeout_ms) {
return channel_accept(session, SSH_CHANNEL_FORWARDED_TCPIP, timeout_ms);
}
/**
* @brief Sends the "cancel-tcpip-forward" global request to ask the server to
* cancel the tcpip-forward request.
*
* @param session The ssh session to send the request.
*
* @param address The bound address on the server.
*
* @param port The bound port on the server.
*
* @return SSH_OK on success\n
* SSH_ERROR on error
*/
int channel_forward_cancel(ssh_session session, const char *address, int port) {
ssh_buffer buffer = NULL;
ssh_string addr = NULL;
int rc = SSH_ERROR;
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
addr = string_from_char(address ? address : "");
if (addr == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, addr) < 0 ||
buffer_add_u32(buffer, htonl(port)) < 0) {
goto error;
}
rc = global_request(session, "cancel-tcpip-forward", buffer, 1);
error:
buffer_free(buffer);
string_free(addr);
return rc;
}
/**
* @brief Set environement variables.
*
* @param channel The channel to set the environement variables.
*
* @param name The name of the variable.
*
* @param value The value to set.
*
* @return SSH_SUCCESS on success, SSH_ERROR on error.
*
* @warning Some environement variables may be refused by security reasons.
* */
int channel_request_env(ssh_channel channel, const char *name, const char *value) {
ssh_buffer buffer = NULL;
ssh_string str = NULL;
int rc = SSH_ERROR;
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
str = string_from_char(name);
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, str) < 0) {
goto error;
}
string_free(str);
str = string_from_char(value);
if (str == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, str) < 0) {
goto error;
}
rc = channel_request(channel, "env", buffer,1);
error:
buffer_free(buffer);
string_free(str);
return rc;
}
/**
* @brief Run a shell command without an interactive shell.
*
* This is similar to 'sh -c command'.
*
* @param channel The channel to execute the command.
*
* @param cmd The command to execute
* (e.g. "ls ~/ -al | grep -i reports").
*
* @return SSH_SUCCESS on success, SSH_ERROR on error.
*
* @see channel_request_shell()
*/
int channel_request_exec(ssh_channel channel, const char *cmd) {
ssh_buffer buffer = NULL;
ssh_string command = NULL;
int rc = SSH_ERROR;
#ifdef WITH_SSH1
if (channel->version == 1) {
return channel_request_exec1(channel, cmd);
}
#endif
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
command = string_from_char(cmd);
if (command == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, command) < 0) {
goto error;
}
rc = channel_request(channel, "exec", buffer, 1);
error:
buffer_free(buffer);
string_free(command);
return rc;
}
/**
* @brief Send a signal to remote process (as described in RFC 4254, section 6.9).
*
* Sends a signal 'signal' to the remote process.
* Note, that remote system may not support signals concept.
* In such a case this request will be silently ignored.
* Only SSH-v2 is supported (I'm not sure about SSH-v1).
*
* @param channel The channel to send signal.
*
* @param signal The signal to send (without SIG prefix)
* (e.g. "TERM" or "KILL").
*
* @return SSH_SUCCESS on success, SSH_ERROR on error (including attempt to send signal via SSH-v1 session).
*
*/
int channel_request_send_signal(ssh_channel channel, const char *signal) {
ssh_buffer buffer = NULL;
ssh_string encoded_signal = NULL;
int rc = SSH_ERROR;
#ifdef WITH_SSH1
if (channel->version == 1) {
return SSH_ERROR; // TODO: Add support for SSH-v1 if possible.
}
#endif
buffer = buffer_new();
if (buffer == NULL) {
goto error;
}
encoded_signal = string_from_char(signal);
if (encoded_signal == NULL) {
goto error;
}
if (buffer_add_ssh_string(buffer, encoded_signal) < 0) {
goto error;
}
rc = channel_request(channel, "signal", buffer, 0);
error:
buffer_free(buffer);
string_free(encoded_signal);
return rc;
}
/* TODO : fix the delayed close thing */
/* TODO : fix the blocking behaviours */
/**
* @brief Read data from a channel into a buffer.
*
* @param channel The channel to read from.
*
* @param buffer The buffer which will get the data.
*
* @param count The count of bytes to be read. If it is biggerthan 0,
* the exact size will be read, else (bytes=0) it will
* return once anything is available.
*
* @param is_stderr A boolean value to mark reading from the stderr stream.
*
* @return The number of bytes read, 0 on end of file or SSH_ERROR on error.
*/
int channel_read_buffer(ssh_channel channel, ssh_buffer buffer, uint32_t count,
int is_stderr) {
ssh_session session=channel->session;
ssh_buffer stdbuf = channel->stdout_buffer;
uint32_t maxread = count;
uint32_t len;
buffer_reinit(buffer);
enter_function();
if (count == 0) {
maxread = MAX_PACKET_LEN;
}
if (is_stderr) {
stdbuf = channel->stderr_buffer;
}
/*
* We may have problem if the window is too small to accept as much data
* as asked
*/
ssh_log(session, SSH_LOG_PROTOCOL,
"Read (%d) buffered: %d bytes. Window: %d",
count,
buffer_get_rest_len(stdbuf),
channel->local_window);
if (count > buffer_get_rest_len(stdbuf) + channel->local_window) {
if (grow_window(session, channel,
count - buffer_get_rest_len(stdbuf)) < 0) {
leave_function();
return -1;
}
}
/* block reading if asked bytes=0 */
while (buffer_get_rest_len(stdbuf) == 0 ||
buffer_get_rest_len(stdbuf) < count) {
if (channel->remote_eof && buffer_get_rest_len(stdbuf) == 0) {
leave_function();
return 0;
}
if (channel->remote_eof) {
/* Return the resting bytes in buffer */
break;
}
if (buffer_get_rest_len(stdbuf) >= maxread) {
/* Stop reading when buffer is full enough */
break;
}
if ((packet_read(session)) != SSH_OK ||
(packet_translate(session) != SSH_OK)) {
leave_function();
return -1;
}
packet_parse(session);
}
if(channel->local_window < WINDOWLIMIT) {
if (grow_window(session, channel, 0) < 0) {
leave_function();
return -1;
}
}
if (count == 0) {
/* write the ful buffer information */
if (buffer_add_data(buffer, buffer_get_rest(stdbuf),
buffer_get_rest_len(stdbuf)) < 0) {
leave_function();
return -1;
}
buffer_reinit(stdbuf);
} else {
/* Read bytes bytes if len is greater, everything otherwise */
len = buffer_get_rest_len(stdbuf);
len = (len > count ? count : len);
if (buffer_add_data(buffer, buffer_get_rest(stdbuf), len) < 0) {
leave_function();
return -1;
}
buffer_pass_bytes(stdbuf,len);
}
leave_function();
return buffer_get_len(buffer);
}
/* TODO FIXME Fix the delayed close thing */
/* TODO FIXME Fix the blocking behaviours */
/**
* @brief Reads data from a channel.
*
* @param channel The channel to read from.
*
* @param dest The destination buffer which will get the data.
*
* @param count The count of bytes to be read.
*
* @param is_stderr A boolean value to mark reading from the stderr flow.
*
* @return The number of bytes read, 0 on end of file or SSH_ERROR on error.
* @warning This function may return less than count bytes of data, and won't
* block until count bytes have been read.
* @warning The read function using a buffer has been renamed to
* channel_read_buffer().
*/
int channel_read(ssh_channel channel, void *dest, uint32_t count, int is_stderr) {
ssh_session session = channel->session;
ssh_buffer stdbuf = channel->stdout_buffer;
uint32_t len;
enter_function();
if (count == 0) {
leave_function();
return 0;
}
if (is_stderr) {
stdbuf=channel->stderr_buffer;
}
/*
* We may have problem if the window is too small to accept as much data
* as asked
*/
ssh_log(session, SSH_LOG_PROTOCOL,
"Read (%d) buffered : %d bytes. Window: %d",
count,
buffer_get_rest_len(stdbuf),
channel->local_window);
if (count > buffer_get_rest_len(stdbuf) + channel->local_window) {
if (grow_window(session, channel,
count - buffer_get_rest_len(stdbuf)) < 0) {
leave_function();
return -1;
}
}
/* block reading until at least one byte is read
* and ignore the trivial case count=0
*/
while (buffer_get_rest_len(stdbuf) == 0 && count > 0) {
if (channel->remote_eof && buffer_get_rest_len(stdbuf) == 0) {
leave_function();
return 0;
}
if (channel->remote_eof) {
/* Return the resting bytes in buffer */
break;
}
if (buffer_get_rest_len(stdbuf) >= count) {
/* Stop reading when buffer is full enough */
break;
}
if ((packet_read(session)) != SSH_OK ||
(packet_translate(session) != SSH_OK)) {
leave_function();
return -1;
}
packet_parse(session);
}
if (channel->local_window < WINDOWLIMIT) {
if (grow_window(session, channel, 0) < 0) {
leave_function();
return -1;
}
}
len = buffer_get_rest_len(stdbuf);
/* Read count bytes if len is greater, everything otherwise */
len = (len > count ? count : len);
memcpy(dest, buffer_get_rest(stdbuf), len);
buffer_pass_bytes(stdbuf,len);
leave_function();
return len;
}
/**
* @brief Do a nonblocking read on the channel.
*
* A nonblocking read on the specified channel. it will return <= count bytes of
* data read atomicly.
*
* @param channel The channel to read from.
*
* @param dest A pointer to a destination buffer.
*
* @param count The count of bytes of data to be read.
*
* @param is_stderr A boolean to select the stderr stream.
*
* @return The number of bytes read, 0 if nothing is available or
* SSH_ERROR on error.
*
* @warning Don't forget to check for EOF as it would return 0 here.
*
* @see channel_is_eof()
*/
int channel_read_nonblocking(ssh_channel channel, void *dest, uint32_t count,
int is_stderr) {
ssh_session session = channel->session;
uint32_t to_read;
int rc;
enter_function();
to_read = channel_poll(channel, is_stderr);
if (to_read <= 0) {
leave_function();
return to_read; /* may be an error code */
}
if (to_read > count) {
to_read = count;
}
rc = channel_read(channel, dest, to_read, is_stderr);
leave_function();
return rc;
}
/**
* @brief Polls a channel for data to read.
*
* @param channel The channel to poll.
*
* @param is_stderr A boolean to select the stderr stream.
*
* @return The number of bytes available for reading, 0 if nothing is available
* or SSH_ERROR on error.
*
* @warning When the channel is in EOF state, the function returns SSH_EOF.
*
* @see channel_is_eof()
*/
int channel_poll(ssh_channel channel, int is_stderr){
ssh_session session = channel->session;
ssh_buffer stdbuf = channel->stdout_buffer;
enter_function();
if (is_stderr) {
stdbuf = channel->stderr_buffer;
}
if (buffer_get_rest_len(stdbuf) == 0 && channel->remote_eof == 0) {
if (ssh_handle_packets(channel->session) == SSH_ERROR) {
leave_function();
return SSH_ERROR;
}
}
if (buffer_get_rest_len(stdbuf) > 0)
return buffer_get_rest_len(stdbuf);
if (channel->remote_eof) {
leave_function();
return SSH_EOF;
}
leave_function();
return buffer_get_rest_len(stdbuf);
}
/**
* @brief Recover the session in which belongs a channel.
*
* @param channel The channel to recover the session from.
*
* @return The session pointer.
*/
ssh_session channel_get_session(ssh_channel channel) {
return channel->session;
}
/**
* @brief Get the exit status of the channel (error code from the executed
* instruction).
*
* @param channel The channel to get the status from.
*
* @return -1 if no exit status has been returned or eof not sent,
* the exit status othewise.
*/
int channel_get_exit_status(ssh_channel channel) {
if (channel->local_eof == 0) {
return -1;
}
while (channel->remote_eof == 0 || channel->exit_status == -1) {
/* Parse every incoming packet */
if (packet_wait(channel->session, 0, 0) != SSH_OK) {
return -1;
}
if (channel->open == 0) {
/* When a channel is closed, no exit status message can
* come anymore */
break;
}
}
return channel->exit_status;
}
/*
* This function acts as a meta select.
*
* First, channels are analyzed to seek potential can-write or can-read ones,
* then if no channel has been elected, it goes in a loop with the posix
* select(2).
* This is made in two parts: protocol select and network select. The protocol
* select does not use the network functions at all
*/
static int channel_protocol_select(ssh_channel *rchans, ssh_channel *wchans,
ssh_channel *echans, ssh_channel *rout, ssh_channel *wout, ssh_channel *eout) {
ssh_channel chan;
int i;
int j = 0;
for (i = 0; rchans[i] != NULL; i++) {
chan = rchans[i];
while (chan->open && ssh_socket_data_available(chan->session->socket)) {
ssh_handle_packets(chan->session);
}
if ((chan->stdout_buffer && buffer_get_len(chan->stdout_buffer) > 0) ||
(chan->stderr_buffer && buffer_get_len(chan->stderr_buffer) > 0) ||
chan->remote_eof) {
rout[j] = chan;
j++;
}
}
rout[j] = NULL;
j = 0;
for(i = 0; wchans[i] != NULL; i++) {
chan = wchans[i];
/* It's not our business to seek if the file descriptor is writable */
if (ssh_socket_data_writable(chan->session->socket) &&
chan->open && (chan->remote_window > 0)) {
wout[j] = chan;
j++;
}
}
wout[j] = NULL;
j = 0;
for (i = 0; echans[i] != NULL; i++) {
chan = echans[i];
if (!ssh_socket_is_open(chan->session->socket) || !chan->open) {
eout[j] = chan;
j++;
}
}
eout[j] = NULL;
return 0;
}
/* Just count number of pointers in the array */
static int count_ptrs(ssh_channel *ptrs) {
int c;
for (c = 0; ptrs[c] != NULL; c++)
;
return c;
}
/**
* @brief Act like the standard select(2) on channels.
*
* The list of pointers are then actualized and will only contain pointers to
* channels that are respectively readable, writable or have an exception to
* trap.
*
* @param readchans A NULL pointer or an array of channel pointers,
* terminated by a NULL.
*
* @param writechans A NULL pointer or an array of channel pointers,
* terminated by a NULL.
*
* @param exceptchans A NULL pointer or an array of channel pointers,
* terminated by a NULL.
*
* @param timeout Timeout as defined by select(2).
*
* @return SSH_SUCCESS operation successful\n
* SSH_EINTR select(2) syscall was interrupted, relaunch the function
*/
int channel_select(ssh_channel *readchans, ssh_channel *writechans,
ssh_channel *exceptchans, struct timeval * timeout) {
ssh_channel *rchans, *wchans, *echans;
ssh_channel dummy = NULL;
fd_set rset;
fd_set wset;
fd_set eset;
int fdmax = -1;
int rc;
int i;
/* don't allow NULL pointers */
if (readchans == NULL) {
readchans = &dummy;
}
if (writechans == NULL) {
writechans = &dummy;
}
if (exceptchans == NULL) {
exceptchans = &dummy;
}
if (readchans[0] == NULL && writechans[0] == NULL && exceptchans[0] == NULL) {
/* No channel to poll?? Go away! */
return 0;
}
/* Prepare the outgoing temporary arrays */
rchans = malloc(sizeof(ssh_channel ) * (count_ptrs(readchans) + 1));
if (rchans == NULL) {
return SSH_ERROR;
}
wchans = malloc(sizeof(ssh_channel ) * (count_ptrs(writechans) + 1));
if (wchans == NULL) {
SAFE_FREE(rchans);
return SSH_ERROR;
}
echans = malloc(sizeof(ssh_channel ) * (count_ptrs(exceptchans) + 1));
if (echans == NULL) {
SAFE_FREE(rchans);
SAFE_FREE(wchans);
return SSH_ERROR;
}
/*
* First, try without doing network stuff then, select and redo the
* networkless stuff
*/
do {
channel_protocol_select(readchans, writechans, exceptchans,
rchans, wchans, echans);
if (rchans[0] != NULL || wchans[0] != NULL || echans[0] != NULL) {
/* We've got one without doing any select overwrite the begining arrays */
memcpy(readchans, rchans, (count_ptrs(rchans) + 1) * sizeof(ssh_channel ));
memcpy(writechans, wchans, (count_ptrs(wchans) + 1) * sizeof(ssh_channel ));
memcpy(exceptchans, echans, (count_ptrs(echans) + 1) * sizeof(ssh_channel ));
SAFE_FREE(rchans);
SAFE_FREE(wchans);
SAFE_FREE(echans);
return 0;
}
/*
* Since we verified the invalid fd cases into the networkless select,
* we can be sure all fd are valid ones
*/
FD_ZERO(&rset);
FD_ZERO(&wset);
FD_ZERO(&eset);
for (i = 0; readchans[i] != NULL; i++) {
if (!ssh_socket_fd_isset(readchans[i]->session->socket, &rset)) {
ssh_socket_fd_set(readchans[i]->session->socket, &rset, &fdmax);
}
}
for (i = 0; writechans[i] != NULL; i++) {
if (!ssh_socket_fd_isset(writechans[i]->session->socket, &wset)) {
ssh_socket_fd_set(writechans[i]->session->socket, &wset, &fdmax);
}
}
for (i = 0; exceptchans[i] != NULL; i++) {
if (!ssh_socket_fd_isset(exceptchans[i]->session->socket, &eset)) {
ssh_socket_fd_set(exceptchans[i]->session->socket, &eset, &fdmax);
}
}
/* Here we go */
rc = select(fdmax, &rset, &wset, &eset, timeout);
/* Leave if select was interrupted */
if (rc == EINTR) {
SAFE_FREE(rchans);
SAFE_FREE(wchans);
SAFE_FREE(echans);
return SSH_EINTR;
}
for (i = 0; readchans[i] != NULL; i++) {
if (ssh_socket_fd_isset(readchans[i]->session->socket, &rset)) {
ssh_socket_set_toread(readchans[i]->session->socket);
}
}
for (i = 0; writechans[i] != NULL; i++) {
if (ssh_socket_fd_isset(writechans[i]->session->socket, &wset)) {
ssh_socket_set_towrite(writechans[i]->session->socket);
}
}
for (i = 0; exceptchans[i] != NULL; i++) {
if (ssh_socket_fd_isset(exceptchans[i]->session->socket, &eset)) {
ssh_socket_set_except(exceptchans[i]->session->socket);
}
}
} while(1); /* Return to do loop */
/* not reached */
return 0;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/channels.c
|
C
|
gpl3
| 58,098
|
/*
* messages.c - message parsion for the server
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/** \defgroup ssh_messages SSH Messages
* this file contains the Message parsing utilities for server programs using
* libssh. The main loop of the program will call ssh_message_get(session) to
* get messages as they come. they are not 1-1 with the protocol messages.
* then, the user will know what kind of a message it is and use the appropriate
* functions to handle it (or use the default handlers if she doesn't know what to
* do
* \addtogroup ssh_messages
* @{
*/
#include <string.h>
#include <stdlib.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/libssh.h"
#include "libssh/priv.h"
#include "libssh/ssh2.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/channels.h"
#include "libssh/session.h"
#include "libssh/misc.h"
#include "libssh/keys.h"
#include "libssh/dh.h"
#include "libssh/messages.h"
static ssh_message message_new(ssh_session session){
ssh_message msg = malloc(sizeof(struct ssh_message_struct));
if (msg == NULL) {
return NULL;
}
ZERO_STRUCTP(msg);
msg->session = session;
return msg;
}
static ssh_message handle_service_request(ssh_session session) {
ssh_string service = NULL;
char *service_c = NULL;
ssh_message msg=NULL;
enter_function();
service = buffer_get_ssh_string(session->in_buffer);
if (service == NULL) {
ssh_set_error(session, SSH_FATAL, "Invalid SSH_MSG_SERVICE_REQUEST packet");
goto error;
}
service_c = string_to_char(service);
if (service_c == NULL) {
goto error;
}
ssh_log(session, SSH_LOG_PACKET,
"Received a SERVICE_REQUEST for service %s", service_c);
msg=message_new(session);
if(!msg){
SAFE_FREE(service_c);
goto error;
}
msg->type=SSH_REQUEST_SERVICE;
msg->service_request.service=service_c;
error:
string_free(service);
leave_function();
return msg;
}
static int handle_unimplemented(ssh_session session) {
if (buffer_add_u32(session->out_buffer, htonl(session->recv_seq - 1)) < 0) {
return -1;
}
if (packet_send(session) != SSH_OK) {
return -1;
}
return 0;
}
static ssh_message handle_userauth_request(ssh_session session){
ssh_string user = NULL;
ssh_string service = NULL;
ssh_string method = NULL;
ssh_message msg = NULL;
char *service_c = NULL;
char *method_c = NULL;
uint32_t method_size = 0;
enter_function();
msg = message_new(session);
if (msg == NULL) {
return NULL;
}
user = buffer_get_ssh_string(session->in_buffer);
if (user == NULL) {
goto error;
}
service = buffer_get_ssh_string(session->in_buffer);
if (service == NULL) {
goto error;
}
method = buffer_get_ssh_string(session->in_buffer);
if (method == NULL) {
goto error;
}
msg->type = SSH_REQUEST_AUTH;
msg->auth_request.username = string_to_char(user);
if (msg->auth_request.username == NULL) {
goto error;
}
string_free(user);
user = NULL;
service_c = string_to_char(service);
if (service_c == NULL) {
goto error;
}
method_c = string_to_char(method);
if (method_c == NULL) {
goto error;
}
method_size = string_len(method);
string_free(service);
service = NULL;
string_free(method);
method = NULL;
ssh_log(session, SSH_LOG_PACKET,
"Auth request for service %s, method %s for user '%s'",
service_c, method_c,
msg->auth_request.username);
if (strncmp(method_c, "none", method_size) == 0) {
msg->auth_request.method = SSH_AUTH_METHOD_NONE;
SAFE_FREE(service_c);
SAFE_FREE(method_c);
leave_function();
return msg;
}
if (strncmp(method_c, "password", method_size) == 0) {
ssh_string pass = NULL;
uint8_t tmp;
msg->auth_request.method = SSH_AUTH_METHOD_PASSWORD;
SAFE_FREE(service_c);
SAFE_FREE(method_c);
buffer_get_u8(session->in_buffer, &tmp);
pass = buffer_get_ssh_string(session->in_buffer);
if (pass == NULL) {
goto error;
}
msg->auth_request.password = string_to_char(pass);
string_burn(pass);
string_free(pass);
pass = NULL;
if (msg->auth_request.password == NULL) {
goto error;
}
leave_function();
return msg;
}
if (strncmp(method_c, "publickey", method_size) == 0) {
ssh_string algo = NULL;
ssh_string publickey = NULL;
uint8_t has_sign;
msg->auth_request.method = SSH_AUTH_METHOD_PUBLICKEY;
SAFE_FREE(method_c);
buffer_get_u8(session->in_buffer, &has_sign);
algo = buffer_get_ssh_string(session->in_buffer);
if (algo == NULL) {
goto error;
}
publickey = buffer_get_ssh_string(session->in_buffer);
if (publickey == NULL) {
string_free(algo);
algo = NULL;
goto error;
}
msg->auth_request.public_key = publickey_from_string(session, publickey);
string_free(algo);
algo = NULL;
string_free(publickey);
publickey = NULL;
if (msg->auth_request.public_key == NULL) {
goto error;
}
msg->auth_request.signature_state = 0;
// has a valid signature ?
if(has_sign) {
SIGNATURE *signature = NULL;
ssh_public_key public_key = msg->auth_request.public_key;
ssh_string sign = NULL;
ssh_buffer digest = NULL;
sign = buffer_get_ssh_string(session->in_buffer);
if(sign == NULL) {
ssh_log(session, SSH_LOG_PACKET, "Invalid signature packet from peer");
msg->auth_request.signature_state = -2;
goto error;
}
signature = signature_from_string(session, sign, public_key,
public_key->type);
digest = ssh_userauth_build_digest(session, msg, service_c);
if ((digest == NULL || signature == NULL) ||
(digest != NULL && signature != NULL &&
sig_verify(session, public_key, signature,
buffer_get(digest), buffer_get_len(digest)) < 0)) {
ssh_log(session, SSH_LOG_PACKET, "Invalid signature from peer");
string_free(sign);
sign = NULL;
buffer_free(digest);
digest = NULL;
signature_free(signature);
signature = NULL;
msg->auth_request.signature_state = -1;
goto error;
}
else
ssh_log(session, SSH_LOG_PACKET, "Valid signature received");
buffer_free(digest);
digest = NULL;
string_free(sign);
sign = NULL;
signature_free(signature);
signature = NULL;
msg->auth_request.signature_state = 1;
}
SAFE_FREE(service_c);
leave_function();
return msg;
}
msg->auth_request.method = SSH_AUTH_METHOD_UNKNOWN;
SAFE_FREE(method_c);
leave_function();
return msg;
error:
string_free(user);
string_free(service);
string_free(method);
SAFE_FREE(method_c);
SAFE_FREE(service_c);
ssh_message_free(msg);
leave_function();
return NULL;
}
static ssh_message handle_channel_request_open(ssh_session session) {
ssh_message msg = NULL;
ssh_string type = NULL, originator = NULL, destination = NULL;
char *type_c = NULL;
uint32_t sender, window, packet, originator_port, destination_port;
enter_function();
msg = message_new(session);
if (msg == NULL) {
ssh_set_error_oom(session);
leave_function();
return NULL;
}
msg->type = SSH_REQUEST_CHANNEL_OPEN;
type = buffer_get_ssh_string(session->in_buffer);
if (type == NULL) {
ssh_set_error_oom(session);
goto error;
}
type_c = string_to_char(type);
if (type_c == NULL) {
ssh_set_error_oom(session);
goto error;
}
ssh_log(session, SSH_LOG_PACKET,
"Clients wants to open a %s channel", type_c);
buffer_get_u32(session->in_buffer, &sender);
buffer_get_u32(session->in_buffer, &window);
buffer_get_u32(session->in_buffer, &packet);
msg->channel_request_open.sender = ntohl(sender);
msg->channel_request_open.window = ntohl(window);
msg->channel_request_open.packet_size = ntohl(packet);
if (strcmp(type_c,"session") == 0) {
msg->channel_request_open.type = SSH_CHANNEL_SESSION;
string_free(type);
SAFE_FREE(type_c);
leave_function();
return msg;
}
if (strcmp(type_c,"direct-tcpip") == 0) {
destination = buffer_get_ssh_string(session->in_buffer);
if (destination == NULL) {
ssh_set_error_oom(session);
goto error;
}
msg->channel_request_open.destination = string_to_char(type);
if (msg->channel_request_open.destination == NULL) {
ssh_set_error_oom(session);
string_free(destination);
goto error;
}
string_free(destination);
buffer_get_u32(session->in_buffer, &destination_port);
msg->channel_request_open.destination_port = ntohl(destination_port);
originator = buffer_get_ssh_string(session->in_buffer);
if (originator == NULL) {
ssh_set_error_oom(session);
goto error;
}
msg->channel_request_open.originator = string_to_char(type);
if (msg->channel_request_open.originator == NULL) {
ssh_set_error_oom(session);
string_free(originator);
goto error;
}
string_free(originator);
buffer_get_u32(session->in_buffer, &originator_port);
msg->channel_request_open.originator_port = ntohl(originator_port);
msg->channel_request_open.type = SSH_CHANNEL_DIRECT_TCPIP;
string_free(type);
SAFE_FREE(type_c);
leave_function();
return msg;
}
if (strcmp(type_c,"forwarded-tcpip") == 0) {
destination = buffer_get_ssh_string(session->in_buffer);
if (destination == NULL) {
ssh_set_error_oom(session);
goto error;
}
msg->channel_request_open.destination = string_to_char(type);
if (msg->channel_request_open.destination == NULL) {
ssh_set_error_oom(session);
string_free(destination);
goto error;
}
string_free(destination);
buffer_get_u32(session->in_buffer, &destination_port);
msg->channel_request_open.destination_port = ntohl(destination_port);
originator = buffer_get_ssh_string(session->in_buffer);
if (originator == NULL) {
ssh_set_error_oom(session);
goto error;
}
msg->channel_request_open.originator = string_to_char(type);
if (msg->channel_request_open.originator == NULL) {
ssh_set_error_oom(session);
string_free(originator);
goto error;
}
string_free(originator);
buffer_get_u32(session->in_buffer, &originator_port);
msg->channel_request_open.originator_port = ntohl(originator_port);
msg->channel_request_open.type = SSH_CHANNEL_FORWARDED_TCPIP;
string_free(type);
SAFE_FREE(type_c);
leave_function();
return msg;
}
if (strcmp(type_c,"x11") == 0) {
originator = buffer_get_ssh_string(session->in_buffer);
if (originator == NULL) {
ssh_set_error_oom(session);
goto error;
}
msg->channel_request_open.originator = string_to_char(type);
if (msg->channel_request_open.originator == NULL) {
ssh_set_error_oom(session);
string_free(originator);
goto error;
}
string_free(originator);
buffer_get_u32(session->in_buffer, &originator_port);
msg->channel_request_open.originator_port = ntohl(originator_port);
msg->channel_request_open.type = SSH_CHANNEL_X11;
string_free(type);
SAFE_FREE(type_c);
leave_function();
return msg;
}
msg->channel_request_open.type = SSH_CHANNEL_UNKNOWN;
string_free(type);
SAFE_FREE(type_c);
leave_function();
return msg;
error:
string_free(type);
SAFE_FREE(type_c);
ssh_message_free(msg);
leave_function();
return NULL;
}
ssh_channel ssh_message_channel_request_open_reply_accept(ssh_message msg) {
ssh_session session = msg->session;
ssh_channel chan = NULL;
enter_function();
if (msg == NULL) {
leave_function();
return NULL;
}
chan = channel_new(session);
if (chan == NULL) {
leave_function();
return NULL;
}
chan->local_channel = ssh_channel_new_id(session);
chan->local_maxpacket = 35000;
chan->local_window = 32000;
chan->remote_channel = msg->channel_request_open.sender;
chan->remote_maxpacket = msg->channel_request_open.packet_size;
chan->remote_window = msg->channel_request_open.window;
chan->open = 1;
if (buffer_add_u8(session->out_buffer, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) < 0) {
goto error;
}
if (buffer_add_u32(session->out_buffer, htonl(chan->remote_channel)) < 0) {
goto error;
}
if (buffer_add_u32(session->out_buffer, htonl(chan->local_channel)) < 0) {
goto error;
}
if (buffer_add_u32(session->out_buffer, htonl(chan->local_window)) < 0) {
goto error;
}
if (buffer_add_u32(session->out_buffer, htonl(chan->local_maxpacket)) < 0) {
goto error;
}
ssh_log(session, SSH_LOG_PACKET,
"Accepting a channel request_open for chan %d", chan->remote_channel);
if (packet_send(session) != SSH_OK) {
goto error;
}
leave_function();
return chan;
error:
channel_free(chan);
leave_function();
return NULL;
}
static ssh_message handle_channel_request(ssh_session session) {
ssh_message msg = NULL;
ssh_string type = NULL;
char *type_c = NULL;
uint32_t channel;
uint8_t want_reply;
enter_function();
msg = message_new(session);
if (msg == NULL) {
ssh_set_error_oom(session);
return NULL;
}
buffer_get_u32(session->in_buffer, &channel);
channel = ntohl(channel);
type = buffer_get_ssh_string(session->in_buffer);
if (type == NULL) {
ssh_set_error_oom(session);
goto error;
}
type_c = string_to_char(type);
if (type_c == NULL) {
ssh_set_error_oom(session);
goto error;
}
string_free(type);
buffer_get_u8(session->in_buffer,&want_reply);
ssh_log(session, SSH_LOG_PACKET,
"Received a %s channel_request for channel %d (want_reply=%hhd)",
type_c, channel, want_reply);
msg->type = SSH_REQUEST_CHANNEL;
msg->channel_request.channel = ssh_channel_from_local(session, channel);
if (msg->channel_request.channel == NULL) {
ssh_set_error(session, SSH_FATAL, "There are no channels with the id %u.",
channel);
goto error;
}
msg->channel_request.want_reply = want_reply;
if (strcmp(type_c, "pty-req") == 0) {
ssh_string term = NULL;
char *term_c = NULL;
SAFE_FREE(type_c);
term = buffer_get_ssh_string(session->in_buffer);
if (term == NULL) {
ssh_set_error_oom(session);
goto error;
}
term_c = string_to_char(term);
if (term_c == NULL) {
ssh_set_error_oom(session);
string_free(term);
goto error;
}
string_free(term);
msg->channel_request.type = SSH_CHANNEL_REQUEST_PTY;
msg->channel_request.TERM = term_c;
buffer_get_u32(session->in_buffer, &msg->channel_request.width);
buffer_get_u32(session->in_buffer, &msg->channel_request.height);
buffer_get_u32(session->in_buffer, &msg->channel_request.pxwidth);
buffer_get_u32(session->in_buffer, &msg->channel_request.pxheight);
msg->channel_request.width = ntohl(msg->channel_request.width);
msg->channel_request.height = ntohl(msg->channel_request.height);
msg->channel_request.pxwidth = ntohl(msg->channel_request.pxwidth);
msg->channel_request.pxheight = ntohl(msg->channel_request.pxheight);
msg->channel_request.modes = buffer_get_ssh_string(session->in_buffer);
if (msg->channel_request.modes == NULL) {
SAFE_FREE(term_c);
goto error;
}
leave_function();
return msg;
}
if (strcmp(type_c, "window-change") == 0) {
SAFE_FREE(type_c);
msg->channel_request.type = SSH_CHANNEL_REQUEST_WINDOW_CHANGE;
buffer_get_u32(session->in_buffer, &msg->channel_request.width);
buffer_get_u32(session->in_buffer, &msg->channel_request.height);
buffer_get_u32(session->in_buffer, &msg->channel_request.pxwidth);
buffer_get_u32(session->in_buffer, &msg->channel_request.pxheight);
msg->channel_request.width = ntohl(msg->channel_request.width);
msg->channel_request.height = ntohl(msg->channel_request.height);
msg->channel_request.pxwidth = ntohl(msg->channel_request.pxwidth);
msg->channel_request.pxheight = ntohl(msg->channel_request.pxheight);
leave_function();
return msg;
}
if (strcmp(type_c, "subsystem") == 0) {
ssh_string subsys = NULL;
char *subsys_c = NULL;
SAFE_FREE(type_c);
subsys = buffer_get_ssh_string(session->in_buffer);
if (subsys == NULL) {
ssh_set_error_oom(session);
goto error;
}
subsys_c = string_to_char(subsys);
if (subsys_c == NULL) {
ssh_set_error_oom(session);
string_free(subsys);
goto error;
}
string_free(subsys);
msg->channel_request.type = SSH_CHANNEL_REQUEST_SUBSYSTEM;
msg->channel_request.subsystem = subsys_c;
leave_function();
return msg;
}
if (strcmp(type_c, "shell") == 0) {
SAFE_FREE(type_c);
msg->channel_request.type = SSH_CHANNEL_REQUEST_SHELL;
leave_function();
return msg;
}
if (strcmp(type_c, "exec") == 0) {
ssh_string cmd = NULL;
SAFE_FREE(type_c);
cmd = buffer_get_ssh_string(session->in_buffer);
if (cmd == NULL) {
ssh_set_error_oom(session);
goto error;
}
msg->channel_request.type = SSH_CHANNEL_REQUEST_EXEC;
msg->channel_request.command = string_to_char(cmd);
if (msg->channel_request.command == NULL) {
string_free(cmd);
goto error;
}
string_free(cmd);
leave_function();
return msg;
}
if (strcmp(type_c, "env") == 0) {
ssh_string name = NULL;
ssh_string value = NULL;
SAFE_FREE(type_c);
name = buffer_get_ssh_string(session->in_buffer);
if (name == NULL) {
ssh_set_error_oom(session);
goto error;
}
value = buffer_get_ssh_string(session->in_buffer);
if (value == NULL) {
ssh_set_error_oom(session);
string_free(name);
goto error;
}
msg->channel_request.type = SSH_CHANNEL_REQUEST_ENV;
msg->channel_request.var_name = string_to_char(name);
msg->channel_request.var_value = string_to_char(value);
if (msg->channel_request.var_name == NULL ||
msg->channel_request.var_value == NULL) {
string_free(name);
string_free(value);
goto error;
}
string_free(name);
string_free(value);
leave_function();
return msg;
}
msg->channel_request.type = SSH_CHANNEL_UNKNOWN;
SAFE_FREE(type_c);
leave_function();
return msg;
error:
string_free(type);
SAFE_FREE(type_c);
ssh_message_free(msg);
leave_function();
return NULL;
}
int ssh_message_channel_request_reply_success(ssh_message msg) {
uint32_t channel;
if (msg == NULL) {
return SSH_ERROR;
}
if (msg->channel_request.want_reply) {
channel = msg->channel_request.channel->remote_channel;
ssh_log(msg->session, SSH_LOG_PACKET,
"Sending a channel_request success to channel %d", channel);
if (buffer_add_u8(msg->session->out_buffer, SSH2_MSG_CHANNEL_SUCCESS) < 0) {
return SSH_ERROR;
}
if (buffer_add_u32(msg->session->out_buffer, htonl(channel)) < 0) {
return SSH_ERROR;
}
return packet_send(msg->session);
}
ssh_log(msg->session, SSH_LOG_PACKET,
"The client doesn't want to know the request succeeded");
return SSH_OK;
}
ssh_message ssh_message_retrieve(ssh_session session, uint32_t packettype){
ssh_message msg=NULL;
enter_function();
switch(packettype) {
case SSH2_MSG_SERVICE_REQUEST:
msg=handle_service_request(session);
break;
case SSH2_MSG_USERAUTH_REQUEST:
msg = handle_userauth_request(session);
break;
case SSH2_MSG_CHANNEL_OPEN:
msg = handle_channel_request_open(session);
break;
case SSH2_MSG_CHANNEL_REQUEST:
msg = handle_channel_request(session);
break;
default:
if (handle_unimplemented(session) == 0) {
ssh_set_error(session, SSH_FATAL,
"Unhandled message %d\n", session->in_packet.type);
}
}
leave_function();
return msg;
}
/* \brief blocking message retrieval
* \bug does anything that is not a message, like a channel read/write
*/
ssh_message ssh_message_get(ssh_session session) {
ssh_message msg = NULL;
enter_function();
do {
if ((packet_read(session) != SSH_OK) ||
(packet_translate(session) != SSH_OK)) {
leave_function();
return NULL;
}
} while(session->in_packet.type==SSH2_MSG_IGNORE || session->in_packet.type==SSH2_MSG_DEBUG);
msg=ssh_message_retrieve(session,session->in_packet.type);
leave_function();
return msg;
}
int ssh_message_type(ssh_message msg) {
if (msg == NULL) {
return -1;
}
return msg->type;
}
int ssh_message_subtype(ssh_message msg) {
if (msg == NULL) {
return -1;
}
switch(msg->type) {
case SSH_REQUEST_AUTH:
return msg->auth_request.method;
case SSH_REQUEST_CHANNEL_OPEN:
return msg->channel_request_open.type;
case SSH_REQUEST_CHANNEL:
return msg->channel_request.type;
}
return -1;
}
void ssh_message_free(ssh_message msg){
if (msg == NULL) {
return;
}
switch(msg->type) {
case SSH_REQUEST_AUTH:
SAFE_FREE(msg->auth_request.username);
if (msg->auth_request.password) {
memset(msg->auth_request.password, 0,
strlen(msg->auth_request.password));
SAFE_FREE(msg->auth_request.password);
}
publickey_free(msg->auth_request.public_key);
break;
case SSH_REQUEST_CHANNEL_OPEN:
SAFE_FREE(msg->channel_request_open.originator);
SAFE_FREE(msg->channel_request_open.destination);
break;
case SSH_REQUEST_CHANNEL:
SAFE_FREE(msg->channel_request.TERM);
SAFE_FREE(msg->channel_request.modes);
SAFE_FREE(msg->channel_request.var_name);
SAFE_FREE(msg->channel_request.var_value);
SAFE_FREE(msg->channel_request.command);
SAFE_FREE(msg->channel_request.subsystem);
break;
case SSH_REQUEST_SERVICE:
SAFE_FREE(msg->service_request.service);
break;
}
ZERO_STRUCTP(msg);
SAFE_FREE(msg);
}
/** \internal
* \brief handle various SSH request messages and stack them for callback
* \param session SSH session
* \param type packet type
* \returns nothing
*/
void message_handle(ssh_session session, uint32_t type){
ssh_message msg=ssh_message_retrieve(session,type);
ssh_log(session,SSH_LOG_PROTOCOL,"Stacking message from packet type %d",type);
if(msg){
if(!session->ssh_message_list){
session->ssh_message_list=ssh_list_new();
}
ssh_list_append(session->ssh_message_list,msg);
}
}
/**
* @}
*/
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/messages.c
|
C
|
gpl3
| 23,313
|
/*
* buffer.c - buffer functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2003-2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "libssh/priv.h"
#include "libssh/buffer.h"
/** \defgroup ssh_buffer SSH Buffers
* \brief buffer handling
*/
/** \addtogroup ssh_buffer
* @{
*/
/** \brief checks that preconditions and postconditions are valid
* \internal
*/
#ifdef DEBUG_BUFFER
static void buffer_verify(struct buffer_struct *buf){
int doabort=0;
if(buf->data == NULL)
return;
if(buf->used > buf->allocated){
fprintf(stderr,"Buffer error : allocated %u, used %u\n",buf->allocated, buf->used);
doabort=1;
}
if(buf->pos > buf->used){
fprintf(stderr,"Buffer error : position %u, used %u\n",buf->pos, buf->used);
doabort=1;
}
if(buf->pos > buf->allocated){
fprintf(stderr,"Buffer error : position %u, allocated %u\n",buf->pos, buf->allocated);
doabort=1;
}
if(doabort)
abort();
}
#else
#define buffer_verify(x)
#endif
/** \brief creates a new buffer
* \return a new initialized buffer, NULL on error.
*/
struct ssh_buffer_struct *buffer_new(void) {
struct ssh_buffer_struct *buf = malloc(sizeof(struct ssh_buffer_struct));
if (buf == NULL) {
return NULL;
}
memset(buf, 0, sizeof(struct ssh_buffer_struct));
buffer_verify(buf);
return buf;
}
/** \brief deallocate a buffer
* \param buffer buffer to free
*/
void buffer_free(struct ssh_buffer_struct *buffer) {
if (buffer == NULL) {
return;
}
buffer_verify(buffer);
if (buffer->data) {
/* burn the data */
memset(buffer->data, 0, buffer->allocated);
SAFE_FREE(buffer->data);
}
memset(buffer, 'X', sizeof(*buffer));
SAFE_FREE(buffer);
}
static int realloc_buffer(struct ssh_buffer_struct *buffer, int needed) {
int smallest = 1;
char *new = NULL;
buffer_verify(buffer);
/* Find the smallest power of two which is greater or equal to needed */
while(smallest < needed) {
smallest <<= 1;
}
needed = smallest;
new = realloc(buffer->data, needed);
if (new == NULL) {
return -1;
}
buffer->data = new;
buffer->allocated = needed;
buffer_verify(buffer);
return 0;
}
/* \internal
* \brief reinitialize a buffer
* \param buffer buffer
* \return 0 on sucess, < 0 on error
*/
int buffer_reinit(struct ssh_buffer_struct *buffer) {
buffer_verify(buffer);
memset(buffer->data, 0, buffer->used);
buffer->used = 0;
buffer->pos = 0;
if(buffer->allocated > 127) {
if (realloc_buffer(buffer, 127) < 0) {
return -1;
}
}
buffer_verify(buffer);
return 0;
}
/** \internal
* \brief add data at tail of the buffer
* \param buffer buffer
* \param data data pointer
* \param len length of data
*/
int buffer_add_data(struct ssh_buffer_struct *buffer, const void *data, uint32_t len) {
buffer_verify(buffer);
if (buffer->allocated < (buffer->used + len)) {
if (realloc_buffer(buffer, buffer->used + len) < 0) {
return -1;
}
}
memcpy(buffer->data+buffer->used, data, len);
buffer->used+=len;
buffer_verify(buffer);
return 0;
}
/** \internal
* \brief add a SSH string to the tail of buffer
* \param buffer buffer
* \param string SSH String to add
* \return 0 on success, -1 on error.
*/
int buffer_add_ssh_string(struct ssh_buffer_struct *buffer,
struct ssh_string_struct *string) {
uint32_t len = 0;
len = string_len(string);
if (buffer_add_data(buffer, string, len + sizeof(uint32_t)) < 0) {
return -1;
}
return 0;
}
/** \internal
* \brief add a 32 bits unsigned integer to the tail of buffer
* \param buffer buffer
* \param data 32 bits integer
* \return 0 on success, -1 on error.
*/
int buffer_add_u32(struct ssh_buffer_struct *buffer,uint32_t data){
if (buffer_add_data(buffer, &data, sizeof(data)) < 0) {
return -1;
}
return 0;
}
/** \internal
* \brief add a 16 bits unsigned integer to the tail of buffer
* \param buffer buffer
* \param data 16 bits integer
* \return 0 on success, -1 on error.
*/
int buffer_add_u16(struct ssh_buffer_struct *buffer,uint16_t data){
if (buffer_add_data(buffer, &data, sizeof(data)) < 0) {
return -1;
}
return 0;
}
/** \internal
* \brief add a 64 bits unsigned integer to the tail of buffer
* \param buffer buffer
* \param data 64 bits integer
* \return 0 on success, -1 on error.
*/
int buffer_add_u64(struct ssh_buffer_struct *buffer, uint64_t data){
if (buffer_add_data(buffer, &data, sizeof(data)) < 0) {
return -1;
}
return 0;
}
/** \internal
* \brief add a 8 bits unsigned integer to the tail of buffer
* \param buffer buffer
* \param data 8 bits integer
* \return 0 on success, -1 on error.
*/
int buffer_add_u8(struct ssh_buffer_struct *buffer,uint8_t data){
if (buffer_add_data(buffer, &data, sizeof(uint8_t)) < 0) {
return -1;
}
return 0;
}
/** \internal
* \brief add data at head of a buffer
* \param buffer buffer
* \param data data to add
* \param len length of data
* \return 0 on success, -1 on error.
*/
int buffer_prepend_data(struct ssh_buffer_struct *buffer, const void *data,
uint32_t len) {
buffer_verify(buffer);
if (buffer->allocated < (buffer->used + len)) {
if (realloc_buffer(buffer, buffer->used + len) < 0) {
return -1;
}
}
memmove(buffer->data + len, buffer->data, buffer->used);
memcpy(buffer->data, data, len);
buffer->used += len;
buffer_verify(buffer);
return 0;
}
/** \internal
* \brief append data from a buffer to tail of another
* \param buffer destination buffer
* \param source source buffer. Doesn't take position in buffer into account
* \return 0 on success, -1 on error.
*/
int buffer_add_buffer(struct ssh_buffer_struct *buffer,
struct ssh_buffer_struct *source) {
if (buffer_add_data(buffer, buffer_get(source), buffer_get_len(source)) < 0) {
return -1;
}
return 0;
}
/** \brief get a pointer on the head of the buffer
* \param buffer buffer
* \return data pointer on the head. Doesn't take position into account.
* \warning don't expect data to be nul-terminated
* \see buffer_get_rest()
* \see buffer_get_len()
*/
void *buffer_get(struct ssh_buffer_struct *buffer){
return buffer->data;
}
/** \internal
* \brief get a pointer to head of the buffer at current position
* \param buffer buffer
* \return pointer to the data from current position
* \see buffer_get_rest_len()
* \see buffer_get()
*/
void *buffer_get_rest(struct ssh_buffer_struct *buffer){
return buffer->data + buffer->pos;
}
/** \brief get length of the buffer, not counting position
* \param buffer
* \return length of the buffer
* \see buffer_get()
*/
uint32_t buffer_get_len(struct ssh_buffer_struct *buffer){
return buffer->used;
}
/** \internal
* \brief get length of the buffer from the current position
* \param buffer
* \return length of the buffer
* \see buffer_get_rest()
*/
uint32_t buffer_get_rest_len(struct ssh_buffer_struct *buffer){
buffer_verify(buffer);
return buffer->used - buffer->pos;
}
/** \internal
* has effect to "eat" bytes at head of the buffer
* \brief advance the position in the buffer
* \param buffer buffer
* \param len number of bytes to eat
* \return new size of the buffer
*/
uint32_t buffer_pass_bytes(struct ssh_buffer_struct *buffer, uint32_t len){
buffer_verify(buffer);
if(buffer->used < buffer->pos+len)
return 0;
buffer->pos+=len;
/* if the buffer is empty after having passed the whole bytes into it, we can clean it */
if(buffer->pos==buffer->used){
buffer->pos=0;
buffer->used=0;
}
buffer_verify(buffer);
return len;
}
/** \internal
* \brief cut the end of the buffer
* \param buffer buffer
* \param len number of bytes to remove from tail
* \return new size of the buffer
*/
uint32_t buffer_pass_bytes_end(struct ssh_buffer_struct *buffer, uint32_t len){
buffer_verify(buffer);
if(buffer->used < buffer->pos + len)
return 0;
buffer->used-=len;
buffer_verify(buffer);
return len;
}
/** \internal
* \brief gets remaining data out of the buffer. Adjust the read pointer.
* \param buffer Buffer to read
* \param data data buffer where to store the data
* \param len length to read from the buffer
* \returns 0 if there is not enough data in buffer
* \returns len otherwise.
*/
uint32_t buffer_get_data(struct ssh_buffer_struct *buffer, void *data, uint32_t len){
/*
* Check for a integer overflow first, then check if not enough data is in
* the buffer.
*/
if (buffer->pos + len < len || buffer->pos + len > buffer->used) {
return 0;
}
memcpy(data,buffer->data+buffer->pos,len);
buffer->pos+=len;
return len; /* no yet support for partial reads (is it really needed ?? ) */
}
/** \internal
* \brief gets a 8 bits unsigned int out of the buffer. Adjusts the read pointer.
* \param buffer Buffer to read
* \param data pointer to a uint8_t where to store the data
* \returns 0 if there is not enough data in buffer
* \returns 1 otherwise.
*/
int buffer_get_u8(struct ssh_buffer_struct *buffer, uint8_t *data){
return buffer_get_data(buffer,data,sizeof(uint8_t));
}
/** \internal
* \brief gets a 32 bits unsigned int out of the buffer. Adjusts the read pointer.
* \param buffer Buffer to read
* \param data pointer to a uint32_t where to store the data
* \returns 0 if there is not enough data in buffer
* \returns 4 otherwise.
*/
int buffer_get_u32(struct ssh_buffer_struct *buffer, uint32_t *data){
return buffer_get_data(buffer,data,sizeof(uint32_t));
}
/** \internal
* \brief gets a 64 bits unsigned int out of the buffer. Adjusts the read pointer.
* \param buffer Buffer to read
* \param data pointer to a uint64_t where to store the data
* \returns 0 if there is not enough data in buffer
* \returns 8 otherwise.
*/
int buffer_get_u64(struct ssh_buffer_struct *buffer, uint64_t *data){
return buffer_get_data(buffer,data,sizeof(uint64_t));
}
/** \internal
* \brief gets a SSH String out of the buffer. Adjusts the read pointer.
* \param buffer Buffer to read
* \returns The SSH String read
* \returns NULL otherwise.
*/
struct ssh_string_struct *buffer_get_ssh_string(struct ssh_buffer_struct *buffer) {
uint32_t stringlen;
uint32_t hostlen;
struct ssh_string_struct *str = NULL;
if (buffer_get_u32(buffer, &stringlen) == 0) {
return NULL;
}
hostlen = ntohl(stringlen);
/* verify if there is enough space in buffer to get it */
if ((buffer->pos + hostlen) > buffer->used) {
return NULL; /* it is indeed */
}
str = string_new(hostlen);
if (str == NULL) {
return NULL;
}
if (buffer_get_data(buffer, string_data(str), hostlen) != hostlen) {
/* should never happen */
SAFE_FREE(str);
return NULL;
}
return str;
}
/** \internal
* \brief gets a mpint out of the buffer. Adjusts the read pointer.
* SSH-1 only
* \param buffer Buffer to read
* \returns the SSH String containing the mpint
* \returns NULL otherwise
*/
struct ssh_string_struct *buffer_get_mpint(struct ssh_buffer_struct *buffer) {
uint16_t bits;
uint32_t len;
struct ssh_string_struct *str = NULL;
if (buffer_get_data(buffer, &bits, sizeof(uint16_t)) != sizeof(uint16_t)) {
return NULL;
}
bits = ntohs(bits);
len = (bits + 7) / 8;
if ((buffer->pos + len) > buffer->used) {
return NULL;
}
str = string_new(len);
if (str == NULL) {
return NULL;
}
if (buffer_get_data(buffer, string_data(str), len) != len) {
SAFE_FREE(str);
return NULL;
}
return str;
}
/** @} */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/buffer.c
|
C
|
gpl3
| 12,443
|
/*
* config.c - parse the ssh config file
*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Andreas Schneider <mail@cynapses.org>
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "libssh/priv.h"
#include "libssh/session.h"
enum ssh_config_opcode_e {
SOC_UNSUPPORTED = -1,
SOC_HOST,
SOC_HOSTNAME,
SOC_PORT,
SOC_USERNAME,
SOC_IDENTITY,
SOC_CIPHERS,
SOC_COMPRESSION,
SOC_TIMEOUT,
SOC_PROTOCOL,
SOC_PROXYCOMMAND
};
struct ssh_config_keyword_table_s {
const char *name;
enum ssh_config_opcode_e opcode;
};
static struct ssh_config_keyword_table_s ssh_config_keyword_table[] = {
{ "host", SOC_HOST },
{ "hostname", SOC_HOSTNAME },
{ "port", SOC_PORT },
{ "user", SOC_USERNAME },
{ "identityfile", SOC_IDENTITY },
{ "ciphers", SOC_CIPHERS },
{ "compression", SOC_COMPRESSION },
{ "connecttimeout", SOC_TIMEOUT },
{ "protocol", SOC_PROTOCOL },
{ "proxycommand", SOC_PROXYCOMMAND },
{ NULL, SOC_UNSUPPORTED }
};
static enum ssh_config_opcode_e ssh_config_get_opcode(char *keyword) {
int i;
for (i = 0; ssh_config_keyword_table[i].name != NULL; i++) {
if (strcasecmp(keyword, ssh_config_keyword_table[i].name) == 0) {
return ssh_config_keyword_table[i].opcode;
}
}
return SOC_UNSUPPORTED;
}
static char *ssh_config_get_token(char **str) {
register char *c;
char *r;
/* Ignore leading spaces */
for (c = *str; *c; c++) {
if (! isblank(*c)) {
break;
}
}
if (*c == '\"') {
for (r = ++c; *c; c++) {
if (*c == '\"') {
*c = '\0';
goto out;
}
}
}
for (r = c; *c; c++) {
if (isblank(*c)) {
*c = '\0';
goto out;
}
}
out:
*str = c + 1;
return r;
}
static int ssh_config_get_int(char **str, int notfound) {
char *p, *endp;
int i;
p = ssh_config_get_token(str);
if (p && *p) {
i = strtol(p, &endp, 10);
if (p == endp) {
return notfound;
}
return i;
}
return notfound;
}
static const char *ssh_config_get_str(char **str, const char *def) {
char *p;
p = ssh_config_get_token(str);
if (p && *p) {
return p;
}
return def;
}
static int ssh_config_get_yesno(char **str, int notfound) {
const char *p;
p = ssh_config_get_str(str, NULL);
if (p == NULL) {
return notfound;
}
if (strncasecmp(p, "yes", 3) == 0) {
return 1;
} else if (strncasecmp(p, "no", 2) == 0) {
return 0;
}
return notfound;
}
static int ssh_config_parse_line(ssh_session session, const char *line,
unsigned int count, int *parsing) {
enum ssh_config_opcode_e opcode;
const char *p;
char *s, *x;
char *keyword;
size_t len;
int i;
x = s = strdup(line);
if (s == NULL) {
ssh_set_error_oom(session);
return -1;
}
/* Remove trailing spaces */
for (len = strlen(s) - 1; len > 0; len--) {
if (! isspace(s[len])) {
break;
}
s[len] = '\0';
}
keyword = ssh_config_get_token(&s);
if (keyword == NULL || *keyword == '#' ||
*keyword == '\0' || *keyword == '\n') {
SAFE_FREE(x);
return 0;
}
opcode = ssh_config_get_opcode(keyword);
switch (opcode) {
case SOC_HOST:
*parsing = 0;
for (p = ssh_config_get_str(&s, NULL); p && *p;
p = ssh_config_get_str(&s, NULL)) {
if (match_hostname(session->host, p, strlen(p))) {
*parsing = 1;
}
}
break;
case SOC_HOSTNAME:
p = ssh_config_get_str(&s, NULL);
if (p && *parsing) {
ssh_options_set(session, SSH_OPTIONS_HOST, p);
}
break;
case SOC_PORT:
if (session->port == 22) {
p = ssh_config_get_str(&s, NULL);
if (p && *parsing) {
ssh_options_set(session, SSH_OPTIONS_PORT_STR, p);
}
}
break;
case SOC_USERNAME:
if (session->username == NULL) {
p = ssh_config_get_str(&s, NULL);
if (p && *parsing) {
ssh_options_set(session, SSH_OPTIONS_USER, p);
}
}
break;
case SOC_IDENTITY:
p = ssh_config_get_str(&s, NULL);
if (p && *parsing) {
ssh_options_set(session, SSH_OPTIONS_ADD_IDENTITY, p);
}
break;
case SOC_CIPHERS:
p = ssh_config_get_str(&s, NULL);
if (p && *parsing) {
ssh_options_set(session, SSH_OPTIONS_CIPHERS_C_S, p);
ssh_options_set(session, SSH_OPTIONS_CIPHERS_S_C, p);
}
break;
case SOC_COMPRESSION:
i = ssh_config_get_yesno(&s, -1);
if (i >= 0 && *parsing) {
if (i) {
ssh_options_set(session, SSH_OPTIONS_COMPRESSION_C_S, "zlib,none");
ssh_options_set(session, SSH_OPTIONS_COMPRESSION_S_C, "zlib,none");
} else {
ssh_options_set(session, SSH_OPTIONS_COMPRESSION_C_S, "none");
ssh_options_set(session, SSH_OPTIONS_COMPRESSION_S_C, "none");
}
}
break;
case SOC_PROTOCOL:
p = ssh_config_get_str(&s, NULL);
if (p && *parsing) {
char *a, *b;
b = strdup(p);
if (b == NULL) {
SAFE_FREE(x);
ssh_set_error_oom(session);
return -1;
}
i = 0;
ssh_options_set(session, SSH_OPTIONS_SSH1, &i);
ssh_options_set(session, SSH_OPTIONS_SSH2, &i);
for (a = strtok(b, ","); a; a = strtok(NULL, ",")) {
switch (atoi(a)) {
case 1:
i = 1;
ssh_options_set(session, SSH_OPTIONS_SSH1, &i);
break;
case 2:
i = 1;
ssh_options_set(session, SSH_OPTIONS_SSH2, &i);
break;
default:
break;
}
}
SAFE_FREE(b);
}
break;
case SOC_TIMEOUT:
i = ssh_config_get_int(&s, -1);
if (i >= 0 && *parsing) {
ssh_options_set(session, SSH_OPTIONS_TIMEOUT, &i);
}
break;
case SOC_PROXYCOMMAND:
p = ssh_config_get_str(&s, NULL);
if (p && *parsing) {
ssh_options_set(session, SSH_OPTIONS_PROXYCOMMAND, p);
}
break;
case SOC_UNSUPPORTED:
fprintf(stderr, "Unsupported option: %s, line: %d\n", keyword, count);
break;
default:
fprintf(stderr, "ERROR - unimplemented opcode: %d\n", opcode);
SAFE_FREE(x);
return -1;
break;
}
SAFE_FREE(x);
return 0;
}
/* ssh_config_parse_file */
int ssh_config_parse_file(ssh_session session, const char *filename) {
char line[1024] = {0};
unsigned int count = 0;
FILE *f;
int parsing;
if ((f = fopen(filename, "r")) == NULL) {
return 0;
}
if (session->log_verbosity) {
fprintf(stderr, "Reading configuration data from %s\n", filename);
}
parsing = 1;
while (fgets(line, sizeof(line), f)) {
count++;
if (ssh_config_parse_line(session, line, count, &parsing) < 0) {
fclose(f);
return -1;
}
}
fclose(f);
return 0;
}
|
zzlydm-fbbs
|
libssh/config.c
|
C
|
gpl3
| 7,707
|
/*
* wrapper.c - wrapper for crytpo functions
*
* This file is part of the SSH Library
*
* Copyright (c) 2003 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/*
* Why a wrapper?
*
* Let's say you want to port libssh from libcrypto of openssl to libfoo
* you are going to spend hours to remove every references to SHA1_Update()
* to libfoo_sha1_update after the work is finished, you're going to have
* only this file to modify it's not needed to say that your modifications
* are welcome.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "libssh/priv.h"
#include "libssh/session.h"
#include "libssh/crypto.h"
#include "libssh/wrapper.h"
#ifdef HAVE_LIBGCRYPT
#include <gcrypt.h>
static int alloc_key(struct crypto_struct *cipher) {
cipher->key = malloc(cipher->keylen);
if (cipher->key == NULL) {
return -1;
}
return 0;
}
SHACTX sha1_init(void) {
SHACTX ctx = NULL;
gcry_md_open(&ctx, GCRY_MD_SHA1, 0);
return ctx;
}
void sha1_update(SHACTX c, const void *data, unsigned long len) {
gcry_md_write(c, data, len);
}
void sha1_final(unsigned char *md, SHACTX c) {
gcry_md_final(c);
memcpy(md, gcry_md_read(c, 0), SHA_DIGEST_LEN);
gcry_md_close(c);
}
void sha1(unsigned char *digest, int len, unsigned char *hash) {
gcry_md_hash_buffer(GCRY_MD_SHA1, hash, digest, len);
}
MD5CTX md5_init(void) {
MD5CTX c = NULL;
gcry_md_open(&c, GCRY_MD_MD5, 0);
return c;
}
void md5_update(MD5CTX c, const void *data, unsigned long len) {
gcry_md_write(c,data,len);
}
void md5_final(unsigned char *md, MD5CTX c) {
gcry_md_final(c);
memcpy(md, gcry_md_read(c, 0), MD5_DIGEST_LEN);
gcry_md_close(c);
}
HMACCTX hmac_init(const void *key, int len, int type) {
HMACCTX c = NULL;
switch(type) {
case HMAC_SHA1:
gcry_md_open(&c, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC);
break;
case HMAC_MD5:
gcry_md_open(&c, GCRY_MD_MD5, GCRY_MD_FLAG_HMAC);
break;
default:
c = NULL;
}
gcry_md_setkey(c, key, len);
return c;
}
void hmac_update(HMACCTX c, const void *data, unsigned long len) {
gcry_md_write(c, data, len);
}
void hmac_final(HMACCTX c, unsigned char *hashmacbuf, unsigned int *len) {
*len = gcry_md_get_algo_dlen(gcry_md_get_algo(c));
memcpy(hashmacbuf, gcry_md_read(c, 0), *len);
gcry_md_close(c);
}
/* the wrapper functions for blowfish */
static int blowfish_set_key(struct crypto_struct *cipher, void *key, void *IV){
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
if (gcry_cipher_open(&cipher->key[0], GCRY_CIPHER_BLOWFISH,
GCRY_CIPHER_MODE_CBC, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setkey(cipher->key[0], key, 16)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setiv(cipher->key[0], IV, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
}
return 0;
}
static void blowfish_encrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len) {
gcry_cipher_encrypt(cipher->key[0], out, len, in, len);
}
static void blowfish_decrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len) {
gcry_cipher_decrypt(cipher->key[0], out, len, in, len);
}
static int aes_set_key(struct crypto_struct *cipher, void *key, void *IV) {
int mode=GCRY_CIPHER_MODE_CBC;
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
if(strstr(cipher->name,"-ctr"))
mode=GCRY_CIPHER_MODE_CTR;
switch (cipher->keysize) {
case 128:
if (gcry_cipher_open(&cipher->key[0], GCRY_CIPHER_AES128,
mode, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
break;
case 192:
if (gcry_cipher_open(&cipher->key[0], GCRY_CIPHER_AES192,
mode, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
break;
case 256:
if (gcry_cipher_open(&cipher->key[0], GCRY_CIPHER_AES256,
mode, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
break;
}
if (gcry_cipher_setkey(cipher->key[0], key, cipher->keysize / 8)) {
SAFE_FREE(cipher->key);
return -1;
}
if(mode == GCRY_CIPHER_MODE_CBC){
if (gcry_cipher_setiv(cipher->key[0], IV, 16)) {
SAFE_FREE(cipher->key);
return -1;
}
} else {
if(gcry_cipher_setctr(cipher->key[0],IV,16)){
SAFE_FREE(cipher->key);
return -1;
}
}
}
return 0;
}
static void aes_encrypt(struct crypto_struct *cipher, void *in, void *out,
unsigned long len) {
gcry_cipher_encrypt(cipher->key[0], out, len, in, len);
}
static void aes_decrypt(struct crypto_struct *cipher, void *in, void *out,
unsigned long len) {
gcry_cipher_decrypt(cipher->key[0], out, len, in, len);
}
static int des3_set_key(struct crypto_struct *cipher, void *key, void *IV) {
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
if (gcry_cipher_open(&cipher->key[0], GCRY_CIPHER_3DES,
GCRY_CIPHER_MODE_CBC, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setkey(cipher->key[0], key, 24)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setiv(cipher->key[0], IV, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
}
return 0;
}
static void des3_encrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len) {
gcry_cipher_encrypt(cipher->key[0], out, len, in, len);
}
static void des3_decrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len) {
gcry_cipher_decrypt(cipher->key[0], out, len, in, len);
}
static int des3_1_set_key(struct crypto_struct *cipher, void *key, void *IV) {
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
if (gcry_cipher_open(&cipher->key[0], GCRY_CIPHER_DES,
GCRY_CIPHER_MODE_CBC, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setkey(cipher->key[0], key, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setiv(cipher->key[0], IV, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_open(&cipher->key[1], GCRY_CIPHER_DES,
GCRY_CIPHER_MODE_CBC, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setkey(cipher->key[1], (unsigned char *)key + 8, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setiv(cipher->key[1], (unsigned char *)IV + 8, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_open(&cipher->key[2], GCRY_CIPHER_DES,
GCRY_CIPHER_MODE_CBC, 0)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setkey(cipher->key[2], (unsigned char *)key + 16, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
if (gcry_cipher_setiv(cipher->key[2], (unsigned char *)IV + 16, 8)) {
SAFE_FREE(cipher->key);
return -1;
}
}
return 0;
}
static void des3_1_encrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len) {
gcry_cipher_encrypt(cipher->key[0], out, len, in, len);
gcry_cipher_decrypt(cipher->key[1], in, len, out, len);
gcry_cipher_encrypt(cipher->key[2], out, len, in, len);
}
static void des3_1_decrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len) {
gcry_cipher_decrypt(cipher->key[2], out, len, in, len);
gcry_cipher_encrypt(cipher->key[1], in, len, out, len);
gcry_cipher_decrypt(cipher->key[0], out, len, in, len);
}
/* the table of supported ciphers */
static struct crypto_struct ssh_ciphertab[] = {
{
.name = "blowfish-cbc",
.blocksize = 8,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 128,
.set_encrypt_key = blowfish_set_key,
.set_decrypt_key = blowfish_set_key,
.cbc_encrypt = blowfish_encrypt,
.cbc_decrypt = blowfish_decrypt
},
{
.name = "aes128-ctr",
.blocksize = 16,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 128,
.set_encrypt_key = aes_set_key,
.set_decrypt_key = aes_set_key,
.cbc_encrypt = aes_encrypt,
.cbc_decrypt = aes_encrypt
},
{
.name = "aes192-ctr",
.blocksize = 16,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 192,
.set_encrypt_key = aes_set_key,
.set_decrypt_key = aes_set_key,
.cbc_encrypt = aes_encrypt,
.cbc_decrypt = aes_encrypt
},
{
.name = "aes256-ctr",
.blocksize = 16,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 256,
.set_encrypt_key = aes_set_key,
.set_decrypt_key = aes_set_key,
.cbc_encrypt = aes_encrypt,
.cbc_decrypt = aes_encrypt
},
{
.name = "aes128-cbc",
.blocksize = 16,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 128,
.set_encrypt_key = aes_set_key,
.set_decrypt_key = aes_set_key,
.cbc_encrypt = aes_encrypt,
.cbc_decrypt = aes_decrypt
},
{
.name = "aes192-cbc",
.blocksize = 16,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 192,
.set_encrypt_key = aes_set_key,
.set_decrypt_key = aes_set_key,
.cbc_encrypt = aes_encrypt,
.cbc_decrypt = aes_decrypt
},
{
.name = "aes256-cbc",
.blocksize = 16,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 256,
.set_encrypt_key = aes_set_key,
.set_decrypt_key = aes_set_key,
.cbc_encrypt = aes_encrypt,
.cbc_decrypt = aes_decrypt
},
{
.name = "3des-cbc",
.blocksize = 8,
.keylen = sizeof(gcry_cipher_hd_t),
.key = NULL,
.keysize = 192,
.set_encrypt_key = des3_set_key,
.set_decrypt_key = des3_set_key,
.cbc_encrypt = des3_encrypt,
.cbc_decrypt = des3_decrypt
},
{
.name = "3des-cbc-ssh1",
.blocksize = 8,
.keylen = sizeof(gcry_cipher_hd_t) * 3,
.key = NULL,
.keysize = 192,
.set_encrypt_key = des3_1_set_key,
.set_decrypt_key = des3_1_set_key,
.cbc_encrypt = des3_1_encrypt,
.cbc_decrypt = des3_1_decrypt
},
{
.name = NULL,
.blocksize = 0,
.keylen = 0,
.key = NULL,
.keysize = 0,
.set_encrypt_key = NULL,
.set_decrypt_key = NULL,
.cbc_encrypt = NULL,
.cbc_decrypt = NULL
}
};
#elif defined HAVE_LIBCRYPTO
#include <openssl/sha.h>
#include <openssl/md5.h>
#include <openssl/dsa.h>
#include <openssl/rsa.h>
#include <openssl/hmac.h>
#include <openssl/opensslv.h>
#ifdef HAVE_OPENSSL_AES_H
#define HAS_AES
#include <openssl/aes.h>
#endif
#ifdef HAVE_OPENSSL_BLOWFISH_H
#define HAS_BLOWFISH
#include <openssl/blowfish.h>
#endif
#ifdef HAVE_OPENSSL_DES_H
#define HAS_DES
#include <openssl/des.h>
#endif
#if (OPENSSL_VERSION_NUMBER<0x00907000L)
#define OLD_CRYPTO
#endif
#include "libssh/crypto.h"
static int alloc_key(struct crypto_struct *cipher) {
cipher->key = malloc(cipher->keylen);
if (cipher->key == NULL) {
return -1;
}
return 0;
}
SHACTX sha1_init(void) {
SHACTX c = malloc(sizeof(*c));
if (c == NULL) {
return NULL;
}
SHA1_Init(c);
return c;
}
void sha1_update(SHACTX c, const void *data, unsigned long len) {
SHA1_Update(c,data,len);
}
void sha1_final(unsigned char *md, SHACTX c) {
SHA1_Final(md, c);
SAFE_FREE(c);
}
void sha1(unsigned char *digest, int len, unsigned char *hash) {
SHA1(digest, len, hash);
}
MD5CTX md5_init(void) {
MD5CTX c = malloc(sizeof(*c));
if (c == NULL) {
return NULL;
}
MD5_Init(c);
return c;
}
void md5_update(MD5CTX c, const void *data, unsigned long len) {
MD5_Update(c, data, len);
}
void md5_final(unsigned char *md, MD5CTX c) {
MD5_Final(md,c);
SAFE_FREE(c);
}
HMACCTX hmac_init(const void *key, int len, int type) {
HMACCTX ctx = NULL;
ctx = malloc(sizeof(*ctx));
if (ctx == NULL) {
return NULL;
}
#ifndef OLD_CRYPTO
HMAC_CTX_init(ctx); // openssl 0.9.7 requires it.
#endif
switch(type) {
case HMAC_SHA1:
HMAC_Init(ctx, key, len, EVP_sha1());
break;
case HMAC_MD5:
HMAC_Init(ctx, key, len, EVP_md5());
break;
default:
SAFE_FREE(ctx);
ctx = NULL;
}
return ctx;
}
void hmac_update(HMACCTX ctx, const void *data, unsigned long len) {
HMAC_Update(ctx, data, len);
}
void hmac_final(HMACCTX ctx, unsigned char *hashmacbuf, unsigned int *len) {
HMAC_Final(ctx,hashmacbuf,len);
#ifndef OLD_CRYPTO
HMAC_CTX_cleanup(ctx);
#else
HMAC_cleanup(ctx);
#endif
SAFE_FREE(ctx);
}
#ifdef HAS_BLOWFISH
/* the wrapper functions for blowfish */
static int blowfish_set_key(struct crypto_struct *cipher, void *key){
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
BF_set_key(cipher->key, 16, key);
}
return 0;
}
static void blowfish_encrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len, void *IV) {
BF_cbc_encrypt(in, out, len, cipher->key, IV, BF_ENCRYPT);
}
static void blowfish_decrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len, void *IV) {
BF_cbc_encrypt(in, out, len, cipher->key, IV, BF_DECRYPT);
}
#endif /* HAS_BLOWFISH */
#ifdef HAS_AES
static int aes_set_encrypt_key(struct crypto_struct *cipher, void *key) {
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
if (AES_set_encrypt_key(key,cipher->keysize,cipher->key) < 0) {
SAFE_FREE(cipher->key);
return -1;
}
}
return 0;
}
static int aes_set_decrypt_key(struct crypto_struct *cipher, void *key) {
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
if (AES_set_decrypt_key(key,cipher->keysize,cipher->key) < 0) {
SAFE_FREE(cipher->key);
return -1;
}
}
return 0;
}
static void aes_encrypt(struct crypto_struct *cipher, void *in, void *out,
unsigned long len, void *IV) {
AES_cbc_encrypt(in, out, len, cipher->key, IV, AES_ENCRYPT);
}
static void aes_decrypt(struct crypto_struct *cipher, void *in, void *out,
unsigned long len, void *IV) {
AES_cbc_encrypt(in, out, len, cipher->key, IV, AES_DECRYPT);
}
#ifndef BROKEN_AES_CTR
/* OpenSSL until 0.9.7c has a broken AES_ctr128_encrypt implementation which
* increments the counter from 2^64 instead of 1. It's better not to use it
*/
/** @internal
* @brief encrypts/decrypts data with stream cipher AES_ctr128. 128 bits is actually
* the size of the CTR counter and incidentally the blocksize, but not the keysize.
* @param len[in] must be a multiple of AES128 block size.
*/
static void aes_ctr128_encrypt(struct crypto_struct *cipher, void *in, void *out,
unsigned long len, void *IV) {
unsigned char tmp_buffer[128/8];
unsigned int num=0;
/* Some things are special with ctr128 :
* In this case, tmp_buffer is not being used, because it is used to store temporary data
* when an encryption is made on lengths that are not multiple of blocksize.
* Same for num, which is being used to store the current offset in blocksize in CTR
* function.
*/
AES_ctr128_encrypt(in, out, len, cipher->key, IV, tmp_buffer, &num);
}
#endif /* BROKEN_AES_CTR */
#endif /* HAS_AES */
#ifdef HAS_DES
static int des3_set_key(struct crypto_struct *cipher, void *key) {
if (cipher->key == NULL) {
if (alloc_key(cipher) < 0) {
return -1;
}
DES_set_odd_parity(key);
DES_set_odd_parity((void*)((uint8_t*)key + 8));
DES_set_odd_parity((void*)((uint8_t*)key + 16));
DES_set_key_unchecked(key, cipher->key);
DES_set_key_unchecked((void*)((uint8_t*)key + 8), (void*)((uint8_t*)cipher->key + sizeof(DES_key_schedule)));
DES_set_key_unchecked((void*)((uint8_t*)key + 16), (void*)((uint8_t*)cipher->key + 2 * sizeof(DES_key_schedule)));
}
return 0;
}
static void des3_encrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len, void *IV) {
DES_ede3_cbc_encrypt(in, out, len, cipher->key,
(void*)((uint8_t*)cipher->key + sizeof(DES_key_schedule)),
(void*)((uint8_t*)cipher->key + 2 * sizeof(DES_key_schedule)),
IV, 1);
}
static void des3_decrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len, void *IV) {
DES_ede3_cbc_encrypt(in, out, len, cipher->key,
(void*)((uint8_t*)cipher->key + sizeof(DES_key_schedule)),
(void*)((uint8_t*)cipher->key + 2 * sizeof(DES_key_schedule)),
IV, 0);
}
static void des3_1_encrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len, void *IV) {
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Encrypt IV before", IV, 24);
#endif
DES_ncbc_encrypt(in, out, len, cipher->key, IV, 1);
DES_ncbc_encrypt(out, in, len, (void*)((uint8_t*)cipher->key + sizeof(DES_key_schedule)),
(void*)((uint8_t*)IV + 8), 0);
DES_ncbc_encrypt(in, out, len, (void*)((uint8_t*)cipher->key + 2 * sizeof(DES_key_schedule)),
(void*)((uint8_t*)IV + 16), 1);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Encrypt IV after", IV, 24);
#endif
}
static void des3_1_decrypt(struct crypto_struct *cipher, void *in,
void *out, unsigned long len, void *IV) {
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Decrypt IV before", IV, 24);
#endif
DES_ncbc_encrypt(in, out, len, (void*)((uint8_t*)cipher->key + 2 * sizeof(DES_key_schedule)),
IV, 0);
DES_ncbc_encrypt(out, in, len, (void*)((uint8_t*)cipher->key + sizeof(DES_key_schedule)),
(void*)((uint8_t*)IV + 8), 1);
DES_ncbc_encrypt(in, out, len, cipher->key, (void*)((uint8_t*)IV + 16), 0);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("Decrypt IV after", IV, 24);
#endif
}
#endif /* HAS_DES */
/*
* The table of supported ciphers
*
* WARNING: If you modify crypto_struct, you must make sure the order is
* correct!
*/
static struct crypto_struct ssh_ciphertab[] = {
#ifdef HAS_BLOWFISH
{
"blowfish-cbc",
8,
sizeof (BF_KEY),
NULL,
128,
blowfish_set_key,
blowfish_set_key,
blowfish_encrypt,
blowfish_decrypt
},
#endif /* HAS_BLOWFISH */
#ifdef HAS_AES
#ifndef BROKEN_AES_CTR
{
"aes128-ctr",
16,
sizeof(AES_KEY),
NULL,
128,
aes_set_encrypt_key,
aes_set_encrypt_key,
aes_ctr128_encrypt,
aes_ctr128_encrypt
},
{
"aes192-ctr",
16,
sizeof(AES_KEY),
NULL,
192,
aes_set_encrypt_key,
aes_set_encrypt_key,
aes_ctr128_encrypt,
aes_ctr128_encrypt
},
{
"aes256-ctr",
16,
sizeof(AES_KEY),
NULL,
256,
aes_set_encrypt_key,
aes_set_encrypt_key,
aes_ctr128_encrypt,
aes_ctr128_encrypt
},
#endif /* BROKEN_AES_CTR */
{
"aes128-cbc",
16,
sizeof(AES_KEY),
NULL,
128,
aes_set_encrypt_key,
aes_set_decrypt_key,
aes_encrypt,
aes_decrypt
},
{
"aes192-cbc",
16,
sizeof(AES_KEY),
NULL,
192,
aes_set_encrypt_key,
aes_set_decrypt_key,
aes_encrypt,
aes_decrypt
},
{
"aes256-cbc",
16,
sizeof(AES_KEY),
NULL,
256,
aes_set_encrypt_key,
aes_set_decrypt_key,
aes_encrypt,
aes_decrypt
},
#endif /* HAS_AES */
#ifdef HAS_DES
{
"3des-cbc",
8,
sizeof(DES_key_schedule) * 3,
NULL,
192,
des3_set_key,
des3_set_key,
des3_encrypt,
des3_decrypt
},
{
"3des-cbc-ssh1",
8,
sizeof(DES_key_schedule) * 3,
NULL,
192,
des3_set_key,
des3_set_key,
des3_1_encrypt,
des3_1_decrypt
},
#endif /* HAS_DES */
{
NULL,
0,
0,
NULL,
0,
NULL,
NULL,
NULL,
NULL
}
};
#endif /* OPENSSL_CRYPTO */
/* it allocates a new cipher structure based on its offset into the global table */
static struct crypto_struct *cipher_new(int offset) {
struct crypto_struct *cipher = NULL;
cipher = malloc(sizeof(struct crypto_struct));
if (cipher == NULL) {
return NULL;
}
/* note the memcpy will copy the pointers : so, you shouldn't free them */
memcpy(cipher, &ssh_ciphertab[offset], sizeof(*cipher));
return cipher;
}
static void cipher_free(struct crypto_struct *cipher) {
#ifdef HAVE_LIBGCRYPT
unsigned int i;
#endif
if (cipher == NULL) {
return;
}
if(cipher->key) {
#ifdef HAVE_LIBGCRYPT
for (i = 0; i < (cipher->keylen / sizeof(gcry_cipher_hd_t)); i++) {
gcry_cipher_close(cipher->key[i]);
}
#elif defined HAVE_LIBCRYPTO
/* destroy the key */
memset(cipher->key, 0, cipher->keylen);
#endif
SAFE_FREE(cipher->key);
}
SAFE_FREE(cipher);
}
struct ssh_crypto_struct *crypto_new(void) {
struct ssh_crypto_struct *crypto;
crypto = malloc(sizeof(struct ssh_crypto_struct));
if (crypto == NULL) {
return NULL;
}
ZERO_STRUCTP(crypto);
return crypto;
}
void crypto_free(struct ssh_crypto_struct *crypto){
if (crypto == NULL) {
return;
}
SAFE_FREE(crypto->server_pubkey);
cipher_free(crypto->in_cipher);
cipher_free(crypto->out_cipher);
bignum_free(crypto->e);
bignum_free(crypto->f);
bignum_free(crypto->x);
bignum_free(crypto->y);
bignum_free(crypto->k);
/* lot of other things */
/* i'm lost in my own code. good work */
memset(crypto,0,sizeof(*crypto));
SAFE_FREE(crypto);
}
static int crypt_set_algorithms2(ssh_session session){
const char *wanted;
int i = 0;
/* we must scan the kex entries to find crypto algorithms and set their appropriate structure */
/* out */
wanted = session->client_kex.methods[SSH_CRYPT_C_S];
while (ssh_ciphertab[i].name && strcmp(wanted, ssh_ciphertab[i].name)) {
i++;
}
if (ssh_ciphertab[i].name == NULL) {
ssh_set_error(session, SSH_FATAL,
"Crypt_set_algorithms2: no crypto algorithm function found for %s",
wanted);
return SSH_ERROR;
}
ssh_log(session, SSH_LOG_PACKET, "Set output algorithm to %s", wanted);
session->next_crypto->out_cipher = cipher_new(i);
if (session->next_crypto->out_cipher == NULL) {
ssh_set_error(session, SSH_FATAL, "No space left");
return SSH_ERROR;
}
i = 0;
/* in */
wanted = session->client_kex.methods[SSH_CRYPT_S_C];
while (ssh_ciphertab[i].name && strcmp(wanted, ssh_ciphertab[i].name)) {
i++;
}
if (ssh_ciphertab[i].name == NULL) {
ssh_set_error(session, SSH_FATAL,
"Crypt_set_algorithms: no crypto algorithm function found for %s",
wanted);
return SSH_ERROR;
}
ssh_log(session, SSH_LOG_PACKET, "Set input algorithm to %s", wanted);
session->next_crypto->in_cipher = cipher_new(i);
if (session->next_crypto->in_cipher == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
return SSH_ERROR;
}
/* compression */
if (strstr(session->client_kex.methods[SSH_COMP_C_S], "zlib")) {
session->next_crypto->do_compress_out = 1;
}
if (strstr(session->client_kex.methods[SSH_COMP_S_C], "zlib")) {
session->next_crypto->do_compress_in = 1;
}
return SSH_OK;
}
static int crypt_set_algorithms1(ssh_session session) {
int i = 0;
/* right now, we force 3des-cbc to be taken */
while (ssh_ciphertab[i].name && strcmp(ssh_ciphertab[i].name,
"3des-cbc-ssh1")) {
i++;
}
if (ssh_ciphertab[i].name == NULL) {
ssh_set_error(session, SSH_FATAL, "cipher 3des-cbc-ssh1 not found!");
return -1;
}
session->next_crypto->out_cipher = cipher_new(i);
if (session->next_crypto->out_cipher == NULL) {
ssh_set_error(session, SSH_FATAL, "No space left");
return SSH_ERROR;
}
session->next_crypto->in_cipher = cipher_new(i);
if (session->next_crypto->in_cipher == NULL) {
ssh_set_error(session, SSH_FATAL, "No space left");
return SSH_ERROR;
}
return SSH_OK;
}
int crypt_set_algorithms(ssh_session session) {
return (session->version == 1) ? crypt_set_algorithms1(session) :
crypt_set_algorithms2(session);
}
// TODO Obviously too much cut and paste here
int crypt_set_algorithms_server(ssh_session session){
char *server = NULL;
char *client = NULL;
char *match = NULL;
int i = 0;
/* we must scan the kex entries to find crypto algorithms and set their appropriate structure */
enter_function();
/* out */
server = session->server_kex.methods[SSH_CRYPT_S_C];
client = session->client_kex.methods[SSH_CRYPT_S_C];
/* That's the client algorithms that are more important */
match = ssh_find_matching(server,client);
if(!match){
ssh_set_error(session,SSH_FATAL,"Crypt_set_algorithms_server : no matching algorithm function found for %s",server);
free(match);
leave_function();
return SSH_ERROR;
}
while(ssh_ciphertab[i].name && strcmp(match,ssh_ciphertab[i].name))
i++;
if(!ssh_ciphertab[i].name){
ssh_set_error(session,SSH_FATAL,"Crypt_set_algorithms_server : no crypto algorithm function found for %s",server);
free(match);
leave_function();
return SSH_ERROR;
}
ssh_log(session,SSH_LOG_PACKET,"Set output algorithm %s",match);
SAFE_FREE(match);
session->next_crypto->out_cipher = cipher_new(i);
if (session->next_crypto->out_cipher == NULL) {
ssh_set_error(session, SSH_FATAL, "No space left");
leave_function();
return SSH_ERROR;
}
i=0;
/* in */
client=session->client_kex.methods[SSH_CRYPT_C_S];
server=session->server_kex.methods[SSH_CRYPT_S_C];
match=ssh_find_matching(server,client);
if(!match){
ssh_set_error(session,SSH_FATAL,"Crypt_set_algorithms_server : no matching algorithm function found for %s",server);
free(match);
leave_function();
return SSH_ERROR;
}
while(ssh_ciphertab[i].name && strcmp(match,ssh_ciphertab[i].name))
i++;
if(!ssh_ciphertab[i].name){
ssh_set_error(session,SSH_FATAL,"Crypt_set_algorithms_server : no crypto algorithm function found for %s",server);
free(match);
leave_function();
return SSH_ERROR;
}
ssh_log(session,SSH_LOG_PACKET,"Set input algorithm %s",match);
SAFE_FREE(match);
session->next_crypto->in_cipher = cipher_new(i);
if (session->next_crypto->in_cipher == NULL) {
ssh_set_error(session, SSH_FATAL, "No space left");
leave_function();
return SSH_ERROR;
}
/* compression */
client=session->client_kex.methods[SSH_CRYPT_C_S];
server=session->server_kex.methods[SSH_CRYPT_C_S];
match=ssh_find_matching(server,client);
if(match && !strcmp(match,"zlib")){
ssh_log(session,SSH_LOG_PACKET,"enabling C->S compression");
session->next_crypto->do_compress_in=1;
}
SAFE_FREE(match);
client=session->client_kex.methods[SSH_CRYPT_S_C];
server=session->server_kex.methods[SSH_CRYPT_S_C];
match=ssh_find_matching(server,client);
if(match && !strcmp(match,"zlib")){
ssh_log(session,SSH_LOG_PACKET,"enabling S->C compression\n");
session->next_crypto->do_compress_out=1;
}
SAFE_FREE(match);
server=session->server_kex.methods[SSH_HOSTKEYS];
client=session->client_kex.methods[SSH_HOSTKEYS];
match=ssh_find_matching(server,client);
if(match && !strcmp(match,"ssh-dss"))
session->hostkeys=TYPE_DSS;
else if(match && !strcmp(match,"ssh-rsa"))
session->hostkeys=TYPE_RSA;
else {
ssh_set_error(session, SSH_FATAL, "Cannot know what %s is into %s",
match ? match : NULL, server);
SAFE_FREE(match);
leave_function();
return SSH_ERROR;
}
SAFE_FREE(match);
leave_function();
return SSH_OK;
}
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/wrapper.c
|
C
|
gpl3
| 28,917
|
/*
* auth1.c - authentication with SSH-1 protocol
*
* This file is part of the SSH Library
*
* Copyright (c) 2005-2008 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <string.h>
#include <stdlib.h>
#include "libssh/priv.h"
#include "libssh/ssh1.h"
#include "libssh/buffer.h"
#include "libssh/packet.h"
#include "libssh/session.h"
#include "libssh/string.h"
#ifdef WITH_SSH1
static int wait_auth1_status(ssh_session session) {
/* wait for a packet */
if (packet_read(session) != SSH_OK) {
return SSH_AUTH_ERROR;
}
if(packet_translate(session) != SSH_OK) {
return SSH_AUTH_ERROR;
}
switch(session->in_packet.type) {
case SSH_SMSG_SUCCESS:
return SSH_AUTH_SUCCESS;
case SSH_SMSG_FAILURE:
return SSH_AUTH_DENIED;
}
ssh_set_error(session, SSH_FATAL, "Was waiting for a SUCCESS or "
"FAILURE, got %d", session->in_packet.type);
return SSH_AUTH_ERROR;
}
static int send_username(ssh_session session, const char *username) {
ssh_string user = NULL;
/* returns SSH_AUTH_SUCCESS or SSH_AUTH_DENIED */
if(session->auth_service_asked) {
return session->auth_service_asked;
}
if (!username) {
if(!(username = session->username)) {
if (ssh_options_set(session, SSH_OPTIONS_USER, NULL) < 0) {
return session->auth_service_asked = SSH_AUTH_ERROR;
} else {
username = session->username;
}
}
}
user = string_from_char(username);
if (user == NULL) {
return SSH_AUTH_ERROR;
}
if (buffer_add_u8(session->out_buffer, SSH_CMSG_USER) < 0) {
string_free(user);
return SSH_AUTH_ERROR;
}
if (buffer_add_ssh_string(session->out_buffer, user) < 0) {
string_free(user);
return SSH_AUTH_ERROR;
}
string_free(user);
if (packet_send(session) != SSH_OK) {
return SSH_AUTH_ERROR;
}
session->auth_service_asked = wait_auth1_status(session);
return session->auth_service_asked;
}
/* use the "none" authentication question */
int ssh_userauth1_none(ssh_session session, const char *username){
return send_username(session, username);
}
/*
int ssh_userauth_offer_pubkey(ssh_session session, char *username,int type, ssh_string publickey){
ssh_string user;
ssh_string service;
ssh_string method;
ssh_string algo;
int err=SSH_AUTH_ERROR;
if(!username)
if(!(username=session->options->username)){
if(options_default_username(session->options))
return SSH_AUTH_ERROR;
else
username=session->options->username;
}
if(ask_userauth(session))
return SSH_AUTH_ERROR;
user=string_from_char(username);
service=string_from_char("ssh-connection");
method=string_from_char("publickey");
algo=string_from_char(ssh_type_to_char(type));
packet_clear_out(session);
buffer_add_u8(session->out_buffer,SSH2_MSG_USERAUTH_REQUEST);
buffer_add_ssh_string(session->out_buffer,user);
buffer_add_ssh_string(session->out_buffer,service);
buffer_add_ssh_string(session->out_buffer,method);
buffer_add_u8(session->out_buffer,0);
buffer_add_ssh_string(session->out_buffer,algo);
buffer_add_ssh_string(session->out_buffer,publickey);
packet_send(session);
err=wait_auth_status(session,0);
free(user);
free(method);
free(service);
free(algo);
return err;
}
*/
/** \internal
* \todo implement ssh1 public key
*/
int ssh_userauth1_offer_pubkey(ssh_session session, const char *username,
int type, ssh_string pubkey) {
(void) session;
(void) username;
(void) type;
(void) pubkey;
return SSH_AUTH_DENIED;
}
/*
int ssh_userauth_pubkey(ssh_session session, char *username, ssh_string publickey, ssh_private_key privatekey){
ssh_string user;
ssh_string service;
ssh_string method;
ssh_string algo;
ssh_string sign;
int err=SSH_AUTH_ERROR;
if(!username)
if(!(username=session->options->username)){
if(options_default_username(session->options))
return err;
else
username=session->options->username;
}
if(ask_userauth(session))
return err;
user=string_from_char(username);
service=string_from_char("ssh-connection");
method=string_from_char("publickey");
algo=string_from_char(ssh_type_to_char(privatekey->type));
*/ /* we said previously the public key was accepted */
/* packet_clear_out(session);
buffer_add_u8(session->out_buffer,SSH2_MSG_USERAUTH_REQUEST);
buffer_add_ssh_string(session->out_buffer,user);
buffer_add_ssh_string(session->out_buffer,service);
buffer_add_ssh_string(session->out_buffer,method);
buffer_add_u8(session->out_buffer,1);
buffer_add_ssh_string(session->out_buffer,algo);
buffer_add_ssh_string(session->out_buffer,publickey);
sign=ssh_do_sign(session,session->out_buffer,privatekey);
if(sign){
buffer_add_ssh_string(session->out_buffer,sign);
free(sign);
packet_send(session);
err=wait_auth_status(session,0);
}
free(user);
free(service);
free(method);
free(algo);
return err;
}
*/
int ssh_userauth1_password(ssh_session session, const char *username,
const char *password) {
ssh_string pwd = NULL;
int rc;
rc = send_username(session, username);
if (rc != SSH_AUTH_DENIED) {
return rc;
}
/* we trick a bit here. A known flaw in SSH1 protocol is that it's
* easy to guess password sizes.
* not that sure ...
*/
/* XXX fix me here ! */
/* cisco IOS doesn't like when a password is followed by zeroes and random pad. */
if(1 || strlen(password) >= 128) {
/* not risky to disclose the size of such a big password .. */
pwd = string_from_char(password);
if (pwd == NULL) {
return SSH_AUTH_ERROR;
}
} else {
/* fill the password string from random things. the strcpy
* ensure there is at least a nul byte after the password.
* most implementation won't see the garbage at end.
* why garbage ? because nul bytes will be compressed by
* gzip and disclose password len.
*/
pwd = string_new(128);
if (pwd == NULL) {
return SSH_AUTH_ERROR;
}
ssh_get_random( pwd->string, 128, 0);
strcpy((char *) pwd->string, password);
}
if (buffer_add_u8(session->out_buffer, SSH_CMSG_AUTH_PASSWORD) < 0) {
string_burn(pwd);
string_free(pwd);
return SSH_AUTH_ERROR;
}
if (buffer_add_ssh_string(session->out_buffer, pwd) < 0) {
string_burn(pwd);
string_free(pwd);
return SSH_AUTH_ERROR;
}
string_burn(pwd);
string_free(pwd);
if (packet_send(session) != SSH_OK) {
return SSH_AUTH_ERROR;
}
return wait_auth1_status(session);
}
#endif /* WITH_SSH1 */
/* vim: set ts=2 sw=2 et cindent: */
|
zzlydm-fbbs
|
libssh/auth1.c
|
C
|
gpl3
| 7,569
|
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -pedantic -Werror")
add_definitions(-D_XOPEN_SOURCE=500 -D_BSD_SOURCE)
add_library(fbbspg SHARED pg.c)
target_link_libraries(fbbspg pq)
install(TARGETS fbbspg LIBRARY DESTINATION so)
|
zzlydm-fbbs
|
pg/CMakeLists.txt
|
CMake
|
gpl3
| 229
|
#include <endian.h>
#ifndef be64toh
# if __BYTE_ORDER == __LITTLE_ENDIAN
# include <byteswap.h>
# define be64toh(x) bswap_64(x)
# else
# define be64toh(x) (x)
# endif
#endif
#include <arpa/inet.h>
#include <stdint.h>
#include <stdlib.h>
#include "fbbs/dbi.h"
#include "fbbs/util.h"
/** Postgresql epoch (Jan 1, 2000) in unix time. */
#define POSTGRES_EPOCH_TIME INT64_C(946684800)
/**
* Default postgresql installation used to use double to represent timestamp.
* It was changed to 64-bit integer since 8.4 (Jul 2009).
*/
#define HAVE_INT64_TIMESTAMP
fb_time_t ts_to_time(timestamp ts)
{
return ts / INT64_C(1000000) + POSTGRES_EPOCH_TIME;
}
timestamp time_to_ts(fb_time_t t)
{
return (t - POSTGRES_EPOCH_TIME) * INT64_C(1000000);
}
db_conn_t *db_connect(const char *host, const char *port,
const char *db, const char *user, const char *pwd)
{
return PQsetdbLogin(host, port, NULL, NULL, db, user, pwd);
}
void db_finish(db_conn_t *conn)
{
PQfinish(conn);
}
db_conn_status_t db_status(db_conn_t *conn)
{
return PQstatus(conn);
}
const char *db_errmsg(db_conn_t *conn)
{
return PQerrorMessage(conn);
}
db_res_t *db_exec_params(db_conn_t *conn, const char *cmd, int count,
db_param_t *params, bool binary)
{
if (count > 0) {
const char *values[count];
int lengths[count];
int formats[count];
for (int i = 0; i < count; ++i) {
values[i] = params[i].value;
lengths[i] = params[i].length;
formats[i] = params[i].format;
}
return PQexecParams(conn, cmd, count, NULL, values, lengths,
formats, binary);
} else {
return PQexecParams(conn, cmd, 0, NULL, NULL, NULL, NULL, binary);
}
}
db_exec_status_t db_res_status(const db_res_t *res)
{
return PQresultStatus(res);
}
const char *db_res_error(const db_res_t *res)
{
return PQresultErrorMessage(res);
}
void db_clear(db_res_t *res)
{
PQclear(res);
}
int db_num_rows(const db_res_t *res)
{
return PQntuples(res);
}
int db_num_fields(const db_res_t *res)
{
return PQnfields(res);
}
bool _is_binary_field(const db_res_t *res, int col)
{
return PQfformat(res, col);
}
bool db_get_is_null(const db_res_t *res, int row, int col)
{
return PQgetisnull(res, row, col);
}
const char *db_get_value(const db_res_t *res, int row, int col)
{
return PQgetvalue(res, row, col);
}
int16_t db_get_smallint(const db_res_t *res, int row, int col)
{
const char *r = PQgetvalue(res, row, col);
if (_is_binary_field(res, col)) {
return (int16_t)ntohs(*((uint16_t *)r));
} else {
return (int16_t)strtol(r, NULL, 10);
}
}
int32_t db_get_integer(const db_res_t *res, int row, int col)
{
const char *r = PQgetvalue(res, row, col);
if (_is_binary_field(res, col)) {
return (int32_t)ntohl(*((uint32_t *)r));
} else {
return (int32_t)strtol(r, NULL, 10);
}
}
int64_t db_get_bigint(const db_res_t *res, int row, int col)
{
const char *r = PQgetvalue(res, row, col);
if (_is_binary_field(res, col)) {
return (int64_t)be64toh(*((uint64_t *)r));
} else {
return (int64_t)strtoll(r, NULL, 10);
}
}
bool db_get_bool(const db_res_t *res, int row, int col)
{
const char *r = PQgetvalue(res, row, col);
if (_is_binary_field(res, col)) {
return *r;
} else {
switch (*r) {
case 'T':
case 't':
case 'Y':
case 'y':
case '1':
return true;
default:
return false;
}
}
}
fb_time_t db_get_time(const db_res_t *res, int row, int col)
{
const char *r = PQgetvalue(res, row, col);
if (_is_binary_field(res, col)) {
#ifdef HAVE_INT64_TIMESTAMP
timestamp ts = (int64_t)be64toh(*(uint64_t *)r);
#else
uint64_t t = be64toh(*(uint64_t *)r);
timestamp ts = *(double *)&t * 1000000;
#endif
return ts_to_time(ts);
}
return 0;
}
|
zzlydm-fbbs
|
pg/pg.c
|
C
|
gpl3
| 3,671
|
BEGIN;
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT,
passwd TEXT,
nick TEXT,
email TEXT,
flag BIGINT,
perm INTEGER,
logins INTEGER DEFAULT 0,
posts INTEGER DEFAULT 0,
stay INTEGER DEFAULT 0,
medals INTEGER DEFAULT 0,
money INTEGER DEFAULT 0,
birth TIMESTAMPTZ,
gender CHAR,
creation TIMESTAMPTZ,
lastlogin TIMESTAMPTZ,
lastlogout TIMESTAMPTZ,
lasthost TEXT
);
CREATE UNIQUE INDEX user_name_idx ON users (lower(name));
CREATE TABLE sectors (
id SERIAL PRIMARY KEY,
name TEXT
);
CREATE TABLE boards (
id SERIAL PRIMARY KEY,
name TEXT,
description TEXT,
category TEXT,
sector SMALLINT,
parent INTEGER,
flag INTEGER
);
CREATE TABLE managers (
user_id INTEGER,
board_id INTEGER,
appointed TIMESTAMPTZ
);
CREATE TABLE club_users (
user_id INTEGER,
board_id INTEGER,
granter INTEGER,
added TIMESTAMPTZ,
comments TEXT
);
CREATE TABLE posts (
id BIGSERIAL PRIMARY KEY,
reid BIGINT,
gid BIGINT,
board_id INTEGER,
user_id INTEGER,
user_name TEXT, -- for compatability
title TEXT,
flag INTEGER, --?
time TIMESTAMPTZ,
t2 TIMESTAMPTZ,
itype SMALLINT
);
COMMIT;
|
zzlydm-fbbs
|
pg/schema.sql
|
PLpgSQL
|
gpl3
| 1,109
|
#!/usr/bin/perl -w
use strict;
use DBI;
use Encode;
use Getopt::Long;
use POSIX;
$| = 1;
my ($host, $port, $db, $user, $dir);
GetOptions(
"h|host=s" => \$host,
"p|port:s" => \$port,
"d|database=s" => \$db,
"u|user=s" => \$user,
"b|basedir:s" => \$dir,
);
$port = 5432 if (not $port);
$dir = '/home/bbs' if (not $dir);
die "Usage: $0 -h host [-p port] -d database -u user -b [base dir]\n" if (not $host or not $db or not $user);
my $dbconf = {
'host' => $host,
'db' => $db,
'user' => $user
};
my $dsn = "DBI:Pg:database=$db;host=$host;port=$port";
my $dbh;
$dbh = DBI->connect($dsn, $user, $user, { RaiseError => 1, AutoCommit => 0 }) or die $dbh->errstr;
my (%users, %boards, @posts);
my $pcount = 0;
my $array = &read_users;
&insert_users($array);
$array = &read_boards;
&insert_boards($array);
&insert_managers($array);
&insert_club_users($array);
&insert_posts;
$dbh->disconnect;
sub read_users
{
# 0 uid 1 userlevel 2 numlogins 3 numposts 4 stay
# 5 nummedals 6 money 7 bet 8 flags 9 passwd
# 10 nummails 11 gender 12 byear 13 bmonth 14 bday
# 15 signature 16 userdefine 17 prefs 18 noteline 19 firstlogin
# 20 lastlogin 21 lastlogout 22 dateforbet 23 notedate 24 userid
# 25 lasthost 26 username 27 email 28 reserved
my ($buf, %hash);
open my $fh, '<', "$dir/.PASSWDS" or die "can't open .PASSWDS\n";
while (1) {
last if (read($fh, $buf, 256) != 256);
my @t = unpack "IiIiIi3sA14IcC3iI2iq5Z16Z40Z40Z40a8", $buf;
if ($t[24] and not exists $hash{$t[24]}) {
$hash{$t[24]} = \@t;
}
}
close $fh;
my @temp = values %hash;
@temp = sort { $a->[19] <=> $b->[19] } @temp;
my $i = 1;
$users{$_->[24]} = $i++ foreach (@temp);
return \@temp;
}
sub insert_users
{
my $arr = shift;
my $query = $dbh->prepare("INSERT INTO users (name, passwd, nick, email, flag, perm, logins, posts, stay, medals, money, birth, gender, creation, lastlogin, lastlogout, lasthost) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") or die $dbh->errstr;
print "inserting users...";
my $i = 0;
foreach (@$arr) {
print "$i..." if (++$i % 500 == 0);
my $nick = &convert($_->[26]);
my $email = &check_email($_->[27]);
my $lasthost = &convert($_->[25]);
my $birth = &check_birth($_->[12], $_->[13], $_->[14]);
$query->execute($_->[24], $_->[9], $nick, $email, $_->[16], $_->[1], $_->[2], $_->[3], $_->[4], $_->[5], $_->[6], $birth, chr($_->[11]), &mytime($_->[19]), &mytime($_->[20]), &mytime($_->[21]), $lasthost) or die $dbh->errstr;
}
$dbh->commit;
print "finished\n";
}
sub read_boards
{
#0 filename 1 nowid 2 group 3 owner 4 bm 5 flag
#6 sector 7 category 8 nonsense 9 title
#10 level 11 accessed
my ($buf, %hash, @temp);
my $i = 0;
my $id = 1;
open my $fh, '<', "$dir/.BOARDS" or die "can't open .BOARDS\n";
while (1) {
last if (read($fh, $buf, 256) != 256);
my @t = unpack "Z72IiZ20Z56ia2a4a5Z69Ia12", $buf;
++$i;
if ($t[0]) {
$hash{$i} = $id;
$boards{$t[0]} = $id;
++$id;
push @temp, \@t;
}
}
$_->[2] = $_->[2] ? $hash{$_->[2]} : undef foreach (@temp);
return \@temp;
}
sub insert_boards
{
my $arr = shift;
print "inserting boards...";
my $query = $dbh->prepare("INSERT INTO boards (name, description, category, sector, parent, flag) VALUES (?, ?, ?, ?, ?, ?)") or die $dbh->errstr;
foreach (@$arr) {
$query->execute(&convert($_->[0]), &convert($_->[9]), &convert($_->[7]), ord(substr($_->[6], 0, 1)), $_->[2], $_->[5]) or die $dbh->errstr;
}
$dbh->commit;
print "finished\n";
}
sub insert_managers
{
my $arr = shift;
print "inserting managers...";
my $query = $dbh->prepare("INSERT INTO managers (user_id, board_id) VALUES (?, ?)") or die $dbh->errstr;
foreach my $brd (@$arr) {
my @bm = split / /, $brd->[4];
foreach my $bm (@bm) {
if (exists $users{$bm}) {
$query->execute($users{$bm}, $boards{$brd->[0]}) or die $dbh->errstr;
}
}
}
$dbh->commit;
print "finished\n";
}
sub insert_club_users
{
my $arr = shift;
print "converting club users...";
my $query = $dbh->prepare("INSERT INTO club_users (user_id, board_id, granter, added, comments) VALUES (?, ?, ?, ?, ?)") or die $dbh->errstr;
foreach my $brd (@$arr) {
next if (not $brd->[5] & 0x40); # club flag
my $fh;
open $fh, '<', "$dir/boards/" . $brd->[0] . '/club_users' and do {
while (<$fh>) {
if (/^(\w+) +(\S*) +(\d{4}.\d\d\.\d\d) (\w+) *$/) {
$query->execute($users{$1}, $boards{$brd->[0]}, $users{$4}, $3 . ' 0:0:0 +8:00', &convert($2)) if (exists $users{$1});
}
}
close $fh;
}
}
$dbh->commit;
print "finished\n";
}
sub read_index
{
my @indices = qw/.DIR .TRASH .JUNK .NOTICE .DIGEST/;
my ($board, $index) = @_;
my $file = $indices[$index];
my $bid = $boards{$board};
my ($fh, $buf);
open $fh, '<', "$dir/boards/$board/$file" and do {
while (1) {
last if (read($fh, $buf, 256) != 256);
my @t = unpack "Z72I2Z80Z67Z13i4", $buf;
my $date;
if ($t[0] =~ /^.\.(\d+)\./) {
$date = $1;
$t[0] = $board . '/' . $t[0];
push @t, $date, $bid, $index;
push @posts, \@t;
}
print "$pcount..." if (++$pcount % 100000 == 0);
}
close $fh;
}
}
sub insert_posts
{
my $query = $dbh->prepare("INSERT INTO posts (reid, gid, board_id, user_id, user_name, title, flag, time, t2, itype) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") or die $dbh->errstr;
print "reading indices...";
foreach my $board (keys %boards) {
foreach my $idx (0..4) {
&read_index($board, $idx);
}
}
print "finished ($pcount posts)\n";
# 0 filename 1 id 2 gid 3 owner 4 title
# 5 eraser 6 level 7 accessed 8 reid 9 timedeleted
# 10 (date) 11 (board_id) 12 (type)
print "sorting...";
@posts = sort { $a->[10] <=> $b->[10] } @posts;
print "finished\n";
print "inserting posts...";
my $id = 0;
my %hash;
my $dest = '/home/fbbs/posts/';
foreach (@posts) {
$hash{$_->[11] . '_' . $_->[1]} = ++$id;
mkdir $dest . int($id / 10000) if ($id % 10000 == 1);
my $fh;
open $fh, '<', $dir . '/boards/' . $_->[0] and do {
my $wh;
if (open $wh, '>', $dest . int($id / 10000) . "/$id") {
my $str;
{
local $/ = undef;
$str = <$fh>;
}
close $fh;
print $wh &convert($str);
close $wh;
} else {
close $fh;
}
};
$query->execute($hash{$_->[11] . '_' . $_->[8]}, $hash{$_->[11] . '_' . $_->[2]}, $_->[11], $users{$_->[3]}, &convert($_->[3]), &convert($_->[4]), $_->[7], &mytime($_->[10]), $_->[9] ? &mytime($_->[9]) : undef, $_->[12]) or die $dbh->errstr;
if ($id % 1000 == 0) {
$dbh->commit;
print "$id..." ;
}
}
print "finished\n";
}
sub convert
{
my $s = shift;
encode('utf8', decode('gbk', $s));
}
sub check_email
{
my $s = shift;
return $s if ($s =~ /^(?:[.\-\w]+)@(?:[.\-\w]+)$/);
return undef;
}
sub check_birth
{
my ($y, $m, $d) = @_;
my $t = mktime(0, 0, 0, $d, $m - 1, $y);
return undef if (not $t);
mytime($t);
}
sub mytime
{
my $t = shift;
my @t = localtime($t);
my $s = sprintf "%d-%d-%d %d:%d:%d +8:00", $t[5] + 1900, $t[4] + 1, $t[3], $t[2], $t[1], $t[0];
}
|
zzlydm-fbbs
|
pg/convert.pl
|
Perl
|
gpl3
| 6,982
|
#! /bin/sh
echo "========================="
echo "clear web process ..."
echo "========================="
for pid in `ps -A | grep apache2 | awk '{ print $1 }'`
do
kill -9 $pid
echo "kill apache2 (pid:$pid)"
done
for pid in `ps -A | grep bbslogin | awk '{ print $1 }'`
do
kill -9 $pid
echo "kill bbslogin (pid:$pid)"
done
echo "========================="
echo "clear bbsd process ..."
echo "========================="
for pid in `ps -A | grep bbsd | awk '{ print $1 }'`
do
kill -9 $pid
echo "kill bbsd (pid:$pid)"
done
echo "========================="
echo "clear chatd process ..."
echo "========================="
for pid in `ps -A | grep chatd | awk '{ print $1 }'`
do
kill -9 $pid
echo "kill chatd (pid:$pid)"
done
echo "========================="
echo "clear bbsnet process ..."
echo "========================="
for pid in `ps -A | grep bbsnet | awk ' { print $1 }'`
do
kill -9 $pid
echo "kill bbsnet (pid:$pid)"
done
echo "========================="
echo "clear miscd process ..."
echo "========================="
/home/bbs/bin/miscd flushed
rm /home/bbs/.PASSWDS.bak
cp /home/bbs/.PASSWDS /home/bbs/.PASSWDS.bak
for pid in `ps -A | grep miscd | awk '{ print $1 }'`
do
kill -9 $pid
# echo "kill bbsd (pid:$pid)"
done
echo "============================"
echo "remove bbs share memory ..."
echo "============================"
for shm_id in `ipcs -m| grep bbs | awk '{ print $2 }'`
do
ipcrm -m $shm_id
done
/home/bbs/bin/miscd daemon
/home/bbs/bin/bbsd 12345
/home/bbs/bin/chatd
|
zzlydm-fbbs
|
restart.sh
|
Shell
|
gpl3
| 1,544
|
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -pedantic -Werror")
add_definitions(-D_XOPEN_SOURCE=500)
link_directories(../lib)
add_executable(bbsd bbsd.c sysconf.c termio.c screen.c main.c stuff.c more.c)
target_link_libraries(bbsd crypt dl fbbs)
install(TARGETS bbsd RUNTIME DESTINATION bin)
|
zzlydm-fbbs
|
src/CMakeLists.txt
|
CMake
|
gpl3
| 297
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "fbbs/sysconf.h"
#include "fbbs/string.h"
#include "fbbs/file.h"
enum {
SC_BUFSIZE = 20480,
SC_KEYSIZE = 256,
SC_CMDSIZE = 256,
LINE_BUFSIZE = 256,
};
struct sysheader {
char *buf;
int menu, key, len;
};
sysconf_t sys_conf = { NULL, NULL, NULL, 0, 0, 0 };
/**
* Concatenates string to the sysconf buffer.
* @param str The string.
* @param conf The sysconf data structure.
*/
static char *sysconf_addstr(const char *str, sysconf_t *conf)
{
char *buf = conf->buf + conf->len;
conf->len += strlcpy(buf, str, SC_BUFSIZE - conf->len) + 1;
if (conf->len > SC_BUFSIZE)
conf->len = SC_BUFSIZE;
return buf;
}
/**
* Search sysconf for 'key'.
* @param key The key.
* @return The correspoding string if found, NULL otherwise.
*/
const char *sysconf_str(const char *key)
{
int n;
for (n = 0; n < sys_conf.keys; n++)
if (strcmp(key, sys_conf.var[n].key) == 0)
return (sys_conf.var[n].str);
return NULL;
}
/**
* Searches sysconf for key.
* @param key The key.
* @param conf The sysconf data structure.
* @return The corresponding value if found. Otherwise, key is converted to
* integer and returned.
*/
int sysconf_eval(const char *key, sysconf_t *conf)
{
int n;
for (n = 0; n < conf->keys; n++)
if (strcmp(key, conf->var[n].key) == 0)
return (conf->var[n].val);
return (strtol(key, NULL, 0));
}
/**
* Add 'str' 'key' to sysconf.
* @param key The key.
* @param str The string.
* @param val The value.
* @param conf The sysconf data structure.
*/
static void sysconf_addkey(const char *key, char *str, int val, sysconf_t *conf)
{
if (conf->keys < SC_KEYSIZE) {
if (str == NULL)
str = conf->buf;
else
str = sysconf_addstr(str, conf);
conf->var[conf->keys].key = sysconf_addstr(key, conf);
conf->var[conf->keys].str = str;
conf->var[conf->keys].val = val;
conf->keys++;
}
}
/**
* Read file and add menu items. Each line stands for an item.
* Format: cmd line col level name desc.
* Line started with '#' are comments.
* Commands start with '\@' are ordinary cmds.
* Commands start with '!' represent a link to another cmd group.
* Otherwise, 'cmd's are properties of the cmd group.
* 'line', 'col' specifies the location to display the item.
* Users above 'level' can see the item.
* The first letter of 'name' is the shortcut to the menu item.
* 'desc' is the description of item shown on screen.
* @param fp The file.
* @param key The key.
* @param conf The sysconf data structure.
*/
static void sysconf_addmenu(FILE *fp, const char *key, sysconf_t *conf)
{
menuitem_t *pm;
char buf[LINE_BUFSIZE];
char *cmd, *arg[5], *ptr;
int n;
sysconf_addkey(key, "menu", conf->items, conf);
while (fgets(buf, sizeof(buf), fp) != NULL && buf[0] != '%') {
cmd = strtok(buf, " \t\n");
if (cmd == NULL || *cmd == '#')
continue;
arg[0] = arg[1] = arg[2] = arg[3] = arg[4] = "";
n = 0;
for (n = 0; n < 5; n++) {
if ((ptr = strtok(NULL, ",\n")) == NULL)
break;
while (*ptr == ' ' || *ptr == '\t')
ptr++;
if (*ptr == '"') {
arg[n] = ++ptr;
while (*ptr != '"' && *ptr != '\0')
ptr++;
*ptr = '\0';
} else {
arg[n] = ptr;
while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
ptr++;
*ptr = '\0';
}
}
pm = conf->item + (conf->items++);
pm->line = sysconf_eval(arg[0], conf);
pm->col = sysconf_eval(arg[1], conf);
if (*cmd == '@') {
pm->level = sysconf_eval(arg[2], conf);
pm->name = sysconf_addstr(arg[3], conf);
pm->desc = sysconf_addstr(arg[4], conf);
pm->func = sysconf_addstr(cmd + 1, conf);
pm->arg = pm->name;
} else if (*cmd == '!') {
pm->level = sysconf_eval(arg[2], conf);
pm->name = sysconf_addstr(arg[3], conf);
pm->desc = sysconf_addstr(arg[4], conf);
pm->func = sysconf_addstr("domenu", conf);
pm->arg = sysconf_addstr(cmd + 1, conf);
} else {
pm->level = -2;
pm->name = sysconf_addstr(cmd, conf);
pm->desc = sysconf_addstr(arg[2], conf);
pm->func = conf->buf;
pm->arg = conf->buf;
}
}
pm = conf->item + (conf->items++);
pm->name = pm->desc = pm->arg = conf->buf;
pm->func = conf->buf;
pm->level = -1;
}
static void encodestr(char *str)
{
register char ch, *buf;
int n;
buf = str;
while ((ch = *str++) != '\0') {
if (*str == ch && str[1] == ch && str[2] == ch) {
n = 4;
str += 3;
while (*str == ch && n < 100) {
str++;
n++;
}
*buf++ = '\01';
*buf++ = ch;
*buf++ = n;
} else
*buf++ = ch;
}
*buf = '\0';
}
/**
* Read file and add menu blocks (background).
* @param fp The file.
* @param key The key.
* @param conf The sysconf data structure.
*/
static void sysconf_addblock(FILE *fp, const char *key, sysconf_t *conf)
{
char buf[LINE_BUFSIZE];
if (conf->keys < SC_KEYSIZE) {
conf->var[conf->keys].key = sysconf_addstr(key, conf);
conf->var[conf->keys].str = conf->buf + conf->len;
conf->var[conf->keys].val = -1;
conf->keys++;
while (fgets(buf, sizeof(buf), fp) != NULL && buf[0] != '%') {
encodestr(buf);
conf->len += strlcpy(conf->buf + conf->len, buf,
SC_BUFSIZE - conf->len);
}
conf->len++;
} else {
while (fgets(buf, sizeof(buf), fp) != NULL && buf[0] != '%') {
}
}
}
/**
* Parse sysconfig file 'fname'.
* '\#include' has the same effect of that in C file.
* Lines starting with '\%' splits the file into groups.
* '\%menu' indicates a group of menu items, otherwise menu background.
*/
static void sysconf_parse(const char *fname, sysconf_t *conf)
{
char buf[LINE_BUFSIZE], tmp[LINE_BUFSIZE], *ptr, *key, *str;
int val;
FILE *fp = fopen(fname, "r");
if (fp == NULL)
return;
sysconf_addstr("(null ptr)", conf);
while (fgets(buf, sizeof(buf), fp) != NULL) {
ptr = buf;
while (*ptr == ' ' || *ptr == '\t')
ptr++;
if (*ptr == '%') {
strtok(ptr, " \t\n");
if (strcmp(ptr, "%menu") == 0) {
str = strtok(NULL, " \t\n");
if (str != NULL)
sysconf_addmenu(fp, str, conf);
} else {
sysconf_addblock(fp, ptr + 1, conf);
}
} else if (*ptr == '#') {
key = strtok(ptr, " \t\"\n");
str = strtok(NULL, " \t\"\n");
if (key != NULL && str != NULL &&
strcmp(key, "#include") == 0) {
sysconf_parse(str, conf);
}
} else if (*ptr != '\n') {
key = strtok(ptr, "=#\n");
str = strtok(NULL, "#\n");
if (key != NULL && str != NULL) {
strtok(key, " \t");
while (*str == ' ' || *str == '\t')
str++;
if (*str == '"') {
str++;
strtok(str, "\"");
val = atoi(str);
sysconf_addkey(key, str, val, conf);
} else {
val = 0;
strlcpy(tmp, str, sizeof(tmp));
ptr = strtok(tmp, ", \t");
while (ptr != NULL) {
val |= sysconf_eval(ptr, conf);
ptr = strtok(NULL, ", \t");
}
sysconf_addkey(key, NULL, val, conf);
}
}
}
}
fclose(fp);
}
/**
* Parse sysconfig file.
* @param configfile The configuration file.
* @param imgfile The file to hold the result.
*/
static int sysconf_build(const char *configfile, const char *imgfile)
{
int ret = -1;
sysconf_t conf;
conf.item = malloc(SC_CMDSIZE * sizeof(*conf.item));
conf.var = malloc(SC_KEYSIZE * sizeof(*conf.var));
conf.buf = malloc(SC_BUFSIZE);
if (!conf.buf || !conf.var || !conf.item) {
if (conf.item)
free(conf.item);
if (conf.var)
free(conf.var);
if (conf.buf)
free(conf.buf);
}
conf.len = conf.items = conf.keys = 0;
sysconf_parse(configfile, &conf);
struct sysheader shead;
FILE *fp = fopen(imgfile, "w");
if (fp) {
shead.buf = conf.buf;
shead.menu = conf.items;
shead.key = conf.keys;
shead.len = conf.len;
fwrite(&shead, sizeof(shead), 1, fp);
fwrite(conf.item, sizeof(*conf.item), conf.items, fp);
fwrite(conf.var, sizeof(*conf.var), conf.keys, fp);
fwrite(conf.buf, conf.len, 1, fp);
fclose(fp);
ret = 0;
}
free(conf.item);
free(conf.var);
free(conf.buf);
return ret;
}
static int sysconf_load_image(const char *imgfile)
{
struct sysheader shead;
struct stat st;
char *ptr;
int fd, n, diff;
if ((fd = open(imgfile, O_RDONLY)) > 0) {
fstat(fd, &st);
ptr = malloc(st.st_size);
if (ptr == NULL) {
close(fd);
return -1;
}
read(fd, &shead, sizeof(shead));
read(fd, ptr, st.st_size);
close(fd);
sys_conf.item = (void *) ptr;
ptr += shead.menu * sizeof(menuitem_t);
sys_conf.var = (void *) ptr;
ptr += shead.key * sizeof(struct sdefine);
sys_conf.buf = (void *) ptr;
ptr += shead.len;
sys_conf.items = shead.menu;
sys_conf.keys = shead.key;
sys_conf.len = shead.len;
diff = sys_conf.buf - shead.buf;
for (n = 0; n < sys_conf.items; n++) {
sys_conf.item[n].name += diff;
sys_conf.item[n].desc += diff;
sys_conf.item[n].arg += diff;
sys_conf.item[n].func += diff;
}
for (n = 0; n < sys_conf.keys; n++) {
sys_conf.var[n].key += diff;
sys_conf.var[n].str += diff;
}
}
return 0;
}
/**
* Load menu config.
* @param rebuild Whether reload config and overwrite the image file.
* @return 0 on success, -1 on error.
*/
int sysconf_load(bool rebuild)
{
if (rebuild && sys_conf.item)
free(sys_conf.item);
if (rebuild || !dashf("sysconf.img")) {
if (sysconf_build("etc/sysconf.ini", "sysconf.img") != 0)
return -1;
}
return sysconf_load_image("sysconf.img");
}
|
zzlydm-fbbs
|
src/sysconf.c
|
C
|
gpl3
| 9,344
|
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <poll.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "fbbs/bbs.h"
#include "fbbs/util.h"
#include "fbbs/site.h"
extern void start_client(void);
/**
* Wait for an child to terminate.
* @param notused Not used.
*/
static void reap_child(int notused)
{
int state, pid;
while ((pid = waitpid(-1, &state, WNOHANG | WUNTRACED)) > 0)
;
}
/**
* Exit.
* @param notused Not used.
*/
static void close_daemon(int notused)
{
exit(0);
}
/**
*
*/
static int bind_port(const char *port, struct pollfd *fds, int nfds)
{
struct addrinfo *ai;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
hints.ai_socktype = SOCK_STREAM;
int e = getaddrinfo(NULL, port, &hints, &ai);
if (e)
return -1;
int n = 0;
for (struct addrinfo *aip = ai; n < nfds && aip; aip = aip->ai_next) {
int fd = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
if (fd < 0) {
freeaddrinfo(ai);
return n;
}
int on = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (aip->ai_family == AF_INET6)
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
if (bind(fd, aip->ai_addr, aip->ai_addrlen) != 0
|| listen(fd, SOMAXCONN) != 0) {
close(fd);
}
fds[n].fd = fd;
fds[n].events = POLLIN;
++n;
}
freeaddrinfo(ai);
return n;
}
static int accept_connection(int fd, int nfds)
{
struct sockaddr_storage sock;
socklen_t socklen = sizeof(sock);
int conn = accept(fd, (struct sockaddr *)&sock, &socklen);
if (conn < 0)
return -1;
int pid = fork();
if (pid < 0)
return -1;
if (pid == 0) {
while (--nfds >= 0)
close(nfds);
dup2(conn, STDIN_FILENO);
close(conn);
dup2(STDIN_FILENO, STDOUT_FILENO);
char host[IP_LEN];
getnameinfo((struct sockaddr *)&sock, socklen, host, sizeof(host),
NULL, 0, NI_NUMERICHOST);
start_client();
exit(0);
} else {
close(conn);
}
return 0;
}
int main(int argc, char **argv)
{
if (argc <= 1) {
printf("Usage: %s [port]\n", argv[0]);
return EXIT_FAILURE;
}
start_daemon();
fb_signal(SIGCHLD, reap_child);
fb_signal(SIGTERM, close_daemon);
struct pollfd fds[2];
int nfds = bind_port(argv[1], fds, sizeof(fds) / sizeof(fds[0]));
if (nfds == 0) {
return EXIT_FAILURE;
}
// Give up root privileges.
setgid((gid_t)BBSGID);
setuid((uid_t)BBSUID);
chdir(BBSHOME);
umask(S_IWGRP | S_IWOTH);
while (1) {
int n = poll(fds, nfds, -1);
if (n > 0) {
for (int i = 0; i < nfds; ++i) {
if (fds[i].revents & POLLIN) {
accept_connection(fds[i].fd, nfds);
}
}
}
}
return EXIT_SUCCESS;
}
|
zzlydm-fbbs
|
src/bbsd.c
|
C
|
gpl3
| 2,765
|
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <wchar.h>
#include <stdarg.h>
#include "fbbs/string.h"
#include "fbbs/screen.h"
/**
* String of commands to clear the entire screen and position the cursor at the
* upper left corner.
*/
#define TERM_CMD_CL "\033[H\033[J"
/**
* String of commands to clear from the cursor to the end of the current line.
*/
#define TERM_CMD_CE "\033[K"
/**
* String of commands to scroll the screen one line down, assuming it is output
* with the cursor at the beginning of the top line.
*/
#define TERM_CMD_SR "\033M"
/** String of commands to enter standout mode. */
#define TERM_CMD_SO "\033[7m"
/** String of commands to leave standout mode. */
#define TERM_CMD_SE "\033[m"
/** Send a terminal command. */
#define term_cmd(cmd) telnet_write(s->tc, (const uchar_t *)cmd, sizeof(cmd) - 1)
/** The standard screen. */
static screen_t stdscr;
/**
* Initialize a screen.
* @param scr The screen to be initialized.
* @param tc Related telnet connection.
* @param lines Lines of the screen.
* @param cols Columns of the screen.
*/
static void _screen_init(screen_t *scr, telconn_t *tc, int lines, int cols)
{
scr->scr_lns = lines;
scr->scr_cols = cols;
scr->cur_ln = scr->cur_col = scr->roll = scr->scroll_cnt = 0;
scr->size = lines;
scr->show_ansi = true;
scr->clear = true;
scr->tc = tc;
scr->lines = fb_malloc(sizeof(*scr->lines) * lines);
screen_line_t *slp = scr->lines;
for (int i = 0; i < lines; ++i) {
slp->oldlen = slp->len = 0;
slp->modified = false;
++slp;
}
}
/**
* Initialize the standard screen.
* @param tc Related telnet connection.
* @param lines Lines of the screen.
* @param cols Columns of the screen.
*/
void screen_init(telconn_t *tc, int lines, int cols)
{
_screen_init(&stdscr, tc, lines, cols);
}
/**
* Move to given position.
* @param s The screen.
* @param line The line to move to.
* @param col The column to move to.
*/
static void _move(screen_t *s, int line, int col)
{
s->cur_ln = line;
s->cur_col = col;
}
/**
* Move to given position in the standard screen.
* @param line The line to move to.
* @param col The column to move to.
*/
void move(int line, int col)
{
_move(&stdscr, line, col);
}
/**
* Clear a screen.
* @param s The screen.
*/
static void _clear(screen_t *s)
{
s->roll = 0;
s->clear = true;
screen_line_t *slp = s->lines;
for (int i = 0; i < s->scr_lns; ++i) {
slp->modified = false;
slp->len = 0;
slp->oldlen = 0;
++slp;
}
_move(s, 0, 0);
}
/**
* Clear the standard screen.
*/
void clear(void)
{
_clear(&stdscr);
}
/**
* Clear from current column to the end of line.
* @param s The screen.
*/
static void _clrtoeol(screen_t *s)
{
screen_line_t *slp = s->lines + (s->cur_ln + s->roll) % s->scr_lns;
if (s->cur_col > slp->len)
memset(slp->data + slp->len, ' ', s->cur_col - slp->len + 1);
slp->len = s->cur_col;
}
/**
* Clear from current column to the end of line.
*/
void clrtoeol(void)
{
_clrtoeol(&stdscr);
}
/**
* Clear from current line (included) to the bottom of the screen.
* @param s The screen.
*/
static void _clrtobot(screen_t *s)
{
screen_line_t *slp;
for (int i = s->cur_ln; i < s->scr_lns; ++i) {
slp = s->lines + (s->cur_ln + s->roll) % s->scr_lns;
slp->modified = true;
slp->len = 0;
}
}
/**
* Clear from current line (included) to the bottom of the standard screen.
*/
void clrtobot(void)
{
_clrtobot(&stdscr);
}
/**
* Scroll one line down.
* @param s The screen.
*/
static void _scroll(screen_t *s)
{
s->scroll_cnt++;
s->roll++;
if (s->roll >= s->scr_lns)
s->roll -= s->scr_lns;
_move(s, s->scr_lns - 1, 0);
_clrtoeol(s);
}
/**
* Scroll one line down.
*/
void scroll(void)
{
_scroll(&stdscr);
}
static inline bool isprint2(int c)
{
return ((c & 0x80) || isprint(c));
}
static void _outs(screen_t *s, const uchar_t *str, int len)
{
bool newline = true;
screen_line_t *slp = s->lines + (s->cur_ln + s->roll) % s->scr_lns;
int col = s->cur_col, c;
if (len == 0)
len = strlen((const char *)str);
while (len-- > 0) {
if (newline) {
slp->modified = true;
if (col > slp->len) {
memset(slp->data + slp->len, ' ', col - slp->len);
slp->len = col;
}
newline = false;
}
c = *str++;
if (!isprint2(c)) {
if (c == '\n' || c == '\r') {
slp->data[col] = ' ';
slp->len = col;
s->cur_col = 0;
if (s->cur_ln < s->scr_lns)
++s->cur_ln;
newline = true;
slp = s->lines + (s->cur_ln + s->roll) % s->scr_lns;
col = s->cur_col;
continue;
} else {
if (c != KEY_ESC || !s->show_ansi)
c = '*';
}
}
slp->data[col++] = c;
if (col >= sizeof(slp->data)) {
col = sizeof(slp->data) - 1;
}
}
if (col > slp->len)
slp->len = col;
s->cur_col = col;
}
void outc(int c)
{
uchar_t ch = c;
_outs(&stdscr, &ch, 1);
}
void outs(const char *str)
{
_outs(&stdscr, (const uchar_t *)str, 0);
}
static inline void ochar(screen_t *s, int c)
{
telnet_putc(s->tc, c);
}
/**
* Move to a new position in terminal.
* @param s The screen.
* @param line The new line.
* @param col The new column.
*/
static void term_move(screen_t *s, int line, int col)
{
if (col == 0 && line == s->tc_ln + 1) { // newline
ochar(s, '\n');
if (s->tc_ln != 0)
ochar(s, '\r');
} else if (col == 0 && line == s->tc_ln) { // return
if (s->tc_col != 0)
ochar(s, '\r');
} else if (col == s->tc_col - 1 && line == s->tc_ln) { // backspace
ochar(s, KEY_CTRL_H);
} else if (col != s->tc_col || line != s->tc_ln) { // arbitrary move
char buf[16];
snprintf(buf, sizeof(buf), "\033[%d;%dH", line + 1, col + 1);
for (char *p = buf; *p != '\0'; p++)
ochar(s, *p);
}
s->tc_ln = line;
s->tc_col = col;
}
/**
* Redraw the screen.
* @param s The screen.
*/
static void _redoscr(screen_t *s)
{
term_cmd(TERM_CMD_CL);
s->tc_col = s->tc_ln = 0;
struct screen_line_t *slp;
for (int i = 0; i < s->scr_lns; i++) {
slp = s->lines + (i + s->roll) % s->scr_lns;
if (slp->len == 0)
continue;
term_move(s, i, 0);
telnet_write(s->tc, slp->data, slp->len);
s->tc_col += slp->len;
slp->modified = false;
slp->oldlen = slp->len;
}
term_move(s, s->cur_ln, s->cur_col);
s->scroll_cnt = 0;
s->clear = false;
telnet_flush(s->tc);
}
/**
* Redraw the standard screen.
*/
void redoscr(void)
{
_redoscr(&stdscr);
}
/**
* Flush all modifications of a screen to terminal.
* @param s The screen.
*/
static void _refresh(screen_t *s)
{
if (!buffer_empty(s->tc))
return;
if (s->clear || s->scroll_cnt >= s->scr_lns - 3) {
_redoscr(s);
return;
}
if (s->scroll_cnt > 0) {
term_move(s, s->tc->lines - 1, 0);
while (s->scroll_cnt-- > 0) {
ochar(s, '\n');
}
}
screen_line_t *slp;
for (int i = 0; i < s->scr_lns; ++i) {
slp = s->lines + (i + s->roll) % s->scr_lns;
if (slp->modified) {
slp->modified = false;
term_move(s, i, 0);
telnet_write(s->tc, slp->data, slp->len);
if (slp->len != 0)
term_cmd(TERM_CMD_CE);
s->tc_col = slp->len + 1;
}
slp->oldlen = slp->len;
}
term_move(s, s->cur_ln, s->cur_col);
telnet_flush(s->tc);
}
/**
* Flush all modifications of the standard screen to terminal.
*/
void refresh(void)
{
_refresh(&stdscr);
}
/**
* Get the width of the standard screen.
* @return The width of the standard screen.
*/
int get_screen_width(void)
{
return stdscr.scr_cols;
}
/**
* Get the height of the standard screen.
* @return The height of the standard screen.
*/
int get_screen_height(void)
{
return stdscr.scr_lns;
}
/**
* Print width-limited string.
* @param str The string.
* @param max Maxmimum string width (if max > 0).
* @param min Minimum string width (if min < 0). If the string has fewer
* columns, it is padded with spaces.
* @param left_align Alignment when padding.
*/
static void outns(const char *str, int max, int min, bool left_align)
{
int ret, w;
size_t width = 0;
wchar_t wc;
mbstate_t state;
memset(&state, 0, sizeof(state));
const char *s = str;
while (*s != '\0') {
ret = mbrtowc(&wc, s, MB_CUR_MAX, &state);
if (ret >= (size_t)-2) {
break;
} else {
w = wcwidth(wc);
if (w == -1)
w = 0;
width += w;
if (max > 0 && width > max)
break;
s += ret;
}
}
if (max > 0) {
_outs(&stdscr, (const uchar_t *)str, s - str);
} else if (min > 0) {
if (!left_align) {
for (int i = 0; i < min - width; ++i)
outc(' ');
}
_outs(&stdscr, (const uchar_t *)str, s - str);
if (left_align) {
for (int i = 0; i < min - width; ++i)
outc(' ');
}
}
}
static void outns2(const char *str, int val, int sgn, int sgn2)
{
if (val) {
if (!sgn2) {
outns(str, val, 0, sgn < 0);
} else {
outns(str, 0, val, sgn < 0);
}
} else {
_outs(&stdscr, (const uchar_t *)str, 0);
}
}
/**
* Format and print string to the standard screen.
* Only 3 format specifiers (s, d, c) are supported.
* Only one of maximum or minimum filed width can be specified.
* @param fmt The format string.
*/
void prints(const char *fmt, ...)
{
const char *bp;
int i;
char tmp[16];
va_list ap;
va_start(ap, fmt);
while (*fmt != '\0') {
if (*fmt == '%') {
int sgn = 1;
int sgn2 = 1;
int val = 0;
fmt++;
switch (*fmt) {
case '-':
while (*fmt == '-') {
sgn = -sgn;
fmt++;
}
break;
case '.':
sgn2 = 0;
fmt++;
break;
}
while (isdigit(*fmt)) {
val *= 10;
val += *fmt - '0';
fmt++;
}
switch (*fmt) {
case 's':
bp = va_arg(ap, const char *);
if (bp == NULL)
continue;
outns2(bp, val, sgn, sgn2);
break;
case 'd':
i = va_arg(ap, int);
snprintf(tmp, sizeof(tmp), "%d", i);
outns2(tmp, val, sgn, sgn2);
break;
case 'c':
i = va_arg(ap, int);
outc(i);
break;
case '\0':
va_end(ap);
return;
default:
outc(*fmt);
break;
}
fmt++;
continue;
}
outc(*fmt);
fmt++;
}
va_end(ap);
return;
}
int getch(void)
{
return term_getch(stdscr.tc);
}
/**
* Delete a UTF-8 character.
* @param backspace If true, delete backward, otherwise forward.
* @return Bytes deleted.
*/
int delch(bool backspace)
{
screen_t *s = &stdscr;
screen_line_t *slp = s->lines + (s->cur_ln + s->roll) % s->scr_lns;
uchar_t *begin = slp->data, *end = slp->data + slp->len;
uchar_t *ptr = slp->data + s->cur_col;
if (backspace) {
while (--ptr >= begin) {
if ((*ptr & 0x80) == 0 || (*ptr & 0xC0) == 0xC0)
break;
}
end = slp->data + s->cur_col;
if (ptr >= begin) {
slp->modified = true;
int width = mbwidth((const char *)ptr);
memmove(ptr, end, slp->len - s->cur_col);
slp->len -= end - ptr;
s->cur_col -= width;
if (s->cur_col < 0)
s->cur_col = 0;
return end - ptr;
}
} else {
while (++ptr < end) {
if ((*ptr & 0x80) == 0 || (*ptr & 0xC0) == 0xC0)
break;
}
begin = slp->data + s->cur_col;
if (ptr < end) {
slp->modified = true;
memmove(begin, ptr, end - ptr);
slp->len -= ptr - begin;
return ptr - begin;
}
}
return 0;
}
/**
* Get user input string.
* @param line Line to show prompt.
* @param prompt The prompt message.
* @param buf The buffer. If not empty, its content is shown.
* @param len Length of buffer.
* @param mask Whether to asterisk the echo.
* @return The user input in bytes.
*/
int getdata(int line, const char *prompt, char *buf, int len, bool mask)
{
move(line, 0);
clrtoeol();
if (prompt)
outs(prompt);
int clen = 0;
if (buf[0] != '\0') {
outs(buf);
clen = strlen(buf);
}
refresh();
int ch;
while (1) {
ch = getch();
if (ch == '\n')
break;
switch (ch) {
case KEY_BACKSPACE:
case KEY_CTRL_H:
if (clen == 0)
continue;
clen -= delch(true);
break;
case KEY_DEL:
if (clen == 0)
continue;
clen -= delch(false);
break;
case KEY_LEFT: // TODO: ...
break;
case KEY_RIGHT:
break;
case KEY_HOME:
case KEY_CTRL_A:
break;
case KEY_END:
case KEY_CTRL_E:
break;
default:
if (!isprint2(ch) || clen >= len - 1)
continue;
buf[clen++] = ch;
if (mask)
outc('*');
else
outc(ch);
break;
}
refresh();
}
buf[clen] = '\0';
return clen;
}
|
zzlydm-fbbs
|
src/screen.c
|
C
|
gpl3
| 12,208
|
#ifndef FB_MORE_H
#define FB_MORE_H
#include <stdbool.h>
extern int ansimore(const char *file, bool presskey, int line, int lines, bool expand);
extern void show_help(const char *file);
#endif // FB_MORE_H
|
zzlydm-fbbs
|
include/fbbs/more.h
|
C
|
gpl3
| 209
|
#ifndef FB_BBS_H
#define FB_BBS_H
#include "fbbs/site.h"
#define USER_FILE BBSHOME"/db/users"
#define BOARD_FILE BBSHOME"/db/boards"
enum {
IP_LEN = 40,
PATHLEN = 128,
};
#endif // FB_BBS_H
|
zzlydm-fbbs
|
include/fbbs/bbs.h
|
C
|
gpl3
| 197
|
#ifndef FB_POST_H
#define FB_POST_H
#include "fbbs/util.h"
enum {
FILE_MARKED = 0x8,
FILE_DIGEST = 0x10,
FILE_NOREPLY = 0x40,
FILE_WATER = 0x80,
};
typedef struct post_t {
seq_t id;
seq_t reid;
seq_t gid;
seq_t owner;
seq_t eraser;
uint_t prop;
uint_t size;
varchar_t title;
fb_time_t date;
fb_time_t deldate;
} post_t;
#endif // FB_POST_H
|
zzlydm-fbbs
|
include/fbbs/post.h
|
C
|
gpl3
| 358
|
#ifndef FB_SOCKET_H
#define FB_SOCKET_H
#define BBSD_SOCKET_BASE BBSHOME"/tmp/bbsd-socket"
extern int unix_dgram_connect(const char *basename, const char *server);
extern int unix_dgram_bind(const char *name, int qlen);
#endif // FB_SOCKET_H
|
zzlydm-fbbs
|
include/fbbs/socket.h
|
C
|
gpl3
| 245
|
#ifndef FB_WEB_H
#define FB_WEB_H
#include "fbbs/cfg.h"
#include "fbbs/dbi.h"
#include "fbbs/pool.h"
#include <fcgi_stdio.h>
#define CHARSET "utf-8"
enum {
MAX_PARAMETERS = 32,
MAX_CONTENT_LENGTH = 1 * 1024 * 1024,
};
enum {
PARSE_NOSIG = 0x1,
PARSE_NOQUOTEIMG = 0x2,
};
typedef struct pair_t {
char *key;
char *val;
} pair_t;
typedef struct http_req_t {
pool_t *p;
char *from;
pair_t params[MAX_PARAMETERS];
int count;
} http_req_t;
typedef struct web_ctx_t {
config_t *c;
db_conn_t *d;
pool_t *p;
http_req_t *r;
} web_ctx_t;
extern http_req_t *get_request(pool_t *p);
extern const char *get_param(http_req_t *r, const char *name);
extern int parse_post_data(http_req_t *r);
extern void html_header(void);
extern void xml_header(const char *xslfile);
extern void print_session(void);
extern void xml_print(const char *s);
extern int xml_print_post(const char *file, int option);
#endif // FB_WEB_H
|
zzlydm-fbbs
|
include/fbbs/web.h
|
C
|
gpl3
| 925
|
#ifndef FB_STRING_H
#define FB_STRING_H
#include <stdlib.h>
#define streq(a, b) (!strcmp(a, b))
extern char *trim(char *str);
extern size_t strlcpy(char *dst, const char *src, size_t siz);
extern size_t mbwidth(const char *s);
#endif // FB_STRING_H
|
zzlydm-fbbs
|
include/fbbs/string.h
|
C
|
gpl3
| 257
|
#ifndef FB_USER_H
#define FB_USER_H
#include "fbbs/util.h"
enum {
EXT_ID_LEN = 16,
NICK_LEN = 40,
NAME_LEN = 32,
EMAIL_LEN = 40,
PASS_LEN = 14,
};
typedef struct user_t {
seq_t uid;
seq_t eid;
uint_t perm;
uint_t logins;
uint_t posts;
uint_t stay;
uint_t medals;
int money;
char gender;
uchar_t birthyear;
uchar_t birthmonth;
uchar_t birthday;
int utmpkey;
int prefs;
fb_time_t reg;
fb_time_t login;
fb_time_t logout;
char passwd[PASS_LEN];
char name[EXT_ID_LEN];
char nick[NICK_LEN];
char real[NAME_LEN];
} user_t;
#endif // FB_USER_H
|
zzlydm-fbbs
|
include/fbbs/user.h
|
C
|
gpl3
| 571
|
#ifndef FB_MMAP_H
#define FB_MMAP_H
#include <stddef.h>
/** Memory mapped file information. */
typedef struct {
int fd; ///< file descriptor.
int oflag; ///< open flags.
int lock; ///< lock status.
int prot; ///< memory protection of the mapping.
int mflag; ///< MAP_SHARED or MAP_PRIVATE.
void *ptr; ///< starting address of the mapping.
size_t msize; ///< mmaped size.
size_t size; ///< real file size.
} mmap_t;
int mmap_open(const char *file, mmap_t *m);
int mmap_close(mmap_t *m);
int mmap_lock(mmap_t *m, int lock);
#endif // FB_MMAP_H
|
zzlydm-fbbs
|
include/fbbs/mmap.h
|
C
|
gpl3
| 578
|
#ifndef FB_PASS_H
#define FB_PASS_H
#include <stdbool.h>
enum {
/** Maximum length for a password. (DES: 8 chars, MD5: also 8.) */
MAX_PASSWORD_LENGTH = 24,
};
extern const char *generate_passwd(const char *pw);
extern bool check_passwd(const char *pw_crypted, const char *pw_try);
#endif // FB_PASS_H
|
zzlydm-fbbs
|
include/fbbs/pass.h
|
C
|
gpl3
| 308
|
#ifndef FB_TERMIO_H
#define FB_TERMIO_H
#include <stdlib.h>
#include <stdbool.h>
#include "fbbs/util.h"
enum {
IOBUF_SIZE = 4096,
};
enum {
KEY_TAB = 9,
KEY_ESC = 27,
KEY_UP = 0x0101,
KEY_DOWN = 0x0102,
KEY_RIGHT = 0x0103,
KEY_LEFT = 0x0104,
KEY_HOME = 0x0201,
KEY_INS = 0x0202,
KEY_DEL = 0x0203,
KEY_BACKSPACE = 0x7f,
KEY_END = 0x0204,
KEY_PGUP = 0x0205,
KEY_PGDN = 0x0206,
KEY_CTRL_A = 1, KEY_CTRL_B, KEY_CTRL_C, KEY_CTRL_D, KEY_CTRL_E,
KEY_CTRL_F, KEY_CTRL_G, KEY_CTRL_H, KEY_CTRL_I, KEY_CTRL_J, KEY_CTRL_L,
KEY_CTRL_M, KEY_CTRL_N, KEY_CTRL_O, KEY_CTRL_P, KEY_CTRL_Q, KEY_CTRL_R,
KEY_CTRL_S, KEY_CTRL_T, KEY_CTRL_U, KEY_CTRL_V, KEY_CTRL_W, KEY_CTRL_X,
KEY_CTRL_Y, KEY_CTRL_Z,
};
typedef struct iobuf_t {
size_t cur;
size_t size;
uchar_t buf[IOBUF_SIZE];
} iobuf_t;
typedef struct telconn_t {
int fd;
bool cr;
int lines;
int cols;
iobuf_t inbuf;
iobuf_t outbuf;
} telconn_t;
extern void telnet_init(telconn_t *tc, int fd);
extern void telnet_opt(telconn_t *tc);
extern int telnet_flush(telconn_t *tc);
extern void telnet_write(telconn_t *tc, const uchar_t *str, int size);
extern int telnet_putc(telconn_t *tc, int c);
extern bool buffer_empty(telconn_t *tc);
extern int term_getch(telconn_t *tc);
#endif // FB_TERMIO_H
|
zzlydm-fbbs
|
include/fbbs/termio.h
|
C
|
gpl3
| 1,258
|
#ifndef FB_TIME_H
#define FB_TIME_H
#include <time.h>
enum {
DATE_ZH = 0, ///< "2001年02月03日04:05:06 星期六"
DATE_EN = 1, ///< "02/03/01 04:05:06"
DATE_SHORT = 2, ///< "02.03 04:05"
DATE_ENWEEK = 4, ///< "02/03/01 04:05:06 Sat"
DATE_XML = 8, ///< "2001-02-03T04:05:06"
DATE_RSS = 16, ///< "Sat,03 Feb 2001 04:05:06 +0800"
};
extern const char *date2str(time_t time, int mode);
#endif // FB_TIME_H
|
zzlydm-fbbs
|
include/fbbs/time.h
|
C
|
gpl3
| 435
|
#ifndef FB_ERROR_H
#define FB_ERROR_H
enum {
FB_SUCCESS = 0,
FB_FAILURE = -1,
FB_FATAL = -2,
};
enum {
FB_EINVAL,
};
#endif // FB_ERROR_H
|
zzlydm-fbbs
|
include/fbbs/error.h
|
C
|
gpl3
| 145
|
#ifndef FB_HASH_H
#define FB_HASH_H
/**
* @file hash.h
* @brief Hash Tables
*/
enum {
HASH_DEFAULT_MAX = 15, ///< default hash max.
/** indicates a string key when passing as key length. */
HASH_KEY_STRING = -1,
};
/**
* Hash function prototype.
* @param key The key.
* @param klen The length of the key. ::HASH_KEY_STRING indicates that the key
* is a string and then the actual length is returned via the pointer.
* */
typedef unsigned int (*hash_func_t)(const char *key, unsigned int *klen);
/** Hash entry struct. */
typedef struct hash_entry_t
{
struct hash_entry_t *next; ///< pointer to next entry.
const char *key; ///< key.
unsigned int klen; ///< key length.
unsigned int hash; ///< hash code.
const void *val; ///< value.
} hash_entry_t;
/** Hash table struct. */
typedef struct hash_t
{
unsigned int count; ///< number of entries in the table.
unsigned int max; ///< maximum slot number, must be 2^n - 1.
hash_entry_t **array; ///< array for hash entries.
hash_entry_t *free; ///< list of recycled entries.
hash_func_t func; ///< hash function.
} hash_t;
/** Hash table iterator type. */
typedef struct hash_iter_t
{
const hash_t *ht; ///< The hash table.
hash_entry_t *entry; ///< Current entry.
hash_entry_t *next; ///< Next entry.
unsigned int index; ///< Current ndex in ht->array.
} hash_iter_t;
unsigned int hash_func_default(const char *key, unsigned int *klen);
int hash_create(hash_t *ht, unsigned int max, hash_func_t func);
int hash_set(hash_t *ht, const void *key, unsigned int klen, const void *val);
void *hash_get(hash_t *ht, const void *key, unsigned int klen);
void hash_destroy(hash_t *ht);
hash_iter_t *hash_next(hash_iter_t *iter);
hash_iter_t *hash_begin(const hash_t *ht);
#endif // FB_HASH_H
|
zzlydm-fbbs
|
include/fbbs/hash.h
|
C
|
gpl3
| 1,835
|
#ifndef FB_SITE_H
#define FB_SITE_H
#define TESTING
#define DES
#define BBSHOME "/home/bbs"
enum {
BBSUID = 9999,
BBSGID = 9999,
};
#ifdef TESTING
enum {
MAX_USERS = 25000,
USER_HASH_SLOTS = 65535,
MAX_BOARDS = 1000,
MAX_ACTIVE = 1000,
};
#endif
#endif // FB_SITE_H
|
zzlydm-fbbs
|
include/fbbs/site.h
|
C
|
gpl3
| 279
|
#ifndef FB_STUFF_H
#define FB_STUFF_H
extern void presskeyfor(const char *msg, int line);
extern void pressanykey(void);
#endif // FB_STUFF_H
|
zzlydm-fbbs
|
include/fbbs/stuff.h
|
C
|
gpl3
| 144
|
#ifndef FB_CFG_H
#define FB_CFG_H
#define DEFAULT_CFG_FILE "/etc/fbbs/fbbs.conf"
typedef struct config_t {
int pairs;
int cur;
int *keys;
int *vals;
char *buf;
} config_t;
extern int config_init(config_t *cfg);
extern void config_destroy(config_t *cfg);
extern int config_load(config_t *cfg, const char *file);
extern const char *config_get(const config_t *cfg, const char *key);
#endif // FB_CFG_H
|
zzlydm-fbbs
|
include/fbbs/cfg.h
|
C
|
gpl3
| 408
|
#ifndef FB_BOARD_H
#define FB_BOARD_H
#include "fbbs/util.h"
typedef struct board_t {
seq_t bid;
seq_t parent;
seq_t current;
uint_t flag;
uint_t perm;
char name[18];
char title[62];
} board_t;
typedef struct bm_t {
seq_t bid;
seq_t uid;
fb_time_t date;
} bm_t;
#endif // FB_BOARD_H
|
zzlydm-fbbs
|
include/fbbs/board.h
|
C
|
gpl3
| 297
|
#ifndef FB_SCREEN_H
#define FB_SCREEN_H
#include "fbbs/util.h"
#include "fbbs/termio.h"
enum {
SCREENLINE_BUFSIZE = 512,
};
typedef struct screen_line_t {
int oldlen; // Length after last flush.
int len; // Length in the buffer.
bool modified; // Modified or not.
uchar_t data[SCREENLINE_BUFSIZE]; // The buffer.
} screen_line_t;
typedef struct screen_t {
int scr_lns; // Lines of the screen.
int scr_cols; // Columns of the screen.
int cur_ln; // Current line.
int cur_col; // Current column.
int tc_ln; // Terminal's current line.
int tc_col; // Terminal's current column.
int roll; // Offset of first line in the array.
int scroll_cnt; // Count of scrolled lines since last update.
bool show_ansi; // Print ansi control codes verbatim.
bool clear; // Clear whole screen.
int size; // Size of screen lines array.
screen_line_t *lines; // Screen lines.
telconn_t *tc; // Associated telnet connection.
} screen_t;
extern void screen_init(telconn_t *tc, int lines, int cols);
extern void move(int line, int col);
extern void clear(void);
extern void clrtoeol(void);
extern void clrtobot(void);
extern void scroll(void);
extern void outc(int c);
extern void outs(const char *str);
extern void redoscr(void);
extern void refresh(void);
extern int get_screen_width(void);
extern int get_screen_height(void);
extern void prints(const char *fmt, ...);
extern int getch(void);
extern int getdata(int line, const char *prompt, char *buf, int len, bool mask);
#endif // FB_SCREEN_H
|
zzlydm-fbbs
|
include/fbbs/screen.h
|
C
|
gpl3
| 1,717
|
#ifndef FB_UTIL_H
#define FB_UTIL_H
#include <stdint.h>
#include <stddef.h>
#include <inttypes.h>
#define elems(x) (sizeof(x) / sizeof(x[0]))
typedef int64_t fb_time_t;
#define PRIdFBT PRId64
typedef uint64_t ulong_t;
typedef uint32_t uint_t;
typedef uint16_t ushort_t;
typedef uint8_t uchar_t;
typedef uint32_t seq_t;
typedef uint32_t varchar_t;
typedef void (*sighandler_t)(int);
extern void start_daemon(void);
extern sighandler_t fb_signal(int signum, sighandler_t handler);
extern void *fb_malloc(size_t size);
#endif // FB_UTIL_H
|
zzlydm-fbbs
|
include/fbbs/util.h
|
C
|
gpl3
| 547
|
#include <libintl.h>
#define _(str) ((const char *)gettext(str))
|
zzlydm-fbbs
|
include/fbbs/i18n.h
|
C
|
gpl3
| 66
|
#ifndef FB_SYSCONF_H
#define FB_SYSCONF_H
#include <stdbool.h>
typedef struct {
int line; ///< Line.
int col; ///< Column.
int level; ///< Level.
const char *name; ///< English name.
const char *desc; ///< Description shown on screen.
const char *arg; ///< Arguments passed to function.
const char *func; ///< Function string.
} menuitem_t;
struct sdefine {
char *key, *str;
int val;
};
typedef struct {
char *buf; ///< The buffer.
menuitem_t *item; ///< Array of menu items.
struct sdefine *var; ///<
int len; ///< Length of used buffer.
int items; ///< Count of menu items.
int keys; ///<
} sysconf_t;
extern sysconf_t sys_conf;
extern const char *sysconf_str(const char *key);
extern int sysconf_eval(const char *key, sysconf_t *conf);
extern int sysconf_load(bool rebuild);
#endif // FB_SYSCONF_H
|
zzlydm-fbbs
|
include/fbbs/sysconf.h
|
C
|
gpl3
| 923
|
#ifndef FB_POOL_H
#define FB_POOL_H
#include "fbbs/util.h"
enum {
DEFAULT_POOL_SIZE = 16 * 1024,
};
typedef struct pool_large_t {
void *ptr;
struct pool_large_t *next;
} pool_large_t;
typedef struct pool_block_t {
uchar_t *last;
uchar_t *end;
struct pool_block_t *next;
} pool_block_t;
typedef struct pool_t {
struct pool_block_t *head;
pool_large_t *large;
} pool_t;
extern pool_t *pool_create(size_t size);
extern void pool_clear(pool_t *p);
extern void pool_destroy(pool_t *p);
extern void *pool_alloc(pool_t *p, size_t size);
#endif // FB_POOL_H
|
zzlydm-fbbs
|
include/fbbs/pool.h
|
C
|
gpl3
| 565
|
#ifndef FB_DBI_H
#define FB_DBI_H
#include <stdbool.h>
#include <stdint.h>
#include <libpq-fe.h>
#include "fbbs/util.h"
#define PARAM_TEXT(x) { .value = x, .length = 0, .format = 0 }
#define PARAM_CHAR(x) { .value = &x, .length = 1, .format = 1 }
#define PARAM_SMALLINT(x) { .value = &x, .length = 2, .format = 1 }
#define PARAM_INT(x) { .value = &x, .length = 4, .format = 1 }
#define PARAM_BIGINT(x) { .value = &x, .length = 8, .format = 1 }
typedef PGconn db_conn_t;
typedef PGresult db_res_t;
typedef int64_t timestamp;
typedef enum db_conn_status_t {
DB_CONNECTION_OK = CONNECTION_OK,
} db_conn_status_t;
typedef enum db_exec_status_t {
DBRES_COMMAND_OK = PGRES_COMMAND_OK,
DBRES_TUPLES_OK = PGRES_TUPLES_OK,
} db_exec_status_t;
typedef struct db_param_t {
const char *value;
int length;
int format;
} db_param_t;
extern timestamp time_to_ts(fb_time_t t);
extern db_conn_t *db_connect(const char *host, const char *port,
const char *db, const char *user, const char *pwd);
extern void db_finish(db_conn_t *conn);
extern db_conn_status_t db_status(db_conn_t *conn);
extern const char *db_errmsg(db_conn_t *conn);
extern db_res_t *db_exec_params(db_conn_t *conn, const char *cmd, int count,
db_param_t *params, bool binary);
extern db_exec_status_t db_res_status(const db_res_t *res);
extern const char *db_res_error(const db_res_t *res);
extern void db_clear(db_res_t *res);
extern int db_num_rows(const db_res_t *res);
extern int db_num_fields(const db_res_t *res);
extern bool db_get_is_null(const db_res_t *res, int row, int col);
extern const char *db_get_value(const db_res_t *res, int row, int col);
extern int16_t db_get_smallint(const db_res_t *res, int row, int col);
extern int32_t db_get_integer(const db_res_t *res, int row, int col);
extern int64_t db_get_bigint(const db_res_t *res, int row, int col);
extern bool db_get_bool(const db_res_t *res, int row, int col);
extern fb_time_t db_get_time(const db_res_t *res, int row, int col);
#endif // FB_DBI_H
|
zzlydm-fbbs
|
include/fbbs/dbi.h
|
C
|
gpl3
| 2,011
|
#ifndef FB_CACHE_H
#define FB_CACHE_H
#include "fbbs/bbs.h"
#include "fbbs/hash.h"
#include "fbbs/mmap.h"
#include "fbbs/pass.h"
#include "fbbs/user.h"
#define CACHE_SERVER BBSHOME"/tmp/cache-server"
#define CACHE_CLIENT BBSHOME"/tmp/cache-client"
enum {
PASSWORD_QUERY = 0,
};
typedef struct ucache_t {
user_t *begin;
user_t *end;
mmap_t m;
hash_t name_hash;
hash_t uid_hash;
} ucache_t;
typedef struct password_query_t {
int type;
char username[EXT_ID_LEN];
char passwd[MAX_PASSWORD_LENGTH];
} password_query_t;
typedef struct password_result_t {
int type;
char match;
} password_result_t;
#endif // FB_CACHE_H
|
zzlydm-fbbs
|
include/fbbs/cache.h
|
C
|
gpl3
| 631
|
#ifndef FB_FILE_H
#define FB_FILE_H
#include <stdbool.h>
extern bool dashf(const char *file);
extern int fb_flock(int fd, int operation);
#endif // FB_FILE_H
|
zzlydm-fbbs
|
include/fbbs/file.h
|
C
|
gpl3
| 161
|
/*
* This file is part of the SSH Library
*
* Copyright (c) 2003,2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
/*
* crypto.h is an include file for internal cryptographic structures of libssh
*/
#ifndef _CRYPTO_H_
#define _CRYPTO_H_
#include "config.h"
#ifdef HAVE_LIBGCRYPT
#include <gcrypt.h>
#endif
#include "libssh/wrapper.h"
#ifdef cbc_encrypt
#undef cbc_encrypt
#endif
#ifdef cbc_decrypt
#undef cbc_decrypt
#endif
struct ssh_crypto_struct {
bignum e,f,x,k,y;
unsigned char session_id[SHA_DIGEST_LEN];
unsigned char encryptIV[SHA_DIGEST_LEN*2];
unsigned char decryptIV[SHA_DIGEST_LEN*2];
unsigned char decryptkey[SHA_DIGEST_LEN*2];
unsigned char encryptkey[SHA_DIGEST_LEN*2];
unsigned char encryptMAC[SHA_DIGEST_LEN];
unsigned char decryptMAC[SHA_DIGEST_LEN];
unsigned char hmacbuf[EVP_MAX_MD_SIZE];
struct crypto_struct *in_cipher, *out_cipher; /* the cipher structures/objects */
ssh_string server_pubkey;
const char *server_pubkey_type;
int do_compress_out; /* idem */
int do_compress_in; /* don't set them, set the option instead */
void *compress_out_ctx; /* don't touch it */
void *compress_in_ctx; /* really, don't */
};
struct crypto_struct {
const char *name; /* ssh name of the algorithm */
unsigned int blocksize; /* blocksize of the algo */
unsigned int keylen; /* length of the key structure */
#ifdef HAVE_LIBGCRYPT
gcry_cipher_hd_t *key;
#elif defined HAVE_LIBCRYPTO
void *key; /* a key buffer allocated for the algo */
#endif
unsigned int keysize; /* bytes of key used. != keylen */
#ifdef HAVE_LIBGCRYPT
/* sets the new key for immediate use */
int (*set_encrypt_key)(struct crypto_struct *cipher, void *key, void *IV);
int (*set_decrypt_key)(struct crypto_struct *cipher, void *key, void *IV);
void (*cbc_encrypt)(struct crypto_struct *cipher, void *in, void *out,
unsigned long len);
void (*cbc_decrypt)(struct crypto_struct *cipher, void *in, void *out,
unsigned long len);
#elif defined HAVE_LIBCRYPTO
/* sets the new key for immediate use */
int (*set_encrypt_key)(struct crypto_struct *cipher, void *key);
int (*set_decrypt_key)(struct crypto_struct *cipher, void *key);
void (*cbc_encrypt)(struct crypto_struct *cipher, void *in, void *out,
unsigned long len, void *IV);
void (*cbc_decrypt)(struct crypto_struct *cipher, void *in, void *out,
unsigned long len, void *IV);
#endif
};
/* vim: set ts=2 sw=2 et cindent: */
#endif /* _CRYPTO_H_ */
|
zzlydm-fbbs
|
include/libssh/crypto.h
|
C
|
gpl3
| 3,307
|
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#ifndef SOCKET_H_
#define SOCKET_H_
/* socket.c */
struct socket;
int ssh_socket_init(void);
struct socket *ssh_socket_new(ssh_session session);
void ssh_socket_free(struct socket *s);
void ssh_socket_set_fd(struct socket *s, socket_t fd);
socket_t ssh_socket_get_fd(struct socket *s);
#ifndef _WIN32
int ssh_socket_unix(struct socket *s, const char *path);
#endif
void ssh_socket_close(struct socket *s);
int ssh_socket_read(struct socket *s, void *buffer, int len);
int ssh_socket_write(struct socket *s,const void *buffer, int len);
int ssh_socket_is_open(struct socket *s);
int ssh_socket_fd_isset(struct socket *s, fd_set *set);
void ssh_socket_fd_set(struct socket *s, fd_set *set, int *fd_max);
int ssh_socket_completeread(struct socket *s, void *buffer, uint32_t len);
int ssh_socket_completewrite(struct socket *s, const void *buffer, uint32_t len);
int ssh_socket_wait_for_data(struct socket *s, ssh_session session, uint32_t len);
int ssh_socket_nonblocking_flush(struct socket *s);
int ssh_socket_blocking_flush(struct socket *s);
int ssh_socket_poll(struct socket *s, int *writeable, int *except);
void ssh_socket_set_towrite(struct socket *s);
void ssh_socket_set_toread(struct socket *s);
void ssh_socket_set_except(struct socket *s);
int ssh_socket_get_status(struct socket *s);
int ssh_socket_data_available(struct socket *s);
int ssh_socket_data_writable(struct socket *s);
#ifndef _WIN32
void ssh_execute_command(const char *command, socket_t in, socket_t out);
socket_t ssh_socket_connect_proxycommand(ssh_session session,
const char *command);
#endif
#endif /* SOCKET_H_ */
|
zzlydm-fbbs
|
include/libssh/socket.h
|
C
|
gpl3
| 2,472
|
/*
* This file is part of the SSH Library
*
* Copyright (c) 2009 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH Library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#ifndef STRING_H_
#define STRING_H_
#include "libssh/priv.h"
/* must be 32 bits number + immediately our data */
#ifdef _MSC_VER
#pragma pack(1)
#endif
struct ssh_string_struct {
uint32_t size;
unsigned char string[MAX_PACKET_LEN];
}
#if !defined(__SUNPRO_C) && !defined(_MSC_VER)
__attribute__ ((packed))
#endif
#ifdef _MSC_VER
#pragma pack()
#endif
;
#endif /* STRING_H_ */
|
zzlydm-fbbs
|
include/libssh/string.h
|
C
|
gpl3
| 1,249
|